<?php

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

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

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

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

$company_id = $_SESSION['company_id'];

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

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

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

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

if(!$po){

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

}

/* ===============================
CALCULATE PO TOTAL
================================ */

$stmt = $pdo->prepare("
SELECT SUM(quantity * cost_price) as total
FROM purchase_order_items
WHERE purchase_order_id = ?
AND company_id = ?
");

$stmt->execute([$po_id,$company_id]);
$row = $stmt->fetch();

$total = $row['total'] ?? 0;

/* ===============================
CREATE INVOICE
================================ */

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

$invoice_number = $_POST['invoice_number'];

$stmt = $pdo->prepare("
INSERT INTO supplier_invoices
(company_id,supplier_id,purchase_order_id,invoice_number,invoice_date,total_amount)
VALUES (?,?,?,?,?,?)
");

$stmt->execute([
$company_id,
$po['supplier_id'],
$po_id,
$invoice_number,
date('Y-m-d'),
$total
]);

$invoice_id = $pdo->lastInsertId();

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

}

?>

<div class="main-content">

<div class="page-header">

<h2>Create Supplier Invoice</h2>

</div>

<div class="stat-card">

<form method="POST">

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

<div class="form-row">

<div class="form-group">

<label>PO Number</label>
<input type="text" value="<?php echo $po['po_number']; ?>" readonly>

</div>

<div class="form-group">

<label>Invoice Number</label>
<input type="text" name="invoice_number" required>

</div>

<div class="form-group">

<label>Total</label>
<input type="text" value="R <?php echo number_format($total,2); ?>" readonly>

</div>

</div>

<button class="btn btn-primary">
Create Invoice
</button>

</form>

</div>

</div>

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