<?php
// update_pembayaran_sukses.php - Update method pembayaranSukses

$file = 'controllers/WisatawanController.php';
$content = file_get_contents($file);

// Cari method pembayaranSukses
$search = '/public function pembayaranSukses\(\) \{.*?\n    \}/s';
preg_match($search, $content, $matches);

if (!empty($matches[0])) {
    $newMethod = 'public function pembayaranSukses() {
        $pesanan_id = (int) ($_GET[\'id\'] ?? 0);
        $order_id = $_GET[\'order_id\'] ?? \'\';
        $user_id = $_SESSION[\'user_id\'];
        $user = $this->getUserData($user_id);
        $unreadCount = $this->getUnreadCount($user_id);
        
        // 🔥 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 id = ? AND status_pembayaran != \'lunas\'");
            $stmt->execute([$pesanan_id]);
            if ($stmt->rowCount() > 0) {
                try {
                    $stmtNotif = $this->pdo->prepare("INSERT INTO notifications (user_id, title, message, booking_id, is_read, created_at) SELECT user_id, \'✅ Pembayaran LUNAS\', CONCAT(\'Pembayaran untuk pesanan \', kode_pesanan, \' telah LUNAS. Perjalanan dikonfirmasi.\'), id, 0, NOW() FROM pesanan WHERE id = ?");
                    $stmtNotif->execute([$pesanan_id]);
                } catch (Exception $e) {}
            }
        } catch (Exception $e) {}

        try {
            $stmt = $this->pdo->prepare("SELECT p.*, k.nama_kapal FROM pesanan p LEFT JOIN kapal k ON p.kapal_id = k.id WHERE p.id = ? AND p.user_id = ?");
            $stmt->execute([$pesanan_id, $user_id]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$pesanan) { throw new Exception(\'Pesanan tidak ditemukan.\'); }
            $this->loadView(\'pembayaran_sukses\', [\'user_id\' => $user_id, \'user\' => $user, \'unreadCount\' => $unreadCount, \'pesanan\' => $pesanan, \'activeMenu\' => \'riwayatPesanan\']);
        } catch (Exception $e) {
            $_SESSION[\'flash_error\'] = $e->getMessage();
            header(\'Location: ?page=wisatawan&action=pesananSaya\');
            exit;
        }
    }';
    
    $content = str_replace($matches[0], $newMethod, $content);
    file_put_contents($file, $content);
    echo "✅ Method pembayaranSukses() berhasil diupdate!" . PHP_EOL;
} else {
    echo "❌ Method pembayaranSukses() tidak ditemukan!" . PHP_EOL;
}