<?php

session_start();
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

// التحقق من صلاحية التسعير/التعديل (استخدمت delete هنا كما في كودك الأصلي)
if (!can('shipments','delete')) {
    die('Access Denied');
}

$id = (int)($_GET['id'] ?? 0);
$currencies = $pdo->query("SELECT * FROM currencies")->fetchAll();

// جلب بيانات الشحنة مع أسماء العميل والوكيل
$stmt = $pdo->prepare("SELECT s.*, c.name as cust_name, a.name as agent_name 
                       FROM newshipments s 
                       JOIN customers c ON s.customer_id = c.customer_id
                       JOIN agents a ON s.agent_id = a.agent_id
                       WHERE s.shipment_id = ? AND s.pricing_status = 'pending'");
$stmt->execute([$id]);
$s = $stmt->fetch();

if (!$s) die("Error: Shipment already priced or not found.");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pdo->beginTransaction();
    try {
        $container_count = (int)$_POST['container_count'];
        $rate            = (float)$_POST['price_per_container'];
        $agent_unit_cost = (float)$_POST['agent_cost']; 
        
        // الحسابات الإجمالية
        $grand_total      = $container_count * $rate;            // إجمالي المبيعات
        $total_agent_cost = $container_count * $agent_unit_cost; // إجمالي التكاليف
        
        $currency_id = 1;
        $today       = date('Y-m-d');
        $user_id     = $_SESSION['user_id'];
        $shipment_id = $s['shipment_id']; // رقم الشحنة للترحيل

        // 1. تحديث بيانات الشحنة وتغيير حالتها إلى مكتملة
        $pdo->prepare("UPDATE newshipments SET container_count=?, price_per_container=?, agent_cost=?, grand_total=?, currency_id=?, pricing_status='completed' WHERE shipment_id=?")
            ->execute([$container_count, $rate, $agent_unit_cost, $grand_total, $currency_id, $shipment_id]);

        $desc = "B/L: {$s['bill_of_lading']} | Qty: $container_count | Unit Rate: $rate";

        // 2. ترحيل حساب العميل (Debit - مدين) مع رقم الشحنة
        $pdo->prepare("INSERT INTO customer_transactions (customer_id, shipment_id, debit, credit, trans_date, description, user_id) VALUES (?, ?, ?, 0, ?, ?, ?)")
            ->execute([$s['customer_id'], $shipment_id, $grand_total, $today, $desc, $user_id]);

        // 3. ترحيل حساب الوكيل (Credit - دائن) مع رقم الشحنة
        $pdo->prepare("INSERT INTO agent_transactions (agent_id, shipment_id, debit, credit, trans_date, description, user_id) VALUES (?, ?, 0, ?, ?, ?, ?)")
            ->execute([$s['agent_id'], $shipment_id, $total_agent_cost, $today, $desc, $user_id]);

        // 4. القيود اليومية (Daily Transactions) مع رقم الشحنة كـ Reference
        // ملاحظة: تأكد من وجود حقل shipment_id في جدول daily_transactions أيضاً إذا كنت ترغب في استخدامه هناك
        $pdo->prepare("INSERT INTO daily_transactions (trans_type, ref_id, shipment_id, debit, credit, trans_date, description, user_id) VALUES ('customer', ?, ?, ?, 0, ?, ?, ?)")
            ->execute([$s['customer_id'], $shipment_id, $grand_total, $today, $desc, $user_id]);

        $pdo->prepare("INSERT INTO daily_transactions (trans_type, ref_id, shipment_id, debit, credit, trans_date, description, user_id) VALUES ('agent', ?, ?, 0, ?, ?, ?, ?)")
            ->execute([$s['agent_id'], $shipment_id, $total_agent_cost, $today, $desc, $user_id]);

        $pdo->commit();
        header("Location: shipments.php?priced=1");
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        die("Fatal Error: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Finance | Shipment Pricing</title>
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <style>
        body { font-family: sans-serif; background: #f1f5f9; padding: 20px; }
        .pricing-card { max-width: 600px; margin: auto; background: white; border-radius: 12px; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); overflow: hidden; }
        .head { background: #0f172a; color: white; padding: 20px; }
        .info-box { padding: 15px; background: #f8fafc; border-bottom: 1px solid #e2e8f0; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 0.8rem; }
        .form-body { padding: 20px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; font-size: 0.85rem; color: #334155; }
        input, select { width: 100%; padding: 10px; margin-bottom: 15px; border: 2px solid #e2e8f0; border-radius: 8px; box-sizing: border-box; }
        .summary-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 20px; }
        .calc-box { padding: 10px; border-radius: 8px; text-align: center; font-size: 0.9rem; border: 1px solid #e2e8f0; }
        .box-customer { background: #ecfdf5; color: #065f46; border-color: #10b981; }
        .box-agent { background: #fff1f2; color: #9f1239; border-color: #fb7185; }
        .box-profit { background: #eff6ff; color: #1e40af; border-color: #3b82f6; grid-column: span 2; }
        .val { display: block; font-weight: 900; font-size: 1.2rem; }
        .btn-post { background: #059669; color: white; width: 100%; padding: 15px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 1rem; }
    </style>
</head>
<body>
    <div class="pricing-card">
        <div class="head">
            <h3 style="margin:0"><i class="fas fa-file-invoice-dollar"></i> Final Settlement</h3>
            <small>Shipment ID: #<?= $s['shipment_id'] ?></small>
        </div>
        
        <div class="info-box">
            <div><strong>Customer:</strong> <?= htmlspecialchars($s['cust_name']) ?></div>
            <div><strong>Agent:</strong> <?= htmlspecialchars($s['agent_name']) ?></div>
        </div>

        <form method="POST" class="form-body">
            <label>Container Count</label>
            <input type="number" name="container_count" id="count" value="<?= $s['container_count'] ?>" required oninput="calculateAll()">

            <label>Selling Rate (To Customer)</label>
            <input type="number" step="0.01" name="price_per_container" id="rate" placeholder="0.00" required oninput="calculateAll()">

            <label>Cost Rate (From Agent)</label>
            <input type="number" step="0.01" name="agent_cost" id="cost" placeholder="0.00" required oninput="calculateAll()">

            <label>Currency</label>
           <select name="currency_id_display" disabled>
    <?php foreach($currencies as $curr): ?> 
        <option value="<?= $curr['currency_id'] ?>" <?= $curr['currency_id'] == 1 ? 'selected' : '' ?>>
            <?= $curr['currency_name'] ?>
        </option> 
    <?php endforeach; ?>
</select>
<input type="hidden" name="currency_id" value="1">

            <div class="summary-grid">
                <div class="calc-box box-customer">
                    <small>Total Customer (Debit)</small>
                    <span class="val" id="total_cust">0.00</span>
                </div>
                <div class="calc-box box-agent">
                    <small>Total Agent (Credit)</small>
                    <span class="val" id="total_agent">0.00</span>
                </div>
                <div class="calc-box box-profit">
                    <small>Expected Net Profit</small>
                    <span class="val" id="profit">0.00</span>
                </div>
            </div>

            <button type="submit" class="btn-post">
                <i class="fas fa-check-double"></i> Confirm & Post to Ledgers
            </button>
        </form>
    </div>

    <script>
        function calculateAll() {
            const count = parseFloat(document.getElementById('count').value) || 0;
            const rate  = parseFloat(document.getElementById('rate').value) || 0;
            const cost  = parseFloat(document.getElementById('cost').value) || 0;

            const totalCust  = count * rate;
            const totalAgent = count * cost;
            const netProfit  = totalCust - totalAgent;

            document.getElementById('total_cust').innerText  = totalCust.toLocaleString(undefined, {minimumFractionDigits: 2});
            document.getElementById('total_agent').innerText = totalAgent.toLocaleString(undefined, {minimumFractionDigits: 2});
            document.getElementById('profit').innerText      = netProfit.toLocaleString(undefined, {minimumFractionDigits: 2});
        }
        window.onload = calculateAll;
    </script>
</body>
</html>