<?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';

if (!can('shipments','edit')) {
    die('Access Denied');
}

$id = (int)($_GET['id'] ?? 0);

// جلب بيانات الشحنة
$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 = ?");
$stmt->execute([$id]);
$s = $stmt->fetch();

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

// تحديد ما إذا كان قد تم الترحيل مسبقاً
$is_added = ($s['extra_charges_vat_type'] === 'added');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pdo->beginTransaction();
    try {
        if (isset($_POST['reverse_action'])) {
            // --- منطق عكس العملية ---
            $pdo->prepare("UPDATE newshipments SET extra_charges=0, extra_charges_notes=NULL, extra_charges_vat_type='reverse' WHERE shipment_id=?")
                ->execute([$id]);

            $pdo->prepare("DELETE FROM customer_transactions WHERE shipment_id=? AND description LIKE 'Extra Charge%'")->execute([$id]);
            $pdo->prepare("DELETE FROM agent_transactions WHERE shipment_id=? AND description LIKE 'Extra Charge%'")->execute([$id]);
            $pdo->prepare("DELETE FROM daily_transactions WHERE shipment_id=? AND description LIKE 'Extra Charge%'")->execute([$id]);

        } else {
            // --- منطق ترحيل العملية ---
            $extra_amount = (float)$_POST['extra_charges'];
            $extra_notes  = trim($_POST['extra_charges_notes']);
            $vat_type     = 'added';

            $pdo->prepare("UPDATE newshipments SET extra_charges=?, extra_charges_notes=?, extra_charges_vat_type=? WHERE shipment_id=?")
                ->execute([$extra_amount, $extra_notes, $vat_type, $id]);

            $desc = "Extra Charge: " . $extra_notes;
            $today = date('Y-m-d');
            $uid = $_SESSION['user_id'];

            // ترحيل الحسابات
            $pdo->prepare("INSERT INTO customer_transactions (customer_id, shipment_id, debit, credit, trans_date, description, user_id) VALUES (?, ?, ?, 0, ?, ?, ?)")
                ->execute([$s['customer_id'], $id, $extra_amount, $today, $desc, $uid]);

            $pdo->prepare("INSERT INTO agent_transactions (agent_id, shipment_id, debit, credit, trans_date, description, user_id) VALUES (?, ?, 0, ?, ?, ?, ?)")
                ->execute([$s['agent_id'], $id, $extra_amount, $today, $desc, $uid]);

            // اليومية العامة
            $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'], $id, $extra_amount, $today, $desc, $uid]);
            $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'], $id, $extra_amount, $today, $desc, $uid]);
        }

        $pdo->commit();
        header("Location: shipment_pricing_add.php?id=$id&success=1");
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        die("Error: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Extra Charges Manager</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #f0f2f5; padding: 40px; color: #333; }
        .card { max-width: 500px; margin: auto; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); }
        
        /* تنسيق رابط العودة العلوي */
        .back-link { display: inline-block; margin-bottom: 15px; color: #64748b; text-decoration: none; font-size: 14px; }
        .back-link:hover { color: #1e293b; text-decoration: underline; }

        .status-badge { display: inline-block; padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; margin-bottom: 15px; }
        .status-added { background: #dcfce7; color: #166534; }
        .status-pending { background: #fef3c7; color: #92400e; }
        h3 { margin-top: 0; color: #1e293b; border-bottom: 1px solid #e5e7eb; padding-bottom: 10px; }
        .info-row { font-size: 14px; color: #64748b; margin-bottom: 20px; }
        label { display: block; margin: 15px 0 5px; font-weight: 600; font-size: 14px; }
        input, textarea { width: 100%; padding: 12px; border: 1px solid #cbd5e1; border-radius: 8px; box-sizing: border-box; background: #fff; }
        input:disabled, textarea:disabled { background: #f8fafc; cursor: not-allowed; color: #94a3b8; }
        
        .btn { width: 100%; padding: 14px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 15px; margin-top: 15px; transition: 0.3s; display: block; text-align: center; text-decoration: none; box-sizing: border-box; }
        .btn-submit { background: #2563eb; color: white; }
        .btn-submit:hover { background: #1d4ed8; }
        .btn-reverse { background: #ef4444; color: white; }
        .btn-reverse:hover { background: #dc2626; }
        
        /* تنسيق زر العودة/الإلغاء السفلي */
        .btn-back { background: #f1f5f9; color: #475569; margin-top: 10px; border: 1px solid #e2e8f0; }
        .btn-back:hover { background: #e2e8f0; }
    </style>
</head>
<body>

<div class="card">
    <a href="shipments.php" class="back-link">← Back to Shipments</a>

    <div class="status-badge <?= $is_added ? 'status-added' : 'status-pending' ?>">
        Status: <?= $is_added ? 'ADDED TO LEDGER' : 'PENDING / REVERSED' ?>
    </div>
    
    <h3>Shipment Extra Charges #<?= $id ?></h3>
    
    <div class="info-row">
        Customer: <strong><?= $s['cust_name'] ?></strong><br>
        Agent: <strong><?= $s['agent_name'] ?></strong>
    </div>

    <form method="POST">
        <label>Extra Amount (USD)</label>
        <input type="number" step="0.01" name="extra_charges" 
               value="<?= $s['extra_charges'] ?>" 
               <?= $is_added ? 'disabled' : 'required' ?> placeholder="0.00">

        <label>Description / Notes</label>
        <textarea name="extra_charges_notes" rows="3" 
                  <?= $is_added ? 'disabled' : 'required' ?> 
                  placeholder="Reason for extra charges..."><?= $s['extra_charges_notes'] ?></textarea>

        <?php if ($is_added): ?>
            <input type="hidden" name="extra_charges_vat_type" value="added">
            <button type="submit" name="reverse_action" class="btn btn-reverse">
                Reverse Transaction (Back to Open)
            </button>
        <?php else: ?>
            <input type="hidden" name="extra_charges_vat_type" value="added">
            <button type="submit" class="btn btn-submit">
                Post to Financial Ledgers
            </button>
        <?php endif; ?>

        <a href="shipments.php" class="btn btn-back">Return to Shipments List</a>
    </form>
</div>

</body>
</html>