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

if (!isset($_GET['id']) || !intval($_GET['id'])) {
    die("Invalid purchase ID");
}

$purchase_id = intval($_GET['id']);

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

if (!$purchase) {
    die("Purchase not found");
}

// Check if supplier system exists
$has_suppliers = false;
try {
    $res = $pdo->query("SHOW TABLES LIKE 'suppliers'")->fetchColumn();
    if ($res) $has_suppliers = true;
} catch (Exception $e) {}

try {
    $pdo->beginTransaction();

    // 1) Load all purchase items
    $items = $pdo->prepare("SELECT * FROM purchase_items WHERE purchase_id = ?");
    $items->execute([$purchase_id]);
    $rows = $items->fetchAll(PDO::FETCH_ASSOC);

    // 2) Delete the created products themselves (not update stock)
    $delProduct = $pdo->prepare("DELETE FROM products WHERE id = ?");
    foreach ($rows as $it) {
        $product_id = intval($it['product_id']);
        $delProduct->execute([$product_id]);
    }

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

    // 4) Fix supplier/customer balance
    $supplier_id = $purchase['supplier_id'];
    $total = floatval($purchase['total']);
    $paid = floatval($purchase['paid']);

    if ($supplier_id) {
        if ($has_suppliers) {
            $cur = $pdo->prepare("SELECT COALESCE(balance,0) FROM suppliers WHERE id = ?");
            $cur->execute([$supplier_id]);
            $old_balance = floatval($cur->fetchColumn() ?? 0);

            $new_balance = round($old_balance - ($total - $paid), 2);
            $pdo->prepare("UPDATE suppliers SET balance = ? WHERE id = ?")
                ->execute([$new_balance, $supplier_id]);

        } else {
            $cur = $pdo->prepare("SELECT COALESCE(balance,0) FROM customers WHERE id = ?");
            $cur->execute([$supplier_id]);
            $old_balance = floatval($cur->fetchColumn() ?? 0);

            $new_balance = round($old_balance - ($total - $paid), 2);
            $pdo->prepare("UPDATE customers SET balance = ? WHERE id = ?")
                ->execute([$new_balance, $supplier_id]);
        }
    }

    // 5) Delete cash transactions
    $pdo->prepare("DELETE FROM cash_transactions WHERE description LIKE ?")
        ->execute(["Purchase #$purchase_id%"]);

    // 6) Delete the purchase itself
    $pdo->prepare("DELETE FROM purchases WHERE id = ?")
        ->execute([$purchase_id]);

    $pdo->commit();

    header("Location: purchase_view.php?msg=deleted");
    exit;

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