<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__.'/../../includes/auth.php';
requireLogin();

require_once __DIR__.'/../../config/database.php';

$company_id = $_SESSION['company_id'];

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

/* ===============================
FETCH PURCHASE ORDER
================================ */

$stmt = $pdo->prepare("
SELECT po.*, s.supplier_name
FROM purchase_orders po
LEFT JOIN suppliers s ON po.supplier_id = s.id
WHERE po.id = ?
AND po.company_id = ?
");

$stmt->execute([$id,$company_id]);
$po = $stmt->fetch();

if(!$po){

echo "<div class='main-content'><div class='stat-card'>Purchase Order not found.</div></div>";
require_once __DIR__.'/../../includes/footer.php';
exit;

}

/* ===============================
ADD ITEM TO PO
================================ */

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

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

$remaining = $quantity;

$stmt = $pdo->prepare("
INSERT INTO purchase_order_items
(company_id,purchase_order_id,product_id,quantity,received_qty,remaining_qty,cost_price)
VALUES (?,?,?,?,?,?,?)
");

$stmt->execute([
$company_id,
$id,
$product_id,
$quantity,
0,
$remaining,
$cost_price
]);

header("Location: view.php?id=".$id);
exit;

}

/* ===============================
RECEIVE STOCK
================================ */

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

$item_id = $_POST['item_id'];
$receive_qty = (int)$_POST['receive_qty'];

/* fetch item */

$stmt = $pdo->prepare("
SELECT *
FROM purchase_order_items
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$item_id,$company_id]);
$item = $stmt->fetch();

if($item){

$remaining = $item['remaining_qty'];

if($receive_qty > 0 && $receive_qty <= $remaining){

$new_received = $item['received_qty'] + $receive_qty;
$new_remaining = $item['quantity'] - $new_received;

/* update PO item */

$stmt = $pdo->prepare("
UPDATE purchase_order_items
SET received_qty = ?, remaining_qty = ?
WHERE id = ?
AND company_id = ?
");

$stmt->execute([
$new_received,
$new_remaining,
$item_id,
$company_id
]);

/* update product stock */

$stmt = $pdo->prepare("
UPDATE inventory_products
SET stock_qty = stock_qty + ?
WHERE id = ?
AND company_id = ?
");

$stmt->execute([
$receive_qty,
$item['product_id'],
$company_id
]);

/* SALES INVENTORY MOVEMENT */

$stmt = $pdo->prepare("
INSERT INTO sales_inventory_movements
(company_id,product_id,movement_type,quantity,reference_type,reference_id,notes,performed_by_user_id)
VALUES (?,?,?,?,?,?,?,?)
");

$stmt->execute([
$company_id,
$item['product_id'],
'PURCHASE',
$receive_qty,
'PURCHASE_ORDER',
$id,
'Purchase Order '.$po['po_number'],
$_SESSION['user_id']
]);

/* ===============================
UPDATE PO STATUS
================================ */

$status = $pdo->prepare("
SELECT SUM(remaining_qty) as remaining
FROM purchase_order_items
WHERE purchase_order_id = ?
AND company_id = ?
");

$status->execute([$id,$company_id]);
$row = $status->fetch();

if($row){

if($row['remaining'] == 0){
$new_status = 'received';
}else{
$new_status = 'partial';
}

$update = $pdo->prepare("
UPDATE purchase_orders
SET status = ?
WHERE id = ?
AND company_id = ?
");

$update->execute([
$new_status,
$id,
$company_id
]);

}

}

}

header("Location: view.php?id=".$id);
exit;

}

/* ===============================
FETCH PO ITEMS
================================ */

$stmt = $pdo->prepare("
SELECT poi.*, p.product_name
FROM purchase_order_items poi
LEFT JOIN inventory_products p ON poi.product_id = p.id
WHERE poi.purchase_order_id = ?
AND poi.company_id = ?
");

$stmt->execute([$id,$company_id]);
$items = $stmt->fetchAll();

/* ===============================
FETCH PRODUCTS
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM inventory_products
WHERE company_id = ?
AND status = 'active'
ORDER BY product_name ASC
");

$stmt->execute([$company_id]);
$products = $stmt->fetchAll();

require_once __DIR__.'/../../includes/header.php';
require_once __DIR__.'/../../includes/sidebar.php';
?>

<div class="main-content">

<div class="page-header">

<h2><?php echo htmlspecialchars($po['po_number']); ?></h2>

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

</div>

<div class="stat-card">

<div class="table-responsive">

<table class="table">

<tr>
<th>Supplier</th>
<td><?php echo htmlspecialchars($po['supplier_name']); ?></td>
</tr>

<tr>
<th>Order Date</th>
<td><?php echo htmlspecialchars($po['order_date']); ?></td>
</tr>

<tr>
<th>Status</th>
<td><?php echo htmlspecialchars($po['status']); ?></td>
</tr>

</table>

</div>

</div>

<div class="stat-card">

<h3>Add Product</h3>

<form method="POST">

<input type="hidden" name="add_item" value="1">

<div class="form-row">

<div class="form-group">

<label>Product</label>

<select name="product_id" id="product_select" required>

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

<?php foreach($products as $product){ ?>

<option 
value="<?php echo $product['id']; ?>"
data-price="<?php echo $product['cost_price']; ?>"
>
<?php echo htmlspecialchars($product['product_name']); ?>
</option>

<?php } ?>

</select>

</div>

<div class="form-group">

<label>Quantity</label>
<input type="number" name="quantity" required>

</div>

<div class="form-group">

<label>Cost Price</label>

<input type="number" step="0.01" name="cost_price" id="cost_price" required>

</div>

</div>

<div class="form-actions">

<button type="submit" class="btn btn-primary">
Add Item
</button>

</div>

</form>

</div>

<div class="stat-card">

<h3>Items</h3>

<div class="table-responsive">

<table class="table">

<thead>

<tr>
<th>Product</th>
<th>Quantity</th>
<th>Received</th>
<th>Remaining</th>
<th>Cost</th>
<th>Receive</th>
</tr>

</thead>

<tbody>

<?php if(count($items)==0){ ?>

<tr>
<td colspan="6" style="text-align:center;padding:20px;">
No items added yet
</td>
</tr>

<?php } ?>

<?php foreach($items as $item){ ?>

<tr>

<td><?php echo htmlspecialchars($item['product_name']); ?></td>

<td><?php echo $item['quantity']; ?></td>

<td><?php echo $item['received_qty']; ?></td>

<td><?php echo $item['remaining_qty']; ?></td>

<td><?php echo number_format($item['cost_price'],2); ?></td>

<td>

<?php if($item['remaining_qty'] > 0){ ?>

<form method="POST" style="display:flex;gap:6px;">

<input type="hidden" name="receive_item" value="1">
<input type="hidden" name="item_id" value="<?php echo $item['id']; ?>">

<input type="number"
name="receive_qty"
min="1"
max="<?php echo $item['remaining_qty']; ?>"
placeholder="Qty"
style="width:80px;"
required>

<button class="btn btn-primary btn-sm">
Receive
</button>

</form>

<?php } else { ?>

Received

<?php } ?>

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

</div>

<script>

document.getElementById('product_select').addEventListener('change', function(){

var selected = this.options[this.selectedIndex];

var price = selected.getAttribute('data-price');

if(price){

document.getElementById('cost_price').value = price;

}

});

</script>

<?php require_once __DIR__.'/../../includes/footer.php'; ?>