<?php
/**
 * helpers/midtrans_helper.php - Helper untuk Midtrans Payment
 * FULL VERSION - Lengkap dengan semua fungsi yang dibutuhkan
 * DIPERBAIKI - Memastikan gross_amount sesuai dengan jumlah DP
 */

// 🔥 LOAD AUTOLOAD
require_once __DIR__ . '/../vendor/autoload.php';

use Midtrans\Config;
use Midtrans\Snap;
use Midtrans\Notification;
use Midtrans\Transaction;

// ============================================
// 🔥 KONFIGURASI MIDTRANS
// ============================================

/**
 * Setup Midtrans Configuration
 */
function setupMidtrans() {
    // 🔥 Cek apakah file config ada
    $configFile = __DIR__ . '/../config/midtrans.php';
    
    if (!file_exists($configFile)) {
        // Fallback config jika file tidak ada
        Config::$serverKey = 'SB-Mid-server-xxxxxxxxxxxxxxxxxxxxxxxx';
        Config::$clientKey = 'SB-Mid-client-xxxxxxxxxxxxxxxxxxxxxxxx';
        Config::$isProduction = false;
        Config::$isSanitized = true;
        Config::$is3ds = true;
        
        // 🔥 Tambahkan timeout
        Config::$curlOptions = [
            CURLOPT_TIMEOUT => 60,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ];
        
        error_log("⚠️ Midtrans: Config file not found, using fallback config");
        return;
    }
    
    // 🔥 Load config dari file
    $config = require $configFile;
    
    if (is_array($config)) {
        Config::$serverKey = $config['server_key'] ?? 'SB-Mid-server-xxxxxxxxxxxxxxxxxxxxxxxx';
        Config::$clientKey = $config['client_key'] ?? 'SB-Mid-client-xxxxxxxxxxxxxxxxxxxxxxxx';
        Config::$isProduction = $config['is_production'] ?? false;
        Config::$isSanitized = true;
        Config::$is3ds = true;
    }
    
    // 🔥 Tambahkan timeout untuk curl
    Config::$curlOptions = [
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false, // Hanya untuk development
        CURLOPT_SSL_VERIFYHOST => false,
    ];
}

// ============================================
// 🔥 BUAT TRANSAKSI MIDTRANS
// ============================================

/**
 * Buat transaksi Snap Midtrans
 * DIPERBAIKI - Memastikan gross_amount sesuai dengan DP
 */
function createMidtransTransaction($orderData) {
    setupMidtrans();
    
    try {
        // 🔥 PASTIKAN GROSS_AMOUNT ADALAH INTEGER
        $grossAmount = (int) $orderData['gross_amount'];
        
        // 🔥 VALIDASI: gross_amount harus > 0
        if ($grossAmount <= 0) {
            throw new Exception('Gross amount harus lebih dari 0');
        }
        
        // 🔥 VALIDASI: order_id tidak boleh kosong
        if (empty($orderData['order_id'])) {
            throw new Exception('Order ID tidak boleh kosong');
        }
        
        // 🔥 BUILD ITEM DETAILS - HANYA ITEM YANG DIBAYAR
        $itemDetails = [];
        
        // 🔥 ITEM UTAMA (DP ATAU FULL)
        $jenisPembayaran = $orderData['jenis_pembayaran'] ?? 'full';
        $totalHarga = (int) ($orderData['total_harga'] ?? 0);
        $sisaPembayaran = (int) ($orderData['sisa_pembayaran'] ?? 0);
        
        if ($jenisPembayaran == 'dp') {
            // 🔥 DP: HANYA KIRIM JUMLAH DP
            $itemName = 'DP 50% - ' . ($orderData['kapal_nama'] ?? 'Booking Kapal');
            $itemDetails[] = [
                'id' => $orderData['pesanan_id'] . '-dp',
                'price' => $grossAmount,
                'quantity' => 1,
                'name' => $itemName . ' (Rp ' . number_format($grossAmount, 0, ',', '.') . ')'
            ];
            
            // 🔥 TAMBAHKAN ITEM SISA PEMBAYARAN DENGAN PRICE 0 (TIDAK DITAGIH)
            if ($sisaPembayaran > 0) {
                $itemDetails[] = [
                    'id' => $orderData['pesanan_id'] . '-sisa',
                    'price' => 0, // 🔥 PRICE 0 AGAR TIDAK DITAGIH
                    'quantity' => 1,
                    'name' => 'Sisa Pembayaran (akan dibayar nanti) - Rp ' . number_format($sisaPembayaran, 0, ',', '.')
                ];
            }
            
            // 🔥 TAMBAHKAN ITEM TOTAL HARGA (SEBAGAI INFORMASI)
            $itemDetails[] = [
                'id' => $orderData['pesanan_id'] . '-total',
                'price' => 0, // 🔥 PRICE 0 AGAR TIDAK DITAGIH
                'quantity' => 1,
                'name' => 'Total Harga: Rp ' . number_format($totalHarga, 0, ',', '.')
            ];
        } else {
            // 🔥 FULL: KIRIM TOTAL HARGA
            $itemName = 'Booking Kapal ' . ($orderData['kapal_nama'] ?? '');
            $itemDetails[] = [
                'id' => $orderData['pesanan_id'],
                'price' => $grossAmount,
                'quantity' => 1,
                'name' => $itemName
            ];
        }
        
        // 🔥 LOG UNTUK DEBUG
        midtransLog("Creating transaction", [
            'order_id' => $orderData['order_id'],
            'gross_amount' => $grossAmount,
            'jenis_pembayaran' => $jenisPembayaran,
            'total_harga' => $totalHarga,
            'sisa_pembayaran' => $sisaPembayaran,
            'item_details' => $itemDetails
        ]);
        
        $params = [
            'transaction_details' => [
                'order_id' => $orderData['order_id'],
                'gross_amount' => $grossAmount, // 🔥 INI YANG PENTING!
            ],
            'customer_details' => [
                'first_name' => $orderData['customer_name'] ?? 'Wisatawan',
                'email' => $orderData['customer_email'] ?? 'user@example.com',
                'phone' => $orderData['customer_phone'] ?? '08123456789',
            ],
            'item_details' => $itemDetails,
            'custom_field1' => $orderData['pesanan_id'] ?? '',
            'custom_field2' => $orderData['kapal_nama'] ?? '',
            'custom_field3' => $jenisPembayaran . '|' . ($sisaPembayaran ?? 0) . '|' . ($totalHarga ?? 0),
        ];
        
        // 🔥 Tambahkan callback URL
        $baseUrl = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/reservasi-kapal-wisata';
        $params['callbacks'] = [
            'finish' => $baseUrl . '/?page=payment&action=finish&order_id=' . $orderData['order_id'],
            'error' => $baseUrl . '/?page=payment&action=error&order_id=' . $orderData['order_id'],
            'pending' => $baseUrl . '/?page=payment&action=unfinish&order_id=' . $orderData['order_id'],
        ];
        
        // 🔥 Tambahkan enabled_payments jika ada
        $configFile = __DIR__ . '/../config/midtrans.php';
        if (file_exists($configFile)) {
            $config = require $configFile;
            if (is_array($config) && !empty($config['enable_payment'])) {
                $params['enabled_payments'] = $config['enable_payment'];
            }
        }
        
        // 🔥 Konfigurasi timeout
        Config::$curlOptions = [
            CURLOPT_TIMEOUT => 60,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ];
        
        $snapToken = Snap::getSnapToken($params);
        
        // 🔥 LOG SUKSES
        midtransLog("Transaction created successfully", [
            'order_id' => $orderData['order_id'],
            'gross_amount' => $grossAmount,
            'snap_token' => $snapToken
        ]);
        
        return [
            'success' => true,
            'token' => $snapToken,
            'params' => $params,
            'redirect_url' => 'https://app.sandbox.midtrans.com/snap/v2/vtweb/' . $snapToken,
            'gross_amount' => $grossAmount
        ];
        
    } catch (Exception $e) {
        error_log("Midtrans create transaction error: " . $e->getMessage());
        midtransLog("Error creating transaction", [
            'error' => $e->getMessage(),
            'order_data' => $orderData
        ]);
        
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// ============================================
// 🔥 HANDLE NOTIFICATION (WEBHOOK)
// ============================================

/**
 * Handle notification dari Midtrans
 */
function handleMidtransNotification() {
    setupMidtrans();
    
    try {
        $notification = new Notification();
        
        $orderId = $notification->order_id;
        $transactionStatus = $notification->transaction_status;
        $fraudStatus = $notification->fraud_status;
        $paymentType = $notification->payment_type;
        $grossAmount = $notification->gross_amount;
        $statusCode = $notification->status_code ?? '';
        $signatureKey = $notification->signature_key ?? '';
        
        // 🔥 Ambil kode pesanan dari order_id (format: BOOK-XXX-YYYYMMDD-timestamp)
        $parts = explode('-', $orderId);
        $kode_pesanan = $parts[0] . '-' . $parts[1] . '-' . $parts[2];
        
        // 🔥 LOG NOTIFIKASI
        midtransLog("Notification received", [
            'order_id' => $orderId,
            'kode_pesanan' => $kode_pesanan,
            'transaction_status' => $transactionStatus,
            'gross_amount' => $grossAmount
        ]);
        
        return [
            'success' => true,
            'order_id' => $orderId,
            'kode_pesanan' => $kode_pesanan,
            'transaction_status' => $transactionStatus,
            'fraud_status' => $fraudStatus,
            'payment_type' => $paymentType,
            'gross_amount' => $grossAmount,
            'status_code' => $statusCode,
            'signature_key' => $signatureKey,
            'raw' => $notification
        ];
        
    } catch (Exception $e) {
        error_log("Midtrans notification error: " . $e->getMessage());
        midtransLog("Error handling notification", [
            'error' => $e->getMessage()
        ]);
        
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// ============================================
// 🔥 VERIFY SIGNATURE (KEAMANAN)
// ============================================

/**
 * Verify Midtrans Signature
 */
function verifyMidtransSignature($orderId, $statusCode, $grossAmount, $signatureKey) {
    setupMidtrans();
    
    $serverKey = Config::$serverKey;
    
    // Format: order_id + status_code + gross_amount + server_key
    $signature = hash('sha512', $orderId . $statusCode . $grossAmount . $serverKey);
    
    $isValid = $signature === $signatureKey;
    
    midtransLog("Signature verification", [
        'order_id' => $orderId,
        'status_code' => $statusCode,
        'gross_amount' => $grossAmount,
        'is_valid' => $isValid
    ]);
    
    return $isValid;
}

// ============================================
// 🔥 CEK STATUS PEMBAYARAN
// ============================================

/**
 * Cek status transaksi di Midtrans
 */
function cekStatusMidtrans($kode_pesanan, $pdo) {
    setupMidtrans();
    
    try {
        // 🔥 Konfigurasi timeout
        Config::$curlOptions = [
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ];
        
        // 🔥 CEK KE MIDTRANS API
        $status = Transaction::status($kode_pesanan);
        
        if (!$status) {
            midtransLog("Status check failed", ['kode_pesanan' => $kode_pesanan]);
            return null;
        }
        
        $transactionStatus = $status->transaction_status ?? '';
        $fraudStatus = $status->fraud_status ?? null;
        $grossAmount = $status->gross_amount ?? 0;
        
        midtransLog("Status check result", [
            'kode_pesanan' => $kode_pesanan,
            'transaction_status' => $transactionStatus,
            'gross_amount' => $grossAmount
        ]);
        
        if ($transactionStatus == 'settlement' || $transactionStatus == 'capture') {
            // 🔥 UPDATE STATUS JADI LUNAS
            $stmt = $pdo->prepare("
                UPDATE pesanan 
                SET 
                    status_pembayaran = 'lunas',
                    status_pembayaran_admin = 'lunas',
                    status_pesanan = 'confirmed',
                    tanggal_bayar = NOW(),
                    tanggal_konfirmasi_pembayaran = NOW(),
                    notifikasi_dibaca = 0
                WHERE kode_pesanan = ? AND status_pembayaran != 'lunas'
            ");
            $stmt->execute([$kode_pesanan]);
            
            if ($stmt->rowCount() > 0) {
                // 🔥 KIRIM NOTIFIKASI KE WISATAWAN
                $stmtNotif = $pdo->prepare("
                    INSERT INTO notifications (user_id, title, message, booking_id, is_read) 
                    SELECT user_id, '✅ Pembayaran LUNAS', 
                           CONCAT('Pembayaran untuk pesanan ', kode_pesanan, ' telah LUNAS via Midtrans. Perjalanan dikonfirmasi.'),
                           id, 0
                    FROM pesanan 
                    WHERE kode_pesanan = ?
                ");
                $stmtNotif->execute([$kode_pesanan]);
                
                return 'lunas';
            }
        } elseif ($transactionStatus == 'deny' || $transactionStatus == 'expire' || $transactionStatus == 'cancel') {
            // 🔥 UPDATE STATUS JADI GAGAL
            $stmt = $pdo->prepare("
                UPDATE pesanan 
                SET 
                    status_pembayaran = 'gagal',
                    status_pembayaran_admin = 'gagal',
                    alasan_penolakan_pembayaran = ?
                WHERE kode_pesanan = ? AND status_pembayaran != 'lunas'
            ");
            $stmt->execute([$transactionStatus, $kode_pesanan]);
            
            return 'gagal';
        } elseif ($transactionStatus == 'pending') {
            return 'pending';
        }
        
        return null;
        
    } catch (Exception $e) {
        error_log("Midtrans status check error: " . $e->getMessage());
        midtransLog("Status check error", [
            'error' => $e->getMessage(),
            'kode_pesanan' => $kode_pesanan
        ]);
        return null;
    }
}

// ============================================
// 🔥 STATUS MAPPING
// ============================================

/**
 * Status mapping Midtrans ke status aplikasi
 */
function mapMidtransStatus($transactionStatus, $fraudStatus = null) {
    switch ($transactionStatus) {
        case 'capture':
            if ($fraudStatus === 'accept') {
                return 'success';
            }
            return 'pending';
        case 'settlement':
            return 'success';
        case 'pending':
            return 'pending';
        case 'deny':
            return 'failed';
        case 'cancel':
        case 'expire':
            return 'cancel';
        case 'refund':
            return 'refund';
        default:
            return 'unknown';
    }
}

// ============================================
// 🔥 SEND WHATSAPP (FONNTE)
// ============================================

/**
 * Send WhatsApp notification (via Fonnte)
 */
function sendWhatsApp($nomor, $pesan) {
    $fonnte_file = __DIR__ . '/../config/fonnte.php';
    
    if (!file_exists($fonnte_file)) {
        error_log("Fonnte config not found: " . $fonnte_file);
        return false;
    }
    
    require_once $fonnte_file;
    
    if (!function_exists('sendWhatsApp')) {
        error_log("Function sendWhatsApp not found");
        return false;
    }
    
    return sendWhatsApp($nomor, $pesan);
}

// ============================================
// 🔥 GET TRANSACTION STATUS
// ============================================

/**
 * Get transaction status dari Midtrans
 */
function getMidtransStatus($orderId) {
    setupMidtrans();
    
    try {
        Config::$curlOptions = [
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ];
        
        $status = Transaction::status($orderId);
        
        if (!$status) {
            return null;
        }
        
        return [
            'transaction_status' => $status->transaction_status ?? '',
            'fraud_status' => $status->fraud_status ?? null,
            'gross_amount' => $status->gross_amount ?? 0,
            'payment_type' => $status->payment_type ?? '',
            'status_code' => $status->status_code ?? '',
            'order_id' => $status->order_id ?? '',
            'transaction_id' => $status->transaction_id ?? '',
            'settlement_time' => $status->settlement_time ?? '',
            'pdf_url' => $status->pdf_url ?? '',
            'va_numbers' => $status->va_numbers ?? [],
            'permata_va_number' => $status->permata_va_number ?? '',
        ];
        
    } catch (Exception $e) {
        error_log("Get Midtrans status error: " . $e->getMessage());
        return null;
    }
}

// ============================================
// 🔥 LOGGING
// ============================================

/**
 * Log untuk debugging
 */
function midtransLog($message, $data = null) {
    $logFile = __DIR__ . '/../logs/midtrans_' . date('Y-m-d') . '.log';
    $logDir = dirname($logFile);
    
    if (!is_dir($logDir)) {
        mkdir($logDir, 0777, true);
    }
    
    $timestamp = date('Y-m-d H:i:s');
    $log = "[$timestamp] $message";
    if ($data !== null) {
        $log .= " - " . json_encode($data, JSON_PRETTY_PRINT);
    }
    $log .= "\n";
    
    file_put_contents($logFile, $log, FILE_APPEND);
}

// ============================================
// 🔥 GET CLIENT KEY
// ============================================

/**
 * Get Midtrans Client Key
 */
function getMidtransClientKey() {
    $configFile = __DIR__ . '/../config/midtrans.php';
    
    if (!file_exists($configFile)) {
        return 'SB-Mid-client-xxxxxxxxxxxxxxxxxxxxxxxx';
    }
    
    $config = require $configFile;
    
    if (is_array($config)) {
        return $config['client_key'] ?? 'SB-Mid-client-xxxxxxxxxxxxxxxxxxxxxxxx';
    }
    
    return 'SB-Mid-client-xxxxxxxxxxxxxxxxxxxxxxxx';
}

// ============================================
// 🔥 GET SERVER KEY
// ============================================

/**
 * Get Midtrans Server Key
 */
function getMidtransServerKey() {
    $configFile = __DIR__ . '/../config/midtrans.php';
    
    if (!file_exists($configFile)) {
        return 'SB-Mid-server-xxxxxxxxxxxxxxxxxxxxxxxx';
    }
    
    $config = require $configFile;
    
    if (is_array($config)) {
        return $config['server_key'] ?? 'SB-Mid-server-xxxxxxxxxxxxxxxxxxxxxxxx';
    }
    
    return 'SB-Mid-server-xxxxxxxxxxxxxxxxxxxxxxxx';
}

// ============================================
// 🔥 VALIDATE ORDER
// ============================================

/**
 * Validasi order di Midtrans
 */
function validateMidtransOrder($orderId, $pesananId, $pdo) {
    try {
        // Ambil data pesanan
        $stmt = $pdo->prepare("SELECT * FROM pesanan WHERE id = ?");
        $stmt->execute([$pesananId]);
        $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$pesanan) {
            return ['success' => false, 'message' => 'Pesanan tidak ditemukan'];
        }
        
        // Cek status
        if ($pesanan['status_pembayaran'] == 'lunas') {
            return ['success' => false, 'message' => 'Pesanan sudah lunas'];
        }
        
        // Cek snap token
        if (empty($pesanan['snap_token'])) {
            return ['success' => false, 'message' => 'Token pembayaran tidak ditemukan'];
        }
        
        // 🔥 CEK KE MIDTRANS
        $status = getMidtransStatus($orderId);
        
        if (!$status) {
            return ['success' => false, 'message' => 'Gagal cek status di Midtrans'];
        }
        
        return [
            'success' => true,
            'status' => $status,
            'pesanan' => $pesanan
        ];
        
    } catch (Exception $e) {
        error_log("Validate Midtrans order error: " . $e->getMessage());
        return ['success' => false, 'message' => $e->getMessage()];
    }
}
?>