<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: /beauty_pos/login.php");
    exit;
}

include_once "../config/database.php";

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error'] = "Invalid Purchase Order.";
    header("Location: /beauty_pos/purchase_orders/index.php");
    exit;
}

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

mysqli_begin_transaction($conn);

try {

    $order = mysqli_query($conn,"
        SELECT invoice
        FROM purchase_orders
        WHERE id='$id'
        LIMIT 1
    ");

    if(mysqli_num_rows($order)==0){

        throw new Exception("Purchase Order not found.");

    }

    $orderRow=mysqli_fetch_assoc($order);

    $items=mysqli_query($conn,"
        SELECT *
        FROM purchase_items
        WHERE purchase_id='$id'
    ");

    while($item=mysqli_fetch_assoc($items)){

        mysqli_query($conn,"
            UPDATE inventory
            SET current_stock=current_stock-".$item['quantity']."
            WHERE product_id='".$item['product_id']."'
        ");

        mysqli_query($conn,"
INSERT INTO stock_history
(
    product_id,
    stock_in,
    stock_out,
    adjustment,
    reason
)
VALUES
(
    '".$item['product_id']."',
    0,
    '".$item['quantity']."',
    0,
    'Purchase Order Deleted #$id'
)
");

    }

    mysqli_query($conn,"
        DELETE FROM purchase_items
        WHERE purchase_id='$id'
    ");

    mysqli_query($conn,"
        DELETE FROM purchase_orders
        WHERE id='$id'
    ");

    if(
        !empty($orderRow['invoice']) &&
        file_exists("../uploads/purchase_invoices/".$orderRow['invoice'])
    ){

        unlink("../uploads/purchase_invoices/".$orderRow['invoice']);

    }

    mysqli_commit($conn);

    $_SESSION['success']="Purchase Order Deleted Successfully.";

} catch(Exception $e){

    mysqli_rollback($conn);

    $_SESSION['error']=$e->getMessage();

}

header("Location: /beauty_pos/purchase_orders/index.php");
exit;
?>