<?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','delete')) {
    die('Access Denied');
}

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

if ($id > 0) {
    $pdo->beginTransaction();
    try {
        // 1. جلب بيانات الشحنة الحالية قبل إلغائها لعكس مبالغها بدقة
        $stmt = $pdo->prepare("SELECT * FROM newshipments WHERE shipment_id = ?");
        $stmt->execute([$id]);
        $shipment = $stmt->fetch();

        if (!$shipment) {
            throw new Exception("Shipment not found.");
        }

        if ($shipment['status'] === 'Inactive') {
            throw new Exception("Shipment is already Inactive.");
        }

        $user_id = (int)($_SESSION['user_id'] ?? 0);
        $today   = date('Y-m-d');
        $cancel_desc = "CANCELLED: Shipment ID: $id | B/L: " . $shipment['bill_of_lading'];

        /* ========= عكس مالي للعميل (Credit بدلاً من Debit) ========= */
        // العميل كان مديناً (Debit)، الآن نجعله دائناً (Credit) بنفس المبلغ لإطفاء الدين
        $pdo->prepare("
            INSERT INTO customer_transactions 
            (customer_id, debit, credit, trans_date, description, user_id) 
            VALUES (?, 0, ?, ?, ?, ?)
        ")->execute([
            $shipment['customer_id'],
            $shipment['grand_total'],
            $today,
            $cancel_desc,
            $user_id
        ]);

        /* ========= عكس مالي للوكيل (Debit بدلاً من Credit) ========= */
        // الوكيل كان دائناً (Credit)، الآن نجعله مديناً (Debit) بنفس التكلفة
        $pdo->prepare("
            INSERT INTO agent_transactions 
            (agent_id, debit, credit, trans_date, description, user_id) 
            VALUES (?, ?, 0, ?, ?, ?)
        ")->execute([
            $shipment['agent_id'],
            $shipment['agent_cost'],
            $today,
            $cancel_desc,
            $user_id
        ]);

        /* ========= تسجيل العكس في اليومية العامة ========= */
        // عكس حركة العميل
        $pdo->prepare("
            INSERT INTO daily_transactions 
            (trans_type, ref_id, debit, credit, trans_date, description, user_id) 
            VALUES ('customer', ?, 0, ?, ?, ?, ?)
        ")->execute([
            $shipment['customer_id'],
            $shipment['grand_total'],
            $today,
            $cancel_desc,
            $user_id
        ]);

        // عكس حركة الوكيل
        $pdo->prepare("
            INSERT INTO daily_transactions 
            (trans_type, ref_id, debit, credit, trans_date, description, user_id) 
            VALUES ('agent', ?, ?, 0, ?, ?, ?)
        ")->execute([
            $shipment['agent_id'],
            $shipment['agent_cost'],
            $today,
            $cancel_desc,
            $user_id
        ]);

        /* ========= 2. تحديث حالة الشحنة إلى Inactive ========= */
        $pdo->prepare("UPDATE newshipments SET status = 'Inactive' WHERE shipment_id = ?")
            ->execute([$id]);

        $pdo->commit();
        header("Location: shipments.php?cancelled=1");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        die("Error during cancellation: " . $e->getMessage());
    }
}