<?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'];
$user_id = $_SESSION['user_id'];

$message = "";

/* ===============================
FETCH SUPPLIERS
================================ */

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

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

/* ===============================
CREATE PURCHASE ORDER
================================ */

if($_SERVER['REQUEST_METHOD'] == 'POST'){

$supplier_id = $_POST['supplier_id'];
$order_date = $_POST['order_date'];

/* get supplier code */

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

$stmt->execute([$supplier_id,$company_id]);
$supplier = $stmt->fetch();

$code = $supplier['supplier_code'];

/* generate PO number */

$stmt = $pdo->prepare("
SELECT COUNT(*) as total
FROM purchase_orders
WHERE supplier_id = ?
AND company_id = ?
");

$stmt->execute([$supplier_id,$company_id]);
$count = $stmt->fetch()['total'];

$next = $count + 1;

$po_number = "PO-".$code."-".str_pad($next,4,'0',STR_PAD_LEFT);

/* insert purchase order */

$stmt = $pdo->prepare("
INSERT INTO purchase_orders
(company_id,supplier_id,po_number,order_date,status,created_by)
VALUES (?,?,?,?,?,?)
");

$stmt->execute([
$company_id,
$supplier_id,
$po_number,
$order_date,
'draft',
$user_id
]);

$po_id = $pdo->lastInsertId();

/* redirect to view */

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

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

<div class="main-content">

<div class="page-header">
<h2>Create Purchase Order</h2>
</div>

<div class="stat-card">

<form method="POST">

<div class="form-row">

<div class="form-group">
<label>Supplier</label>

<select name="supplier_id" required>

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

<?php foreach($suppliers as $supplier){ ?>

<option value="<?php echo $supplier['id']; ?>">
<?php echo htmlspecialchars($supplier['supplier_name']); ?>
</option>

<?php } ?>

</select>

</div>

<div class="form-group">
<label>Order Date</label>
<input type="date" name="order_date" required>
</div>

</div>

<div class="form-actions">

<button type="submit" class="btn btn-primary">
Create Purchase Order
</button>

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

</div>

</form>

</div>

</div>

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