<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Purchase Order Approvals';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) require_permission($pdo, 'purchase_orders', 'view');
}

if (!function_exists('h')) { function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); } }
if (!function_exists('money_fmt')) { function money_fmt($v): string { return number_format((float)$v, 2); } }
if (!function_exists('qty_fmt')) { function qty_fmt($v): string { $n=(float)$v; return abs($n-round($n))<0.00001 ? number_format($n,0) : number_format($n,4); } }
if (!function_exists('poa_flash')) { function poa_flash(string $type,string $message): void { $_SESSION['po_approval_flash'][]=['type'=>$type,'message'=>$message]; } }
if (!function_exists('poa_get_flash')) { function poa_get_flash(): array { $x=$_SESSION['po_approval_flash']??[]; unset($_SESSION['po_approval_flash']); return $x; } }
if (!function_exists('poa_table_exists')) { function poa_table_exists(PDO $pdo,string $table): bool { $s=$pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t"); $s->execute([':t'=>$table]); return (int)$s->fetchColumn()>0; } }
if (!function_exists('poa_col_exists')) { function poa_col_exists(PDO $pdo,string $table,string $col): bool { $s=$pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c"); $s->execute([':t'=>$table,':c'=>$col]); return (int)$s->fetchColumn()>0; } }
if (!function_exists('poa_add_col')) { function poa_add_col(PDO $pdo,string $table,string $col,string $sql): void { if (!poa_col_exists($pdo,$table,$col)) $pdo->exec($sql); } }
if (!function_exists('poa_user_name_expr')) {
    function poa_user_name_expr(PDO $pdo,string $a='u'): string {
        if (!poa_table_exists($pdo,'users')) return 'NULL';
        if (poa_col_exists($pdo,'users','firstname') && poa_col_exists($pdo,'users','lastname')) return "CONCAT($a.firstname,' ',$a.lastname)";
        foreach(['name','full_name','username','email'] as $c) if (poa_col_exists($pdo,'users',$c)) return "$a.$c";
        return "CONCAT('User #',$a.id)";
    }
}
if (!function_exists('poa_status_badge')) {
    function poa_status_badge(string $s): string {
        return ['draft'=>'text-bg-secondary','pending_approval'=>'text-bg-warning','approved'=>'text-bg-success','rejected'=>'text-bg-danger','part_received'=>'text-bg-info','received'=>'text-bg-primary','cancelled'=>'text-bg-dark','void'=>'text-bg-dark'][$s] ?? 'text-bg-light';
    }
}

$errors=[];
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_purchase_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        po_no VARCHAR(60) NOT NULL,
        supplier_id INT UNSIGNED NOT NULL,
        supplier_name VARCHAR(180) NULL,
        store_id INT UNSIGNED NOT NULL,
        po_date DATE NOT NULL,
        expected_date DATE NULL,
        status ENUM('draft','pending_approval','approved','rejected','part_received','received','cancelled','void') NOT NULL DEFAULT 'draft',
        subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        tax_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        notes TEXT NULL,
        rejection_reason TEXT NULL,
        submitted_by INT UNSIGNED NULL,
        submitted_at DATETIME NULL,
        approved_by INT UNSIGNED NULL,
        approved_at DATETIME NULL,
        rejected_by INT UNSIGNED NULL,
        rejected_at DATETIME NULL,
        created_by INT UNSIGNED NULL,
        cancelled_reason TEXT NULL,
        cancelled_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_po_no (po_no),
        INDEX idx_po_supplier (supplier_id), INDEX idx_po_store (store_id), INDEX idx_po_status (status), INDEX idx_po_date (po_date)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    poa_add_col($pdo,'inventory_purchase_orders','rejection_reason',"ALTER TABLE inventory_purchase_orders ADD COLUMN rejection_reason TEXT NULL AFTER notes");
    poa_add_col($pdo,'inventory_purchase_orders','submitted_by',"ALTER TABLE inventory_purchase_orders ADD COLUMN submitted_by INT UNSIGNED NULL AFTER rejection_reason");
    poa_add_col($pdo,'inventory_purchase_orders','submitted_at',"ALTER TABLE inventory_purchase_orders ADD COLUMN submitted_at DATETIME NULL AFTER submitted_by");
    poa_add_col($pdo,'inventory_purchase_orders','approved_by',"ALTER TABLE inventory_purchase_orders ADD COLUMN approved_by INT UNSIGNED NULL AFTER submitted_at");
    poa_add_col($pdo,'inventory_purchase_orders','approved_at',"ALTER TABLE inventory_purchase_orders ADD COLUMN approved_at DATETIME NULL AFTER approved_by");
    poa_add_col($pdo,'inventory_purchase_orders','rejected_by',"ALTER TABLE inventory_purchase_orders ADD COLUMN rejected_by INT UNSIGNED NULL AFTER approved_at");
    poa_add_col($pdo,'inventory_purchase_orders','rejected_at',"ALTER TABLE inventory_purchase_orders ADD COLUMN rejected_at DATETIME NULL AFTER rejected_by");
    try { $pdo->exec("ALTER TABLE inventory_purchase_orders MODIFY status ENUM('draft','pending_approval','approved','rejected','part_received','received','cancelled','void') NOT NULL DEFAULT 'draft'"); } catch(Throwable $e) {}
} catch(Throwable $e) { $errors[]='Could not prepare approval fields: '.$e->getMessage(); }

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();
        $action=(string)($_POST['action']??'');
        $poId=(int)($_POST['po_id']??0);
        if ($poId<=0) throw new RuntimeException('Invalid purchase order selected.');
        $stmt=$pdo->prepare("SELECT * FROM inventory_purchase_orders WHERE id=:id LIMIT 1");
        $stmt->execute([':id'=>$poId]);
        $po=$stmt->fetch(PDO::FETCH_ASSOC);
        if (!$po) throw new RuntimeException('Purchase order not found.');

        if ($action==='submit_for_approval') {
            if (function_exists('require_permission')) require_permission($pdo,'purchase_orders','edit');
            if (!in_array($po['status'],['draft','rejected'],true)) throw new RuntimeException('Only draft/rejected POs can be submitted.');
            $stmt=$pdo->prepare("SELECT COUNT(*) FROM inventory_purchase_order_lines WHERE po_id=:id AND qty_ordered>0");
            $stmt->execute([':id'=>$poId]);
            if ((int)$stmt->fetchColumn()<=0) throw new RuntimeException('Purchase order has no valid item lines.');
            $stmt=$pdo->prepare("UPDATE inventory_purchase_orders SET status='pending_approval', submitted_by=:uid, submitted_at=NOW(), rejection_reason=NULL, updated_at=NOW() WHERE id=:id");
            $stmt->execute([':uid'=>$_SESSION['user_id']??null, ':id'=>$poId]);
            poa_flash('success','Purchase order submitted for approval.');
            header('Location: purchase_order_approvals.php?po_id='.$poId); exit;
        }

        if ($action==='approve_po') {
            if (function_exists('require_permission')) require_permission($pdo,'purchase_orders','approve');
            if (!in_array($po['status'],['draft','pending_approval'],true)) throw new RuntimeException('Only draft/pending POs can be approved.');
            $approvedBy=$_SESSION['user_id']??null;
            if (file_exists(__DIR__ . '/../../includes/manager_approval_modal.php')) {
                require_once __DIR__ . '/../../includes/manager_approval_modal.php';
                if (function_exists('require_manager_approval')) {
                    $m=require_manager_approval($pdo,'purchase_orders','Approve Purchase Order '.($po['po_no']??('#'.$poId)),'purchase_order',$poId);
                    $approvedBy=(int)($m['id']??($approvedBy??0)) ?: null;
                }
            }
            $stmt=$pdo->prepare("UPDATE inventory_purchase_orders SET status='approved', approved_by=:uid, approved_at=NOW(), updated_at=NOW() WHERE id=:id");
            $stmt->execute([':uid'=>$approvedBy, ':id'=>$poId]);
            poa_flash('success','Purchase order approved and ready for GRN receiving.');
            header('Location: purchase_order_approvals.php?po_id='.$poId); exit;
        }

        if ($action==='reject_po') {
            if (function_exists('require_permission')) require_permission($pdo,'purchase_orders','approve');
            if (!in_array($po['status'],['draft','pending_approval'],true)) throw new RuntimeException('Only draft/pending POs can be rejected.');
            $reason=trim((string)($_POST['rejection_reason']??''));
            if ($reason==='') throw new RuntimeException('Rejection reason is required.');
            $stmt=$pdo->prepare("UPDATE inventory_purchase_orders SET status='rejected', rejected_by=:uid, rejected_at=NOW(), rejection_reason=:reason, updated_at=NOW() WHERE id=:id");
            $stmt->execute([':uid'=>$_SESSION['user_id']??null, ':reason'=>$reason, ':id'=>$poId]);
            poa_flash('warning','Purchase order rejected.');
            header('Location: purchase_order_approvals.php?po_id='.$poId); exit;
        }
        throw new RuntimeException('Unknown action.');
    } catch(Throwable $e) {
        poa_flash('danger',$e->getMessage());
        header('Location: purchase_order_approvals.php'.(!empty($poId)?'?po_id='.(int)$poId:'')); exit;
    }
}

$status=trim((string)($_GET['status']??''));
$supplierId=(int)($_GET['supplier_id']??0);
$storeId=(int)($_GET['store_id']??0);
$dateFrom=trim((string)($_GET['date_from']??date('Y-m-01')));
$dateTo=trim((string)($_GET['date_to']??date('Y-m-d')));
$search=trim((string)($_GET['q']??''));
if (strtotime($dateFrom)===false) $dateFrom=date('Y-m-01');
if (strtotime($dateTo)===false) $dateTo=date('Y-m-d');

$where="po.po_date BETWEEN :from AND :to";
$params=[':from'=>$dateFrom, ':to'=>$dateTo];
if ($status!=='') { $where.=" AND po.status=:status"; $params[':status']=$status; }
if ($supplierId>0) { $where.=" AND po.supplier_id=:supplier_id"; $params[':supplier_id']=$supplierId; }
if ($storeId>0) { $where.=" AND po.store_id=:store_id"; $params[':store_id']=$storeId; }
if ($search!=='') {
    $where.=" AND (po.po_no LIKE :q_po OR po.supplier_name LIKE :q_supplier OR sl.location_name LIKE :q_store OR po.notes LIKE :q_notes)";
    $params[':q_po']='%'.$search.'%';
    $params[':q_supplier']='%'.$search.'%';
    $params[':q_store']='%'.$search.'%';
    $params[':q_notes']='%'.$search.'%';
}

$suppliers=[]; $stores=[]; $orders=[]; $viewPo=null; $viewItems=[]; $viewGrns=[]; $approvalLogs=[];
$summary=['draft'=>0,'pending_approval'=>0,'approved'=>0,'rejected'=>0,'part_received'=>0,'received'=>0,'cancelled'=>0,'void'=>0];
try {
    $suppliers=$pdo->query("SELECT id,supplier_name FROM inventory_suppliers WHERE is_active=1 ORDER BY supplier_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $stores=$pdo->query("SELECT id,location_name FROM store_locations WHERE is_active=1 ORDER BY location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $created=poa_user_name_expr($pdo,'cu'); $submitted=poa_user_name_expr($pdo,'su'); $approved=poa_user_name_expr($pdo,'au'); $rejected=poa_user_name_expr($pdo,'ru');
    $joins=poa_table_exists($pdo,'users') ? "LEFT JOIN users cu ON cu.id=po.created_by LEFT JOIN users su ON su.id=po.submitted_by LEFT JOIN users au ON au.id=po.approved_by LEFT JOIN users ru ON ru.id=po.rejected_by" : '';
    $stmt=$pdo->prepare("SELECT po.*, COALESCE(po.supplier_name,s.supplier_name) supplier_display, sl.location_name,
        COALESCE(li.line_count,0) line_count, COALESCE(li.total_qty,0) total_qty, COALESCE(li.received_qty,0) received_qty,
        COALESCE(gr.grn_count,0) grn_count, gr.last_grn_date,
        $created created_by_name, $submitted submitted_by_name, $approved approved_by_name, $rejected rejected_by_name
        FROM inventory_purchase_orders po
        LEFT JOIN inventory_suppliers s ON s.id=po.supplier_id
        LEFT JOIN store_locations sl ON sl.id=po.store_id
        LEFT JOIN (SELECT po_id, COUNT(*) line_count, SUM(qty_ordered) total_qty, SUM(qty_received) received_qty FROM inventory_purchase_order_lines GROUP BY po_id) li ON li.po_id=po.id
        LEFT JOIN (SELECT po_id, COUNT(*) grn_count, MAX(grn_date) last_grn_date FROM inventory_grns WHERE po_id IS NOT NULL GROUP BY po_id) gr ON gr.po_id=po.id
        $joins
        WHERE $where
        ORDER BY CASE po.status WHEN 'pending_approval' THEN 0 WHEN 'approved' THEN 1 WHEN 'part_received' THEN 2 WHEN 'received' THEN 3 WHEN 'draft' THEN 4 WHEN 'rejected' THEN 5 ELSE 6 END, po.po_date DESC, po.id DESC LIMIT 500");
    $stmt->execute($params); $orders=$stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt=$pdo->query("SELECT status,COUNT(*) cnt FROM inventory_purchase_orders GROUP BY status");
    foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) $summary[$r['status']]=(int)$r['cnt'];

    $viewId=(int)($_GET['po_id']??($_GET['view_id']??0));
    if ($viewId>0) {
        $stmt=$pdo->prepare("SELECT po.*, COALESCE(po.supplier_name,s.supplier_name) supplier_display, s.email supplier_email, s.phone supplier_phone, s.payment_terms, sl.location_name,
            $created created_by_name, $submitted submitted_by_name, $approved approved_by_name, $rejected rejected_by_name
            FROM inventory_purchase_orders po
            LEFT JOIN inventory_suppliers s ON s.id=po.supplier_id
            LEFT JOIN store_locations sl ON sl.id=po.store_id
            $joins
            WHERE po.id=:id LIMIT 1");
        $stmt->execute([':id'=>$viewId]); $viewPo=$stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        if ($viewPo) {
            $stmt=$pdo->prepare("SELECT pol.*, ii.item_name, ii.item_code FROM inventory_purchase_order_lines pol LEFT JOIN inventory_items ii ON ii.id=pol.item_id WHERE pol.po_id=:id ORDER BY pol.id ASC");
            $stmt->execute([':id'=>$viewId]); $viewItems=$stmt->fetchAll(PDO::FETCH_ASSOC);
            $stmt=$pdo->prepare("SELECT * FROM inventory_grns WHERE po_id=:id ORDER BY grn_date DESC,id DESC");
            $stmt->execute([':id'=>$viewId]); $viewGrns=$stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
} catch(Throwable $e) { $errors[]='Could not load purchase approvals: '.$e->getMessage(); }

if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    $filename = 'purchase_order_approvals_' . date('Ymd_His') . '.xls';

    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    echo "\xEF\xBB\xBF";
    echo '<html><head><meta charset="UTF-8">';
    echo '<style>
        table{border-collapse:collapse;width:100%;font-family:Arial,Helvetica,sans-serif;font-size:10pt}
        th{background:#e5e7eb;font-weight:bold;border:1px solid #94a3b8;padding:6px;text-align:left}
        td{border:1px solid #cbd5e1;padding:5px}
        .num{text-align:right}
        .title{font-size:16pt;font-weight:bold;margin-bottom:4px}
        .filters{font-size:9pt;color:#475569;margin-bottom:10px}
    </style></head><body>';

    echo '<div class="title">Purchase Order Approvals</div>';
    echo '<div class="filters">';
    echo 'Date From: ' . h($dateFrom) . ' | Date To: ' . h($dateTo);
    echo ' | Status: ' . h($status !== '' ? ucwords(str_replace('_',' ', $status)) : 'All');
    echo ' | Search: ' . h($search !== '' ? $search : 'All');
    echo '</div>';

    echo '<table>';
    echo '<thead><tr>
        <th>Date</th>
        <th>PO No</th>
        <th>Supplier</th>
        <th>Store</th>
        <th>Status</th>
        <th>Lines</th>
        <th>Ordered Qty</th>
        <th>Received Qty</th>
        <th>GRNs</th>
        <th>Total Amount</th>
        <th>Created By</th>
        <th>Submitted By</th>
        <th>Approved By</th>
        <th>Approved At</th>
        <th>Rejected By</th>
        <th>Rejected At</th>
        <th>Last GRN Date</th>
    </tr></thead><tbody>';

    if (!$orders) {
        echo '<tr><td colspan="17">No purchase orders found for the selected filters.</td></tr>';
    } else {
        foreach ($orders as $o) {
            echo '<tr>';
            echo '<td>' . h($o['po_date'] ?? '') . '</td>';
            echo '<td>' . h($o['po_no'] ?? '') . '</td>';
            echo '<td>' . h($o['supplier_display'] ?: 'Supplier') . '</td>';
            echo '<td>' . h($o['location_name'] ?: 'Store') . '</td>';
            echo '<td>' . h(ucwords(str_replace('_',' ', (string)($o['status'] ?? '')))) . '</td>';
            echo '<td class="num">' . (int)($o['line_count'] ?? 0) . '</td>';
            echo '<td class="num">' . h(qty_fmt($o['total_qty'] ?? 0)) . '</td>';
            echo '<td class="num">' . h(qty_fmt($o['received_qty'] ?? 0)) . '</td>';
            echo '<td class="num">' . (int)($o['grn_count'] ?? 0) . '</td>';
            echo '<td class="num">' . h(money_fmt($o['total_amount'] ?? 0)) . '</td>';
            echo '<td>' . h($o['created_by_name'] ?: '') . '</td>';
            echo '<td>' . h($o['submitted_by_name'] ?: '') . '</td>';
            echo '<td>' . h($o['approved_by_name'] ?: '') . '</td>';
            echo '<td>' . h($o['approved_at'] ?: '') . '</td>';
            echo '<td>' . h($o['rejected_by_name'] ?: '') . '</td>';
            echo '<td>' . h($o['rejected_at'] ?: '') . '</td>';
            echo '<td>' . h($o['last_grn_date'] ?: '') . '</td>';
            echo '</tr>';
        }
    }

    echo '</tbody></table></body></html>';
    exit;
}


$flashes=poa_get_flash();
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band no-print">
  <div class="row g-4 align-items-center">
    <div class="col-lg-8"><div class="page-eyebrow text-white-50"><i class="bi bi-shield-check"></i> Purchasing Control</div><div class="hero-title mt-2">Purchase Order Approvals</div><div class="hero-subtitle mt-2">Uses inventory_purchase_orders, so approved and received GRN purchase orders now show on this list.</div></div>
    <div class="col-lg-4 text-lg-end"><a href="purchase_orders.php" class="btn btn-light me-2"><i class="bi bi-file-earmark-text me-2"></i>Purchase Orders</a><a href="grn.php" class="btn btn-outline-light"><i class="bi bi-truck me-2"></i>GRN</a></div>
  </div>
</div>
<?php foreach($flashes as $f): ?><div class="alert alert-<?php echo h($f['type']); ?> no-print"><?php echo h($f['message']); ?></div><?php endforeach; ?>
<?php if($errors): ?><div class="alert alert-danger no-print"><div class="fw-bold mb-2">Please fix the following:</div><ul class="mb-0"><?php foreach($errors as $e): ?><li><?php echo h($e); ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<div class="row g-4 mb-4 no-print">
  <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-hourglass-split"></i></div><div><div class="metric-label">Pending</div><div class="metric-value"><?php echo (int)$summary['pending_approval']; ?></div></div></div></div>
  <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check-circle"></i></div><div><div class="metric-label">Approved</div><div class="metric-value"><?php echo (int)$summary['approved']; ?></div></div></div></div>
  <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-info-subtle text-info"><i class="bi bi-box-seam"></i></div><div><div class="metric-label">Part Received</div><div class="metric-value"><?php echo (int)$summary['part_received']; ?></div></div></div></div>
  <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-box-arrow-in-down"></i></div><div><div class="metric-label">Received</div><div class="metric-value"><?php echo (int)$summary['received']; ?></div></div></div></div>
</div>

<?php if($viewPo): ?>
<div class="card panel-card mb-4 approval-detail" id="approvalDetail">
  <div class="card-header d-flex justify-content-between align-items-center"><div><h5 class="mb-0"><?php echo h($viewPo['po_no']); ?></h5><div class="small text-muted"><?php echo h($viewPo['supplier_display']); ?> • <?php echo h($viewPo['location_name']); ?> • <?php echo h($viewPo['po_date']); ?></div></div><div class="d-flex gap-2 no-print"><a href="purchase_orders.php?view_id=<?php echo (int)$viewPo['id']; ?>" class="btn btn-sm btn-outline-success"><i class="bi bi-box-arrow-in-down me-1"></i>Open Receiving</a><button onclick="window.print()" class="btn btn-sm btn-outline-primary"><i class="bi bi-printer me-1"></i>Print</button><a href="purchase_order_approvals.php" class="btn btn-sm btn-outline-secondary">Close</a></div></div>
  <div class="card-body">
    <div class="row g-3 mb-3"><div class="col-md-2"><strong>Status</strong><br><span class="badge <?php echo h(poa_status_badge($viewPo['status'])); ?>"><?php echo h(ucwords(str_replace('_',' ',$viewPo['status']))); ?></span></div><div class="col-md-2"><strong>Date</strong><br><?php echo h($viewPo['po_date']); ?></div><div class="col-md-3"><strong>Approved By</strong><br><?php echo h($viewPo['approved_by_name'] ?: '—'); ?></div><div class="col-md-2"><strong>GRNs</strong><br><?php echo count($viewGrns); ?></div><div class="col-md-3 text-md-end"><strong>Total</strong><br><span class="fs-5 fw-bold"><?php echo money_fmt($viewPo['total_amount']); ?></span></div></div>
    <?php if(!empty($viewPo['notes'])): ?><div class="alert alert-info"><strong>Notes:</strong><br><?php echo nl2br(h($viewPo['notes'])); ?></div><?php endif; ?>
    <?php if(!empty($viewPo['rejection_reason'])): ?><div class="alert alert-danger"><strong>Rejected reason:</strong><br><?php echo nl2br(h($viewPo['rejection_reason'])); ?></div><?php endif; ?>

    <h6 class="fw-bold">Items</h6><div class="table-responsive mb-4"><table class="table table-sm align-middle"><thead><tr><th>Item</th><th class="text-end">Ordered</th><th class="text-end">Received</th><th class="text-end">Remaining</th><th class="text-end">Unit Cost</th><th class="text-end">Total</th></tr></thead><tbody>
    <?php if(!$viewItems): ?><tr><td colspan="6" class="text-center text-muted py-3">No items found.</td></tr><?php else: foreach($viewItems as $line): $rem=max(0,(float)$line['qty_ordered']-(float)$line['qty_received']); ?>
      <tr><td><strong><?php echo h($line['item_name'] ?: ('Item #'.$line['item_id'])); ?></strong><div class="small text-muted"><?php echo h($line['item_code'] ?? ''); ?></div></td><td class="text-end"><?php echo qty_fmt($line['qty_ordered']); ?></td><td class="text-end"><?php echo qty_fmt($line['qty_received']); ?></td><td class="text-end fw-bold"><?php echo qty_fmt($rem); ?></td><td class="text-end"><?php echo money_fmt($line['unit_cost']); ?></td><td class="text-end fw-bold"><?php echo money_fmt($line['line_total']); ?></td></tr>
    <?php endforeach; endif; ?></tbody><tfoot><tr><th colspan="5" class="text-end">Subtotal</th><th class="text-end"><?php echo money_fmt($viewPo['subtotal']); ?></th></tr><tr><th colspan="5" class="text-end">Tax</th><th class="text-end"><?php echo money_fmt($viewPo['tax_amount']); ?></th></tr><tr><th colspan="5" class="text-end fs-5">Total</th><th class="text-end fs-5"><?php echo money_fmt($viewPo['total_amount']); ?></th></tr></tfoot></table></div>

    <?php if($viewGrns): ?><h6 class="fw-bold">GRNs From This PO</h6><div class="table-responsive mb-4"><table class="table table-sm align-middle"><thead><tr><th>Date</th><th>GRN</th><th>Invoice</th><th>Status</th><th class="text-end">Total</th><th></th></tr></thead><tbody><?php foreach($viewGrns as $g): ?><tr><td><?php echo h($g['grn_date']); ?></td><td><strong><?php echo h($g['grn_no']); ?></strong></td><td><?php echo h($g['invoice_no'] ?: '—'); ?></td><td><span class="badge <?php echo $g['status']==='posted'?'text-bg-success':'text-bg-danger'; ?>"><?php echo h(ucwords($g['status'])); ?></span></td><td class="text-end fw-bold"><?php echo money_fmt($g['total_amount']); ?></td><td class="text-end"><a href="grn.php?view_id=<?php echo (int)$g['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i></a></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?>

    <div class="d-flex flex-wrap gap-2 no-print">
      <?php if(in_array($viewPo['status'],['draft','rejected'],true)): ?><form method="post"><?php if(function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="submit_for_approval"><input type="hidden" name="po_id" value="<?php echo (int)$viewPo['id']; ?>"><button class="btn btn-warning"><i class="bi bi-send-check me-2"></i>Submit for Approval</button></form><?php endif; ?>
      <?php if(in_array($viewPo['status'],['draft','pending_approval'],true)): ?><form method="post" id="approvePoForm<?php echo (int)$viewPo['id']; ?>"><?php if(function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="approve_po"><input type="hidden" name="po_id" value="<?php echo (int)$viewPo['id']; ?>"><input type="hidden" name="manager_approved" value="0"><input type="hidden" name="manager_password" value=""><button type="button" class="btn btn-success manager-approval-trigger" data-action-title="Approve Purchase Order <?php echo h($viewPo['po_no']); ?>" data-action-message="Manager approval is required before approving this purchase order." data-target-form="#approvePoForm<?php echo (int)$viewPo['id']; ?>"><i class="bi bi-shield-check me-2"></i>Approve</button></form><?php endif; ?>
      <?php if($viewPo['status']==='pending_approval'): ?><button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#rejectPoModal<?php echo (int)$viewPo['id']; ?>"><i class="bi bi-x-circle me-2"></i>Reject</button><?php endif; ?>
      <?php if(in_array($viewPo['status'],['approved','part_received'],true)): ?><a href="purchase_orders.php?view_id=<?php echo (int)$viewPo['id']; ?>" class="btn btn-primary"><i class="bi bi-box-arrow-in-down me-2"></i>Receive Goods / Create GRN</a><?php endif; ?>
    </div>
  </div>
</div>
<?php if($viewPo['status']==='pending_approval'): ?><div class="modal fade" id="rejectPoModal<?php echo (int)$viewPo['id']; ?>" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><form method="post"><?php if(function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="reject_po"><input type="hidden" name="po_id" value="<?php echo (int)$viewPo['id']; ?>"><div class="modal-header"><h5 class="modal-title">Reject <?php echo h($viewPo['po_no']); ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><label class="form-label">Rejection Reason</label><textarea name="rejection_reason" class="form-control" rows="4" required></textarea></div><div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-danger">Reject</button></div></form></div></div></div><?php endif; ?>
<?php endif; ?>

<div class="card panel-card mb-4 no-print compact-filter-card">
  <div class="card-body">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-6 col-lg-1"><label class="form-label">From</label><input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>"></div>
      <div class="col-6 col-lg-1"><label class="form-label">To</label><input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>"></div>
      <div class="col-6 col-lg-2"><label class="form-label">Status</label><select name="status" class="form-select"><option value="">All</option><?php foreach(['draft','pending_approval','approved','rejected','part_received','received','cancelled','void'] as $st): ?><option value="<?php echo h($st); ?>" <?php echo $status===$st?'selected':''; ?>><?php echo h(ucwords(str_replace('_',' ',$st))); ?></option><?php endforeach; ?></select></div>
      <div class="col-6 col-lg-2"><label class="form-label">Supplier</label><select name="supplier_id" class="form-select"><option value="0">All</option><?php foreach($suppliers as $s): ?><option value="<?php echo (int)$s['id']; ?>" <?php echo $supplierId===(int)$s['id']?'selected':''; ?>><?php echo h($s['supplier_name']); ?></option><?php endforeach; ?></select></div>
      <div class="col-6 col-lg-2"><label class="form-label">Store</label><select name="store_id" class="form-select"><option value="0">All</option><?php foreach($stores as $s): ?><option value="<?php echo (int)$s['id']; ?>" <?php echo $storeId===(int)$s['id']?'selected':''; ?>><?php echo h($s['location_name']); ?></option><?php endforeach; ?></select></div>
      <div class="col-6 col-lg-2"><label class="form-label">Search</label><input type="text" name="q" class="form-control" value="<?php echo h($search); ?>"></div>
      <div class="col-6 col-lg-1 d-grid"><button class="btn btn-primary compact-action-btn" title="Filter"><i class="bi bi-funnel me-1"></i>Filter</button></div>
      <div class="col-6 col-lg-1 d-grid"><button type="submit" name="export" value="excel" class="btn btn-success compact-action-btn" title="Export Excel"><i class="bi bi-file-earmark-excel me-1"></i>Excel</button></div>
    </form>
  </div>
</div>

<div class="card panel-card no-print po-card">
  <div class="card-header d-flex justify-content-between align-items-center po-card-header">
    <h5 class="mb-0">Inventory Purchase Orders</h5>
    <span class="small text-muted">Showing latest 500</span>
  </div>
  <div class="card-body p-0">
    <div class="po-table-scroll" id="poTableScroll">
      <table class="table table-modern align-middle mb-0 po-sticky-table">
        <thead>
          <tr>
            <th>Date</th>
            <th>PO No</th>
            <th>Supplier</th>
            <th>Store</th>
            <th>Status</th>
            <th class="text-end">Lines</th>
            <th class="text-end">Ordered</th>
            <th class="text-end">Received</th>
            <th class="text-end">GRNs</th>
            <th class="text-end">Total</th>
            <th>Approved</th>
            <th class="text-end">Action</th>
          </tr>
        </thead>
        <tbody>
<?php if(!$orders): ?><tr><td colspan="12" class="text-center text-muted py-4">No purchase orders found for the selected filters.</td></tr><?php else: foreach($orders as $o): ?>
<tr class="<?php echo $o['status']==='pending_approval'?'table-warning':($o['status']==='rejected'?'table-danger':''); ?>"><td><?php echo h($o['po_date']); ?><div class="small text-muted"><?php echo h(!empty($o['created_at'])?date('Y-m-d H:i',strtotime($o['created_at'])):''); ?></div></td><td><strong><?php echo h($o['po_no']); ?></strong></td><td><?php echo h($o['supplier_display'] ?: 'Supplier'); ?></td><td><?php echo h($o['location_name'] ?: 'Store'); ?></td><td><span class="badge <?php echo h(poa_status_badge($o['status'])); ?>"><?php echo h(ucwords(str_replace('_',' ',$o['status']))); ?></span></td><td class="text-end"><?php echo (int)$o['line_count']; ?></td><td class="text-end"><?php echo qty_fmt($o['total_qty']); ?></td><td class="text-end"><?php echo qty_fmt($o['received_qty']); ?></td><td class="text-end"><span class="badge <?php echo (int)$o['grn_count']>0?'text-bg-success':'text-bg-light'; ?>"><?php echo (int)$o['grn_count']; ?></span><?php if(!empty($o['last_grn_date'])): ?><div class="small text-muted"><?php echo h($o['last_grn_date']); ?></div><?php endif; ?></td><td class="text-end fw-bold"><?php echo money_fmt($o['total_amount']); ?></td><td><?php echo h($o['approved_by_name'] ?: '—'); ?><div class="small text-muted"><?php echo h($o['approved_at'] ?: ''); ?></div></td><td class="text-end"><div class="btn-group btn-group-sm"><a href="purchase_order_approvals.php?po_id=<?php echo (int)$o['id']; ?>" class="btn btn-outline-primary"><i class="bi bi-eye"></i></a><a href="purchase_orders.php?view_id=<?php echo (int)$o['id']; ?>" class="btn btn-outline-success"><i class="bi bi-box-arrow-in-down"></i></a><?php if(in_array($o['status'],['draft','rejected'],true)): ?><form method="post" class="d-inline"><?php if(function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="submit_for_approval"><input type="hidden" name="po_id" value="<?php echo (int)$o['id']; ?>"><button class="btn btn-outline-warning" title="Submit"><i class="bi bi-send-check"></i></button></form><?php endif; ?><?php if(in_array($o['status'],['draft','pending_approval'],true)): ?><form method="post" id="approvePoRowForm<?php echo (int)$o['id']; ?>" class="d-inline"><?php if(function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="approve_po"><input type="hidden" name="po_id" value="<?php echo (int)$o['id']; ?>"><input type="hidden" name="manager_approved" value="0"><input type="hidden" name="manager_password" value=""><button type="button" class="btn btn-outline-success manager-approval-trigger" data-action-title="Approve Purchase Order <?php echo h($o['po_no']); ?>" data-action-message="Manager approval is required before approving this purchase order." data-target-form="#approvePoRowForm<?php echo (int)$o['id']; ?>"><i class="bi bi-check-circle"></i></button></form><?php endif; ?></div></td></tr>
<?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<style>

/* Ultra compact top part */
.hero-band{
    padding:9px 14px!important;
    margin-bottom:8px!important;
}
.hero-band .row{
    --bs-gutter-x:.75rem!important;
    --bs-gutter-y:.4rem!important;
}
.page-eyebrow{
    font-size:.66rem!important;
    letter-spacing:.06em!important;
    line-height:1!important;
}
.hero-title{
    font-size:1.22rem!important;
    line-height:1.1!important;
    margin-top:2px!important;
}
.hero-subtitle{
    font-size:.76rem!important;
    line-height:1.15!important;
    margin-top:2px!important;
}
.hero-band .btn{
    padding:5px 9px!important;
    font-size:.78rem!important;
    border-radius:8px!important;
}
.row.g-4.mb-4{
    margin-bottom:8px!important;
    --bs-gutter-x:.65rem!important;
    --bs-gutter-y:.65rem!important;
}
.metric-card{
    padding:7px 9px!important;
    gap:6px!important;
    min-height:50px!important;
}
.metric-icon{
    width:29px!important;
    height:29px!important;
    border-radius:8px!important;
    font-size:12px!important;
}
.metric-label{
    font-size:.67rem!important;
    line-height:1.05!important;
    margin-bottom:1px!important;
}
.metric-value{
    font-size:.95rem!important;
    line-height:1.05!important;
}
.panel-card.mb-4{
    margin-bottom:8px!important;
}
.panel-card .card-header{
    padding:8px 10px!important;
}
.panel-card .card-body{
    padding:8px 10px!important;
}
.form-label{
    font-size:.68rem!important;
    margin-bottom:1px!important;
    font-weight:700!important;
}
.form-control,.form-select{
    height:29px!important;
    min-height:29px!important;
    font-size:.78rem!important;
    padding:3px 7px!important;
    border-radius:8px!important;
}
.btn{
    border-radius:8px;
}
.card-header h5{
    font-size:1rem!important;
}
.table-modern th,.table-modern td{
    padding:6px 8px!important;
    font-size:.82rem!important;
}
.po-table-scroll{
    max-height:calc(100vh - 245px)!important;
}

.small-value{font-size:1rem!important;letter-spacing:0!important}
.approval-detail{border:2px solid rgba(37,99,235,.18)}
.table-modern td,.table-modern th{white-space:nowrap}

/* Enterprise sticky Purchase Order table */
.po-card{overflow:hidden}
.po-card-header{position:relative;z-index:3;background:#fff}
.po-table-scroll{
    max-height:680px;
    overflow-y:auto;
    overflow-x:auto;
    position:relative;
    border-radius:0 0 18px 18px;
    background:#fff;
    -webkit-overflow-scrolling:touch;
}
.po-sticky-table{
    border-collapse:separate!important;
    border-spacing:0!important;
    margin-bottom:0!important;
}
.po-sticky-table thead{position:relative;z-index:10}
.po-sticky-table thead th{
    position:sticky!important;
    top:0!important;
    z-index:25!important;
    background:#f8fafc!important;
    color:#0f172a!important;
    font-weight:800!important;
    border-bottom:1px solid #cbd5e1!important;
    box-shadow:0 2px 8px rgba(15,23,42,.14)!important;
}
.po-sticky-table tbody td{background-clip:padding-box}
.po-sticky-table thead th:first-child{border-top-left-radius:0}
.po-sticky-table thead th:last-child{border-top-right-radius:0}

@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    body{background:#fff!important}
    .panel-card,.card,.metric-card{box-shadow:none!important}
    .po-table-scroll{max-height:none!important;overflow:visible!important}
    .po-sticky-table thead th{position:static!important;box-shadow:none!important}
}
</style>
<?php
if (file_exists(__DIR__ . '/../../includes/manager_approval_modal.php')) require_once __DIR__ . '/../../includes/manager_approval_modal.php';
require_once __DIR__ . '/../../includes/footer.php';
?>
