<?php
require_once __DIR__ . '/../config/config.php';
require_permission('purchase_orders.manage');
$u = current_user();

$prId = (int)($_GET['pr_id'] ?? $_POST['pr_id'] ?? 0);
$stmt = $pdo->prepare("SELECT * FROM purchase_requisitions WHERE id = ? AND status = 'approved'");
$stmt->execute([$prId]);
$pr = $stmt->fetch();
if (!$pr) { flash('error', 'Requisition not found or not yet approved.'); redirect('purchase_requisitions/list.php'); }

$existingPO = $pdo->prepare("SELECT id FROM purchase_orders WHERE pr_id = ?");
$existingPO->execute([$prId]);
if ($existingPO->fetch()) { flash('error', 'A purchase order has already been raised for this requisition.'); redirect('purchase_requisitions/view.php?id=' . $prId); }

$lineStmt = $pdo->prepare("SELECT pri.*, i.name item_name FROM purchase_requisition_items pri
                            JOIN items i ON i.id = pri.item_id WHERE pri.pr_id = ?");
$lineStmt->execute([$prId]);
$lines = $lineStmt->fetchAll();

$suppliers = $pdo->query("SELECT id, name FROM suppliers WHERE is_active=1 ORDER BY name")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $supplierId = $_POST['supplier_id'];
    $qtys = $_POST['quantity'] ?? [];
    $costs = $_POST['unit_cost'] ?? [];
    $itemIds = $_POST['item_id'] ?? [];

    if (!$supplierId) {
        flash('error', 'Please select a supplier.');
    } else {
        $pdo->beginTransaction();
        try {
            $poNumber = generate_doc_number($pdo, 'purchase_orders', 'po_number', 'PO');
            $total = 0;
            foreach ($itemIds as $i => $itemId) { $total += (float)$qtys[$i] * (float)$costs[$i]; }

            $pdo->prepare("INSERT INTO purchase_orders (po_number, pr_id, supplier_id, total_cost, created_by) VALUES (?,?,?,?,?)")
                ->execute([$poNumber, $prId, $supplierId, $total, $u['id']]);
            $poId = $pdo->lastInsertId();

            $ins = $pdo->prepare("INSERT INTO purchase_order_items (po_id, item_id, quantity, unit_cost) VALUES (?,?,?,?)");
            foreach ($itemIds as $i => $itemId) {
                $ins->execute([$poId, $itemId, (float)$qtys[$i], (float)$costs[$i]]);
            }

            $pdo->prepare("UPDATE purchase_requisitions SET status='ordered' WHERE id=?")->execute([$prId]);
            $pdo->commit();
            flash('success', "Purchase order $poNumber created.");
            redirect('purchase_orders/view.php?id=' . $poId);
        } catch (Exception $ex) {
            $pdo->rollBack();
            flash('error', 'Failed: ' . $ex->getMessage());
        }
    }
}

$pageTitle = 'Create Purchase Order';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">Create Purchase Order</h1>
<p class="text-slate-500 text-sm mb-6">From requisition <?= e($pr['pr_number']) ?></p>

<form method="POST" class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
  <input type="hidden" name="pr_id" value="<?= $prId ?>">
  <div class="mb-6 max-w-sm">
    <label class="text-sm font-medium block mb-1">Supplier</label>
    <select name="supplier_id" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <option value="">-- Select supplier --</option>
      <?php foreach ($suppliers as $s): ?><option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
    </select>
  </div>

  <div class="overflow-x-auto"><table class="w-full text-sm mb-6">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-3 py-2">Item</th><th class="text-left px-3 py-2">Quantity</th><th class="text-left px-3 py-2">Unit Cost</th></tr></thead>
    <tbody>
    <?php foreach ($lines as $l): ?>
      <tr class="border-t border-slate-100">
        <td class="px-3 py-2"><?= e($l['item_name']) ?><input type="hidden" name="item_id[]" value="<?= $l['item_id'] ?>"></td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="quantity[]" value="<?= $l['quantity'] ?>" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="unit_cost[]" value="<?= $l['estimated_unit_cost'] ?>" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table></div>

  <button type="submit" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Create Purchase Order</button>
</form>
<?php include __DIR__ . '/../includes/footer.php'; ?>
