<?php
/**
 * PaymentController.php - Handle Callback/Notification dari Midtrans
 * URL: ?page=payment&action=notification (POST dari Midtrans)
 */

class PaymentController {
    private $pdo;
    private $debugMode = true;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    /**
     * Helper: Log untuk debugging
     */
    private function log($message, $data = null) {
        if ($this->debugMode) {
            $log = date('Y-m-d H:i:s') . " - " . $message;
            if ($data !== null) {
                $log .= " - " . json_encode($data);
            }
            error_log($log);
            
            // Simpan ke file log
            $logFile = __DIR__ . '/../logs/midtrans_' . date('Y-m-d') . '.log';
            $dir = dirname($logFile);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            file_put_contents($logFile, $log . "\n", FILE_APPEND);
        }
    }
    
    /**
     * Helper: Get column names from a table
     */
    private function getTableColumns($table) {
        try {
            $stmt = $this->pdo->query("SHOW COLUMNS FROM $table");
            return $stmt->fetchAll(PDO::FETCH_COLUMN);
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * Helper: Kirim notifikasi WhatsApp
     */
    private function sendWhatsAppNotification($nomor, $pesan) {
        $fonnte_file = __DIR__ . '/../config/fonnte.php';
        if (!file_exists($fonnte_file)) {
            $this->log("❌ File fonnte.php tidak ditemukan");
            return false;
        }
        
        require_once $fonnte_file;
        
        if (!function_exists('sendWhatsApp')) {
            $this->log("❌ Fungsi sendWhatsApp tidak ditemukan");
            return false;
        }
        
        return sendWhatsApp($nomor, $pesan);
    }
    
    /**
     * ================================================================
     * NOTIFICATION - Handle callback dari Midtrans
     * URL: ?page=payment&action=notification
     * METHOD: POST (dari Midtrans)
     * ================================================================
     */
    public function notification() {
        // Log request yang masuk
        $this->log("📩 Notification received", $_POST);
        
        try {
            // Load Midtrans helper
            require_once __DIR__ . '/../helpers/midtrans_helper.php';
            
            // Handle notifikasi
            $result = handleMidtransNotification();
            
            $this->log("📊 Notification result", $result);
            
            if (!$result['success']) {
                $this->log("❌ Notification error: " . ($result['error'] ?? 'Unknown error'));
                http_response_code(400);
                echo 'Invalid notification';
                exit;
            }
            
            $order_id = $result['order_id'];
            $transactionStatus = $result['transaction_status'];
            $fraudStatus = $result['fraud_status'] ?? null;
            $paymentType = $result['payment_type'] ?? 'unknown';
            $grossAmount = $result['gross_amount'] ?? 0;
            
            // Ambil kode pesanan dari order_id (format: KODE_PESANAN-timestamp)
            $parts = explode('-', $order_id);
            // Ambil 3 bagian pertama sebagai kode pesanan (BOOK-XXXXX-YYYYMMDD)
            $kode_pesanan = $parts[0] . '-' . $parts[1] . '-' . $parts[2];
            
            $this->log("🔍 Extracted order_id: $order_id, kode_pesanan: $kode_pesanan");
            
            // Cari pesanan berdasarkan kode_pesanan
            $stmt = $this->pdo->prepare("
                SELECT p.*, k.pemilik_id, k.nama_kapal, u.nama as wisatawan_nama, u.no_hp as wisatawan_hp
                FROM pesanan p
                LEFT JOIN kapal k ON p.kapal_id = k.id
                LEFT JOIN users u ON p.user_id = u.id
                WHERE p.kode_pesanan = ?
            ");
            $stmt->execute([$kode_pesanan]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$pesanan) {
                $this->log("❌ Order not found: $kode_pesanan");
                http_response_code(404);
                echo 'Order not found';
                exit;
            }
            
            $this->log("📋 Pesanan ditemukan", ['id' => $pesanan['id'], 'status' => $pesanan['status_pembayaran']]);
            
            // Cek apakah sudah diproses sebelumnya
            if ($pesanan['status_pembayaran'] == 'lunas') {
                $this->log("⚠️ Order already paid: $kode_pesanan");
                echo 'OK (already paid)';
                exit;
            }
            
            // ==============================================
            // PROSES STATUS PEMBAYARAN
            // ==============================================
            $paymentStatus = 'belum_bayar';
            $pesananStatus = 'pending';
            $message = '';
            $isSuccess = false;
            
            // Mapping status Midtrans
            switch ($transactionStatus) {
                case 'capture':
                    if ($fraudStatus === 'accept') {
                        // Pembayaran berhasil (capture)
                        $paymentStatus = 'lunas';
                        $pesananStatus = 'confirmed';
                        $message = '✅ Pembayaran berhasil! Pesanan Anda telah dikonfirmasi.';
                        $isSuccess = true;
                        $this->log("✅ Payment captured and accepted");
                    } else {
                        // Fraud challenge
                        $paymentStatus = 'menunggu_konfirmasi';
                        $pesananStatus = 'pending';
                        $message = '⏳ Pembayaran dalam proses verifikasi anti-fraud.';
                        $this->log("⚠️ Payment captured but fraud challenge");
                    }
                    break;
                    
                case 'settlement':
                    // Pembayaran berhasil (settlement)
                    $paymentStatus = 'lunas';
                    $pesananStatus = 'confirmed';
                    $message = '✅ Pembayaran berhasil! Pesanan Anda telah dikonfirmasi.';
                    $isSuccess = true;
                    $this->log("✅ Payment settled");
                    break;
                    
                case 'pending':
                    // Menunggu pembayaran
                    $paymentStatus = 'menunggu_konfirmasi';
                    $pesananStatus = 'pending';
                    $message = '⏳ Pembayaran sedang diproses. Mohon tunggu konfirmasi.';
                    $this->log("⏳ Payment pending");
                    break;
                    
                case 'deny':
                    // Pembayaran ditolak
                    $paymentStatus = 'gagal';
                    $pesananStatus = 'pending';
                    $message = '❌ Pembayaran ditolak. Silakan coba lagi dengan metode lain.';
                    $this->log("❌ Payment denied");
                    break;
                    
                case 'cancel':
                    // Pembayaran dibatalkan
                    $paymentStatus = 'gagal';
                    $pesananStatus = 'cancelled';
                    $message = '❌ Pembayaran dibatalkan. Silakan lakukan pemesanan ulang.';
                    $this->log("❌ Payment cancelled");
                    break;
                    
                case 'expire':
                    // Pembayaran expired
                    $paymentStatus = 'gagal';
                    $pesananStatus = 'pending';
                    $message = '⏰ Waktu pembayaran habis. Silakan lakukan pembayaran ulang.';
                    $this->log("⏰ Payment expired");
                    break;
                    
                case 'refund':
                    // Pembayaran di-refund
                    $paymentStatus = 'gagal';
                    $pesananStatus = 'cancelled';
                    $message = '💰 Pembayaran di-refund. Dana akan dikembalikan.';
                    $this->log("💰 Payment refunded");
                    break;
                    
                default:
                    $paymentStatus = 'belum_bayar';
                    $pesananStatus = 'pending';
                    $message = 'Status pembayaran tidak diketahui. Silakan hubungi admin.';
                    $this->log("❓ Unknown payment status: $transactionStatus");
                    break;
            }
            
            // ==============================================
            // UPDATE DATABASE
            // ==============================================
            $columns = $this->getTableColumns('pesanan');
            
            $sql = "UPDATE pesanan SET 
                    status_pembayaran = ?,
                    status_pesanan = ?,
                    payment_type = ?,
                    payment_gross_amount = ?,
                    payment_status = ?";
            $params = [
                $paymentStatus,
                $pesananStatus,
                $paymentType,
                $grossAmount,
                $transactionStatus
            ];
            
            // Tambahkan snap_token jika ada
            if (in_array('snap_token', $columns)) {
                $sql .= ", snap_token = NULL";
            }
            
            // Jika sukses, tambahkan tanggal konfirmasi
            if ($isSuccess) {
                if (in_array('tanggal_konfirmasi_pembayaran', $columns)) {
                    $sql .= ", tanggal_konfirmasi_pembayaran = NOW()";
                }
                if (in_array('tanggal_bayar', $columns)) {
                    $sql .= ", tanggal_bayar = NOW()";
                }
            }
            
            $sql .= " WHERE id = ?";
            $params[] = $pesanan['id'];
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            
            $this->log("✅ Database updated", ['status' => $paymentStatus, 'pesanan_status' => $pesananStatus]);
            
            // ==============================================
            // KIRIM NOTIFIKASI
            // ==============================================
            
            // 1. Notifikasi ke Wisatawan (Aplikasi)
            try {
                $stmt = $this->pdo->prepare("
                    INSERT INTO notifications (user_id, title, message, booking_id, is_read, created_at)
                    VALUES (?, ?, ?, ?, 0, NOW())
                ");
                $stmt->execute([
                    $pesanan['user_id'],
                    $isSuccess ? '✅ Pembayaran Berhasil' : '📱 Pembayaran Midtrans',
                    $message . ' Kode: ' . $pesanan['kode_pesanan'],
                    $pesanan['id']
                ]);
                $this->log("✅ Notification sent to user: " . $pesanan['user_id']);
            } catch (Exception $e) {
                $this->log("❌ Failed to send notification: " . $e->getMessage());
            }
            
            // 2. Notifikasi WhatsApp ke Wisatawan (jika sukses)
            if ($isSuccess && !empty($pesanan['wisatawan_hp'])) {
                try {
                    $wa_msg = "
✅ *PEMBAYARAN BERHASIL* ✅

Halo *{$pesanan['wisatawan_nama']}*,

Pembayaran untuk pesanan *{$pesanan['kode_pesanan']}* telah berhasil!

📅 Tanggal: " . date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) . "
⛵ Kapal: {$pesanan['nama_kapal']}
💰 Total: Rp " . number_format($pesanan['total_harga'], 0, ',', '.') . "
💳 Metode: " . strtoupper($paymentType) . "

📌 Status: *LUNAS*
Pesanan Anda telah dikonfirmasi!

Silakan cek aplikasi untuk detail lebih lanjut.

Terima kasih telah menggunakan layanan kami. 🌊⛵
";
                    $this->sendWhatsAppNotification($pesanan['wisatawan_hp'], $wa_msg);
                    $this->log("✅ WhatsApp sent to wisatawan: " . $pesanan['wisatawan_hp']);
                } catch (Exception $e) {
                    $this->log("❌ Failed to send WhatsApp: " . $e->getMessage());
                }
            }
            
            // 3. Notifikasi ke Supir (Pemilik Kapal) jika sukses
            if ($isSuccess && !empty($pesanan['pemilik_id'])) {
                try {
                    $stmt = $this->pdo->prepare("
                        INSERT INTO notifications (user_id, title, message, booking_id, is_read, created_at)
                        VALUES (?, ?, ?, ?, 0, NOW())
                    ");
                    $msg_supir = "✅ Pembayaran untuk pesanan {$pesanan['kode_pesanan']} telah LUNAS.\n\n" .
                                 "👤 Wisatawan: {$pesanan['wisatawan_nama']}\n" .
                                 "⛵ Kapal: {$pesanan['nama_kapal']}\n" .
                                 "📅 Tanggal: " . date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) . "\n" .
                                 "💰 Total: Rp " . number_format($pesanan['total_harga'], 0, ',', '.') . "\n\n" .
                                 "📌 Pesanan siap untuk dijadwalkan.";
                    $stmt->execute([
                        $pesanan['pemilik_id'],
                        '✅ Pembayaran Lunas - Pesanan Siap',
                        $msg_supir,
                        $pesanan['id']
                    ]);
                    $this->log("✅ Notification sent to supir: " . $pesanan['pemilik_id']);
                } catch (Exception $e) {
                    $this->log("❌ Failed to send notification to supir: " . $e->getMessage());
                }
                
                // 4. WhatsApp ke Supir
                try {
                    // Ambil no HP supir
                    $stmt = $this->pdo->prepare("SELECT no_hp, nama FROM users WHERE id = ?");
                    $stmt->execute([$pesanan['pemilik_id']]);
                    $supir = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($supir && !empty($supir['no_hp'])) {
                        $wa_msg_supir = "
✅ *PEMBAYARAN LUNAS* ✅

Halo *{$supir['nama']}*,

Pembayaran untuk pesanan berikut telah LUNAS:

📌 Kode: *{$pesanan['kode_pesanan']}*
👤 Wisatawan: {$pesanan['wisatawan_nama']}
⛵ Kapal: {$pesanan['nama_kapal']}
📅 Tanggal: " . date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) . "
💰 Total: Rp " . number_format($pesanan['total_harga'], 0, ',', '.') . "

📌 Segera verifikasi dan jadwalkan perjalanan.

Terima kasih! 🌊
";
                        $this->sendWhatsAppNotification($supir['no_hp'], $wa_msg_supir);
                        $this->log("✅ WhatsApp sent to supir: " . $supir['no_hp']);
                    }
                } catch (Exception $e) {
                    $this->log("❌ Failed to send WhatsApp to supir: " . $e->getMessage());
                }
            }
            
            // ==============================================
            // RESPONSE KE MIDTRANS
            // ==============================================
            echo 'OK';
            $this->log("✅ Notification processed successfully");
            
        } catch (Exception $e) {
            $this->log("❌ Fatal error: " . $e->getMessage(), $e->getTrace());
            http_response_code(500);
            echo 'Error: ' . $e->getMessage();
        }
    }
    
    /**
     * ================================================================
     * FINISH - Halaman sukses dari Midtrans (redirect)
     * URL: ?page=payment&action=finish
     * ================================================================
     */
    public function finish() {
        $this->log("🎉 Payment finish page accessed", $_GET);
        
        $order_id = $_GET['order_id'] ?? '';
        $status_code = $_GET['status_code'] ?? '';
        $transaction_status = $_GET['transaction_status'] ?? '';
        
        if (empty($order_id)) {
            $_SESSION['flash_error'] = 'Data pembayaran tidak lengkap.';
            header('Location: ?page=wisatawan&action=pesananSaya');
            exit;
        }
        
        // Ambil kode pesanan dari order_id
        $parts = explode('-', $order_id);
        $kode_pesanan = $parts[0] . '-' . $parts[1] . '-' . $parts[2];
        
        // 🔥🔥🔥 TAMBAHKAN INI! UPDATE STATUS JADI LUNAS!
        try {
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET 
                    status_pembayaran = 'lunas',
                    status_pembayaran_admin = 'dikonfirmasi',
                    status_pesanan = 'confirmed',
                    tanggal_bayar = NOW(),
                    tanggal_konfirmasi_pembayaran = NOW()
                WHERE kode_pesanan = ? AND status_pembayaran != 'lunas'
            ");
            $stmt->execute([$kode_pesanan]);
            $this->log("✅ Status updated to LUNAS for: " . $kode_pesanan);
        } catch (Exception $e) {
            $this->log("❌ Failed to update status: " . $e->getMessage());
        }
        
        // Cari pesanan
        $stmt = $this->pdo->prepare("SELECT id FROM pesanan WHERE kode_pesanan = ?");
        $stmt->execute([$kode_pesanan]);
        $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($pesanan) {
            // Redirect ke halaman sukses wisatawan
            header('Location: ?page=wisatawan&action=pembayaranSukses&id=' . $pesanan['id'] . '&order_id=' . $order_id);
        } else {
            $_SESSION['flash_error'] = 'Pesanan tidak ditemukan.';
            header('Location: ?page=wisatawan&action=pesananSaya');
        }
        exit;
    }
    
    /**
     * ================================================================
     * UNFINISH - Halaman pending dari Midtrans (redirect)
     * URL: ?page=payment&action=unfinish
     * ================================================================
     */
    public function unfinish() {
        $this->log("⏳ Payment unfinish page accessed", $_GET);
        
        $order_id = $_GET['order_id'] ?? '';
        
        if (empty($order_id)) {
            $_SESSION['flash_error'] = 'Data pembayaran tidak lengkap.';
            header('Location: ?page=wisatawan&action=pesananSaya');
            exit;
        }
        
        // Ambil kode pesanan dari order_id
        $parts = explode('-', $order_id);
        $kode_pesanan = $parts[0] . '-' . $parts[1] . '-' . $parts[2];
        
        // Cari pesanan
        $stmt = $this->pdo->prepare("SELECT id FROM pesanan WHERE kode_pesanan = ?");
        $stmt->execute([$kode_pesanan]);
        $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($pesanan) {
            // Redirect ke halaman pending wisatawan
            header('Location: ?page=wisatawan&action=pembayaranPending&id=' . $pesanan['id'] . '&order_id=' . $order_id);
        } else {
            $_SESSION['flash_error'] = 'Pesanan tidak ditemukan.';
            header('Location: ?page=wisatawan&action=pesananSaya');
        }
        exit;
    }
    
    /**
     * ================================================================
     * ERROR - Halaman error dari Midtrans (redirect)
     * URL: ?page=payment&action=error
     * ================================================================
     */
    public function error() {
        $this->log("❌ Payment error page accessed", $_GET);
        
        $order_id = $_GET['order_id'] ?? '';
        $status_code = $_GET['status_code'] ?? '';
        
        $_SESSION['flash_error'] = 'Terjadi kesalahan dalam pembayaran. Kode: ' . $status_code;
        
        if (!empty($order_id)) {
            // Ambil kode pesanan dari order_id
            $parts = explode('-', $order_id);
            $kode_pesanan = $parts[0] . '-' . $parts[1] . '-' . $parts[2];
            
            $stmt = $this->pdo->prepare("SELECT id FROM pesanan WHERE kode_pesanan = ?");
            $stmt->execute([$kode_pesanan]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($pesanan) {
                header('Location: ?page=wisatawan&action=status&id=' . $pesanan['id']);
                exit;
            }
        }
        
        header('Location: ?page=wisatawan&action=pesananSaya');
        exit;
    }
}
?>