<?php
// create_payment.php - Buat transaksi Midtrans

// 🔥 KONEKSI DATABASE MANUAL
$host = 'localhost';
$dbname = 'platform_kapal_samosir';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage());
}

$pesanan_id = $argv[1] ?? 0;

if ($pesanan_id <= 0) {
    echo "❌ Gunakan: php create_payment.php <pesanan_id>\n";
    exit;
}

// Ambil data pesanan
$stmt = $pdo->prepare("SELECT * FROM pesanan WHERE id = ?");
$stmt->execute([$pesanan_id]);
$pesanan = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$pesanan) {
    echo "❌ Pesanan tidak ditemukan!\n";
    exit;
}

if (!empty($pesanan['snap_token'])) {
    echo "✅ Snap token sudah ada: " . $pesanan['snap_token'] . "\n";
    exit;
}

echo "\n========================================\n";
echo "   💳 PROSES PEMBAYARAN MIDTRANS\n";
echo "========================================\n\n";

echo "📋 Data Pesanan:\n";
echo "   Kode    : " . $pesanan['kode_pesanan'] . "\n";
echo "   Total   : Rp " . number_format($pesanan['total_harga'], 0, ',', '.') . "\n";
echo "   Kapal   : " . $pesanan['nama_kapal'] . "\n\n";

// 🔥 LOAD MIDTRANS
require_once 'helpers/midtrans_helper.php';
setupMidtrans();

$orderData = [
    'order_id' => $pesanan['kode_pesanan'] . '-' . time(),
    'gross_amount' => (int) $pesanan['total_harga'],
    'customer_name' => $pesanan['nama_lengkap'] ?? 'Wisatawan',
    'customer_email' => 'wisatawan@example.com',
    'customer_phone' => $pesanan['no_hp'] ?? '08123456789',
    'item_details' => [
        [
            'id' => 'ROUTE-' . ($pesanan['route_id'] ?? '0'),
            'price' => (int) $pesanan['total_harga'],
            'quantity' => 1,
            'name' => 'Sewa Kapal ' . ($pesanan['nama_kapal'] ?? 'Kapal Wisata')
        ]
    ],
    'pesanan_id' => $pesanan['id'],
    'kapal_nama' => $pesanan['nama_kapal']
];

$result = createMidtransTransaction($orderData);

if ($result['success']) {
    $stmt = $pdo->prepare("UPDATE pesanan SET snap_token = ? WHERE id = ?");
    $stmt->execute([$result['token'], $pesanan['id']]);
    
    echo "✅ Snap token berhasil dibuat!\n";
    echo "   Token : " . $result['token'] . "\n";
    echo "   URL   : " . $result['redirect_url'] . "\n\n";
    echo "📌 Buka URL di browser untuk bayar\n";
    echo "   start " . $result['redirect_url'] . "\n";
    
} else {
    echo "❌ ERROR: " . $result['error'] . "\n";
}

echo "========================================\n";