<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

$sale_id = intval($_GET['id'] ?? 0);
if (!$sale_id) die("Invalid Sale ID");

try {
    $pdo->beginTransaction();

    // 1) Load sale
    $stmt = $pdo->prepare("SELECT * FROM sales WHERE id = ? LIMIT 1");
    $stmt->execute([$sale_id]);
    $sale = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sale) throw new Exception("Sale not found");

    $customer_id = intval($sale['customer_id']);
    $total  = floatval($sale['total']);
    $paid   = floatval($sale['paid']);
    $delta  = round($total - $paid, 2);  // المبلغ المستحق للعميل
    $invoice_no = $sale['invoice_no'];

    // 2) Restore stock
    $stmt2 = $pdo->prepare("SELECT * FROM sale_items WHERE sale_id = ?");
    $stmt2->execute([$sale_id]);
    $items = $stmt2->fetchAll(PDO::FETCH_ASSOC);

    foreach ($items as $it) {
        $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?")
            ->execute([$it['qty'], $it['product_id']]);
    }

    // 3) Delete sale_items
    $pdo->prepare("DELETE FROM sale_items WHERE sale_id = ?")
        ->execute([$sale_id]);


    // 4) Delete cash transaction using invoice number (no sale_id column)
    $pdo->prepare("DELETE FROM cash_transactions WHERE description LIKE ?")
        ->execute(["%{$invoice_no}%"]);


    // 5) Delete customer transactions related to this invoice
    $pdo->prepare("DELETE FROM customer_transactions WHERE note LIKE ?")
        ->execute(["%{$invoice_no}%"]);


    // 6) Restore customer balance ONLY if he was on debt
    if ($customer_id > 0 && $delta > 0) {
        $pdo->prepare("UPDATE customers SET balance = balance - ? WHERE id = ?")
            ->execute([$delta, $customer_id]);
    }


    // 7) Delete sale
    $pdo->prepare("DELETE FROM sales WHERE id = ?")->execute([$sale_id]);

    $pdo->commit();

    header("Location: sales.php?deleted=1");
    exit;

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