<?php
session_start();

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

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

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

if (isset($_POST['save_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'];

    if ($supplier_id == 0 || empty($order_date)) {

        $_SESSION['error'] = "Please fill all required fields.";

    } else {

        mysqli_begin_transaction($conn);

        try {

            $invoice = "";

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

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

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

                $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,"
                INSERT INTO purchase_orders
                (
                    supplier_id,
                    order_date,
                    total_amount,
                    status,
                    invoice
                )
                VALUES
                (
                    '$supplier_id',
                    '$order_date',
                    '$grand_total',
                    '$status',
                    '$invoice'
                )
            ");

            $purchase_id = mysqli_insert_id($conn);
                        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
                    (
                        '$purchase_id',
                        '$pid',
                        '$qty',
                        '$cost',
                        '$total'
                    )
                ");

                $checkInventory = mysqli_query($conn,"
SELECT id
FROM inventory
WHERE product_id='$pid'
LIMIT 1
");

if(mysqli_num_rows($checkInventory)>0){

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

}else{

    mysqli_query($conn,"
    INSERT INTO inventory
    (
        product_id,
        current_stock
    )
    VALUES
    (
        '$pid',
        '$qty'
    )
    ");

}

                mysqli_query($conn,"
INSERT INTO stock_history
(
    product_id,
    stock_in,
    stock_out,
    adjustment,
    reason
)
VALUES
(
    '$pid',
    '$qty',
    0,
    0,
    'Purchase Order #$purchase_id'
)
");
            }

            mysqli_commit($conn);

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

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

        }catch(Exception $e){

    mysqli_rollback($conn);

    die($e->getMessage());

}

    }

}

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

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 shadow border-0 rounded-4">

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

<h4 class="mb-0">
Add 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 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"
required>

</div>

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

<label class="form-label">

Status

</label>

<select
name="status"
class="form-select">

<option value="Pending">Pending</option>
<option value="Received">Received</option>
<option value="Cancelled">Cancelled</option>

</select>

</div>

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

<label class="form-label">

Invoice

</label>

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

</div>

<hr class="my-4">

<div class="table-responsive">

<table class="table table-bordered" id="purchaseTable">

<thead>

<tr>

<th>Product</th>

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

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

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

<th width="80"></th>

</tr>

</thead>

<tbody>

<tr>
<td>

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

<option value="">Select Product</option>

<?php while($product=mysqli_fetch_assoc($products)){ ?>

<option value="<?php echo $product['id']; ?>">

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

</option>

<?php } ?>

</select>

</td>

<td>

<input
type="number"
name="quantity[]"
class="form-control qty"
min="1"
value="1"
required>

</td>

<td>

<input
type="number"
name="cost_price[]"
class="form-control price"
step="0.01"
min="0"
value="0"
required>

</td>

<td>

<input
type="text"
class="form-control total"
value="0.00"
readonly>

</td>

<td>

<button
type="button"
class="btn btn-danger removeRow">

<i class="fa fa-trash"></i>

</button>

</td>

</tr>

</tbody>

</table>

</div>

<div class="mt-3">

<button
type="button"
id="addRow"
class="btn btn-secondary">

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

Add Product

</button>

</div>

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

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

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

Save Purchase Order

</button>

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

Cancel

</a>

</div>

</div>

</form>

</div>

</div>

</div>

<script>

document.getElementById("addRow").onclick=function(){

let tbody=document.querySelector("#purchaseTable tbody");

let row=tbody.rows[0].cloneNode(true);

row.querySelector(".product").selectedIndex=0;
row.querySelector(".qty").value=1;
row.querySelector(".price").value=0;
row.querySelector(".total").value="0.00";

tbody.appendChild(row);

};

document.addEventListener("click",function(e){

if(e.target.closest(".removeRow")){

let tbody=document.querySelector("#purchaseTable tbody");

if(tbody.rows.length>1){

e.target.closest("tr").remove();

}

}

});

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

if(e.target.classList.contains("qty") || e.target.classList.contains("price")){

let row=e.target.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"; ?>