<?php
// update_pencairan.php - Update nominal pesanan yang sudah cair

$pdo = new PDO('mysql:host=localhost;dbname=platform_kapal_samosir;charset=utf8mb4', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "========================================\n";
echo "   UPDATE NOMINAL PENCAIRAN\n";
echo "========================================\n\n";

// Cek pesanan ID 1
$stmt = $pdo->prepare("SELECT id, kode_pesanan, total_harga, komisi_admin, nominal_diterima_supir, status_pencairan FROM pesanan WHERE id = ?");
$stmt->execute([1]);
$pesanan = $stmt->fetch(PDO::FETCH_ASSOC);

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

echo "📋 Data Pesanan ID 1:\n";
echo "   Kode: {$pesanan['kode_pesanan']}\n";
echo "   Total Harga: Rp " . number_format($pesanan['total_harga'], 0, ',', '.') . "\n";
echo "   Komisi Admin: Rp " . number_format($pesanan['komisi_admin'] ?? 0, 0, ',', '.') . "\n";
echo "   Diterima Supir: Rp " . number_format($pesanan['nominal_diterima_supir'] ?? 0, 0, ',', '.') . "\n";
echo "   Status: {$pesanan['status_pencairan']}\n\n";

// 🔥 UPDATE
if ($pesanan['nominal_diterima_supir'] == 0 || $pesanan['nominal_diterima_supir'] == null) {
    $total = $pesanan['total_harga'];
    $komisi = round($total * 10 / 100); // 10% komisi
    $diterima = $total - $komisi;
    
    $stmt = $pdo->prepare("UPDATE pesanan SET komisi_admin = ?, nominal_diterima_supir = ? WHERE id = ?");
    $stmt->execute([$komisi, $diterima, 1]);
    
    echo "✅ Pesanan ID 1 berhasil diupdate!\n";
    echo "   Komisi Admin: Rp " . number_format($komisi, 0, ',', '.') . "\n";
    echo "   Diterima Supir: Rp " . number_format($diterima, 0, ',', '.') . "\n\n";
} else {
    echo "✅ Pesanan ID 1 sudah memiliki nominal yang benar.\n\n";
}

// CEK HASIL AKHIR
echo "📊 HASIL AKHIR:\n";
$stmt = $pdo->query("SELECT id, kode_pesanan, total_harga, komisi_admin, nominal_diterima_supir, status_pencairan FROM pesanan WHERE id = 1");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo "   ID: {$row['id']}\n";
echo "   Kode: {$row['kode_pesanan']}\n";
echo "   Total: Rp " . number_format($row['total_harga'], 0, ',', '.') . "\n";
echo "   Komisi: Rp " . number_format($row['komisi_admin'], 0, ',', '.') . "\n";
echo "   Diterima Supir: Rp " . number_format($row['nominal_diterima_supir'], 0, ',', '.') . "\n";
echo "   Status: {$row['status_pencairan']}\n";

echo "\n========================================\n";
echo "✅ SELESAI!\n";
echo "========================================\n";