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

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

if(mysqli_num_rows($orderQuery)==0){
    $_SESSION['error']="Purchase Order not found.";
    header("Location: /beauty_pos/purchase_orders/index.php");
    exit;
}

$order=mysqli_fetch_assoc($orderQuery);

$itemQuery=mysqli_query($conn,"
SELECT
pi.*,
p.product_name
FROM purchase_items pi
LEFT JOIN products p
ON pi.product_id=p.id
WHERE pi.purchase_id='$id'
ORDER BY pi.id ASC
");

$suppliers=mysqli_query($conn,"
SELECT id,supplier_name
FROM suppliers
ORDER BY supplier_name ASC
");

$products=mysqli_query($conn,"
SELECT id,product_name
FROM products
ORDER BY product_name ASC
");

if(isset($_POST['update_purchase'])){

    $supplier_id=(int)$_POST['supplier_id'];
    $order_date=mysqli_real_escape_string($conn,$_POST['order_date']);
    $status=mysqli_real_escape_string($conn,$_POST['status']);

    $product_id=$_POST['product_id'];
    $quantity=$_POST['quantity'];
    $cost_price=$_POST['cost_price'];

    mysqli_begin_transaction($conn);

    try{

        $invoice=$order['invoice'];

        if(!empty($_FILES['invoice']['name'])){

            $folder="../uploads/purchase_invoices/";

            if(!is_dir($folder)){
                mkdir($folder,0777,true);
            }

            if(!empty($invoice) && file_exists($folder.$invoice)){
                unlink($folder.$invoice);
            }

            $ext=pathinfo($_FILES['invoice']['name'],PATHINFO_EXTENSION);

            $invoice=time()."_".rand(1000,9999).".".$ext;

            move_uploaded_file(
                $_FILES['invoice']['tmp_name'],
                $folder.$invoice
            );
        }

        $grand_total=0;
                foreach($product_id as $key=>$pid){

            $qty=(int)$quantity[$key];
            $cost=(float)$cost_price[$key];

            $grand_total += ($qty*$cost);

        }

        mysqli_query($conn,"
        UPDATE purchase_orders
        SET
        supplier_id='$supplier_id',
        order_date='$order_date',
        total_amount='$grand_total',
        status='$status',
        invoice='$invoice'
        WHERE id='$id'
        ");

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

        while($old=mysqli_fetch_assoc($oldItems)){

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

        }

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

        foreach($product_id as $key=>$pid){

            $pid=(int)$pid;
            $qty=(int)$quantity[$key];
            $cost=(float)$cost_price[$key];
            $total=$qty*$cost;

            if($pid==0 || $qty<=0){
                continue;
            }

            mysqli_query($conn,"
            INSERT INTO purchase_items
            (
            purchase_id,
            product_id,
            quantity,
            cost_price,
            total
            )
            VALUES
            (
            '$id',
            '$pid',
            '$qty',
            '$cost',
            '$total'
            )
            ");

            mysqli_query($conn,"
            UPDATE inventory
            SET current_stock=current_stock+$qty
            WHERE product_id='$pid'
            ");

        }

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

        mysqli_commit($conn);

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

    }catch(Exception $e){

        mysqli_rollback($conn);

        $_SESSION['error']="Something went wrong.";

    }

}

include_once "../includes/header.php";
include_once "../includes/sidebar.php";
?>

<div class="overlay" id="overlay"></div>

<div class="main-content">

<?php include_once "../includes/topbar.php"; ?>

<div class="container-fluid py-4">

<div class="card border-0 shadow rounded-4">

<div class="card-header bg-white">

<h4 class="mb-0">

Edit Purchase Order

</h4>

</div>

<div class="card-body">

<form
method="POST"
enctype="multipart/form-data">

<div class="row g-3">

<div class="col-lg-4">

<label class="form-label">

Supplier

</label>

<select
name="supplier_id"
class="form-select"
required>

<option value="">

Select Supplier

</option>

<?php while($supplier=mysqli_fetch_assoc($suppliers)){ ?>

<option
value="<?php echo $supplier['id'];?>"
<?php if($supplier['id']==$order['supplier_id']) echo "selected";?>>

<?php echo htmlspecialchars($supplier['supplier_name']);?>

</option>

<?php } ?>

</select>

</div>

<div class="col-lg-4">

<label class="form-label">

Order Date

</label>

<input
type="date"
name="order_date"
class="form-control"
value="<?php echo $order['order_date'];?>"
required>

</div>

<div class="col-lg-4">

<label class="form-label">

Status

</label>

<select
name="status"
class="form-select">
<option value="Pending" <?php if($order['status']=="Pending") echo "selected"; ?>>
Pending
</option>

<option value="Received" <?php if($order['status']=="Received") echo "selected"; ?>>
Received
</option>

<option value="Cancelled" <?php if($order['status']=="Cancelled") echo "selected"; ?>>
Cancelled
</option>

</select>

</div>

<div class="col-lg-6">

<label class="form-label">

Replace Invoice

</label>

<input
type="file"
name="invoice"
class="form-control"
accept=".jpg,.jpeg,.png,.pdf">

</div>

<?php if(!empty($order['invoice'])){ ?>

<div class="col-lg-6 d-flex align-items-end">

<a
href="/beauty_pos/uploads/purchase_invoices/<?php echo $order['invoice'];?>"
target="_blank"
class="btn btn-outline-primary">

<i class="fa fa-file-invoice me-2"></i>

View Current Invoice

</a>

</div>

<?php } ?>

</div>

<hr class="my-4">

<div class="table-responsive">

<table class="table table-bordered align-middle">

<thead>

<tr>

<th>Product</th>

<th width="120">Qty</th>

<th width="150">Cost Price</th>

<th width="150">Total</th>

</tr>

</thead>

<tbody>

<?php while($item=mysqli_fetch_assoc($itemQuery)){ ?>

<tr>

<td>

<select
name="product_id[]"
class="form-select"
required>

<?php

mysqli_data_seek($products,0);

while($product=mysqli_fetch_assoc($products)){

?>

<option
value="<?php echo $product['id'];?>"
<?php if($product['id']==$item['product_id']) echo "selected"; ?>>

<?php echo htmlspecialchars($product['product_name']);?>

</option>

<?php } ?>

</select>

</td>

<td>

<input
type="number"
name="quantity[]"
class="form-control qty"
value="<?php echo $item['quantity'];?>"
min="1"
required>

</td>

<td>

<input
type="number"
step="0.01"
min="0"
name="cost_price[]"
class="form-control price"
value="<?php echo $item['cost_price'];?>"
required>

</td>

<td>

<input
type="text"
class="form-control total"
value="<?php echo number_format($item['total'],2,'.','');?>"
readonly>

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

<div class="mt-4 d-flex gap-2 flex-wrap">

<button
type="submit"
name="update_purchase"
class="btn btn-primary">

<i class="fa fa-save me-2"></i>

Update Purchase Order

</button>

<a
href="/beauty_pos/purchase_orders/index.php"
class="btn btn-secondary">

Cancel

</a>

</div>

</form>

</div>

</div>

</div>

<script>
document.querySelectorAll(".qty,.price").forEach(function(input){

input.addEventListener("input",function(){

let row=this.closest("tr");

let qty=parseFloat(row.querySelector(".qty").value)||0;

let price=parseFloat(row.querySelector(".price").value)||0;

row.querySelector(".total").value=(qty*price).toFixed(2);

});

});
</script>

<?php include_once "../includes/footer.php"; ?>