<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../../dripend/includes/db.php';

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: managePurchaseOrder.php");
    exit;
}

$po_id = (int)$_GET['id'];

// 1. Fetch PO Header
$stmt = $conn->prepare("
    SELECT p.*, s.supplier_name, s.contact_person, s.phone, s.email, s.address, l.location_name 
    FROM purchase_orders p
    JOIN suppliers s ON p.supplier_id = s.id
    JOIN inventory_locations l ON p.location_id = l.id
    WHERE p.id = ?
");
$stmt->bind_param("i", $po_id);
$stmt->execute();
$po = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$po) {
    die("Purchase Order not found.");
}

// 2. Fetch PO Line Items
$stmt_items = $conn->prepare("
    SELECT poi.*, sc.service_name, sc.unit_of_pricing, ic.category_name
    FROM purchase_order_items poi
    JOIN service_catalog sc ON poi.service_id = sc.id
    JOIN item_categories ic ON sc.category_id = ic.id
    WHERE poi.po_id = ?
");
$stmt_items->bind_param("i", $po_id);
$stmt_items->execute();
$items = $stmt_items->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_items->close();

// Badge Status
$badge_class = '';
switch ($po['status']) {
    case 'Pending': $badge_class = 'bg-pending'; break;
    case 'Approved': $badge_class = 'bg-approved'; break;
    case 'Partially Received': $badge_class = 'bg-partial'; break;
    case 'Received': $badge_class = 'bg-received'; break;
    case 'Cancelled': $badge_class = 'bg-cancelled'; break;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Purchase Order <?= htmlspecialchars($po['po_number']) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --sidebar-width: 240px; --bg: #f8fafc; --border: #e2e8f0; --text: #334155; }
    body { font-family: "Segoe UI", system-ui, sans-serif; background: var(--bg); margin: 0; padding: 0; color: var(--text); }
    .page-wrapper { margin-left: var(--sidebar-width); padding: 30px; min-height: 100vh; box-sizing: border-box; }
    
    .invoice-card { background: #fff; max-width: 1000px; margin: 0 auto; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); padding: 40px; border: 1px solid var(--border); }
    
    .invoice-header { display: flex; justify-content: space-between; border-bottom: 2px solid #0f172a; padding-bottom: 20px; margin-bottom: 30px; }
    .invoice-title h1 { margin: 0; color: #0f172a; font-size: 32px; font-weight: 900; text-transform: uppercase; }
    .invoice-title p { margin: 5px 0 0 0; font-size: 16px; color: #64748b; font-weight: 700; font-family: monospace; }
    
    .badge { padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 800; display: inline-flex; align-items: center; gap: 5px; text-transform: uppercase; }
    .bg-pending { background: #fef3c7; color: #b45309; }
    .bg-approved { background: #e0f2fe; color: #0369a1; }
    .bg-partial { background: #e0e7ff; color: #4338ca; }
    .bg-received { background: #dcfce7; color: #166534; }
    .bg-cancelled { background: #fee2e2; color: #991b1b; }

    .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 40px; }
    .info-box h3 { font-size: 14px; color: #94a3b8; text-transform: uppercase; margin: 0 0 10px 0; border-bottom: 1px solid var(--border); padding-bottom: 5px; }
    .info-box p { margin: 4px 0; font-size: 15px; color: #0f172a; font-weight: 600; }
    .info-box i { color: #0284c7; width: 20px; }

    table { width: 100%; border-collapse: collapse; margin-bottom: 30px; }
    th { background: #0f172a; color: #fff; padding: 12px 15px; text-align: left; font-size: 13px; text-transform: uppercase; }
    td { padding: 12px 15px; border-bottom: 1px solid var(--border); font-size: 14px; color: #0f172a; font-weight: 600; }
    .text-right { text-align: right; }
    
    .totals-box { width: 300px; float: right; background: #f8fafc; padding: 20px; border-radius: 8px; border: 1px solid var(--border); }
    .totals-row { display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 14px; font-weight: 700; color: #64748b; }
    .totals-grand { display: flex; justify-content: space-between; margin-top: 10px; padding-top: 10px; border-top: 2px solid #cbd5e1; font-size: 20px; font-weight: 900; color: #16a34a; }

    .remarks-box { clear: both; background: #fffbeb; border-left: 4px solid #f59e0b; padding: 15px 20px; border-radius: 4px; margin-top: 120px; }
    
    .btn-print { background: #0f172a; color: #fff; padding: 12px 25px; border-radius: 8px; text-decoration: none; font-weight: bold; display: inline-block; margin-bottom: 20px; transition: 0.2s; }
    .btn-print:hover { background: #1e293b; }
    
    @media print {
        .sidebar, .btn-print, .header-bar { display: none !important; }
        .page-wrapper { margin-left: 0; padding: 0; width: 100%; }
        .invoice-card { box-shadow: none; border: none; padding: 0; }
    }
</style>
</head>
<body>

<?php include('../../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">
    <div style="max-width: 1000px; margin: 0 auto; display:flex; justify-content:space-between; align-items:center;">
        <a href="managePurchaseOrder.php" style="color:#64748b; text-decoration:none; font-weight:700; font-size:13px;"><i class="fa-solid fa-arrow-left"></i> Back to PO Dashboard</a>
        <button onclick="window.print()" class="btn-print"><i class="fa-solid fa-print"></i> Print / Export PDF</button>
    </div>

    <div class="invoice-card">
        <div class="invoice-header">
            <div class="invoice-title">
                <h1>Purchase Order</h1>
                <p># <?= htmlspecialchars($po['po_number']) ?></p>
            </div>
            <div style="text-align:right;">
                <span class="badge <?= $badge_class ?>"><?= $po['status'] ?></span>
                <p style="margin: 10px 0 0 0; color:#64748b; font-weight:700; font-size:13px;">Date: <?= date('d M Y', strtotime($po['order_date'])) ?></p>
            </div>
        </div>

        <div class="info-grid">
            <div class="info-box">
                <h3><i class="fa-solid fa-building"></i> Supplier Details</h3>
                <p><?= htmlspecialchars($po['supplier_name']) ?></p>
                <p><i class="fa-solid fa-user"></i> <?= htmlspecialchars($po['contact_person'] ?: '--') ?></p>
                <p><i class="fa-solid fa-phone"></i> <?= htmlspecialchars($po['phone'] ?: '--') ?></p>
                <p><i class="fa-solid fa-envelope"></i> <?= htmlspecialchars($po['email'] ?: '--') ?></p>
            </div>
            <div class="info-box">
                <h3><i class="fa-solid fa-truck-fast"></i> Logistics & Delivery</h3>
                <p><strong>Deliver To:</strong></p>
                <p style="color:#0284c7; font-size:18px;"><i class="fa-solid fa-location-dot"></i> <?= htmlspecialchars($po['location_name']) ?></p>
                <p style="margin-top:15px; color:#64748b;"><strong>Expected Delivery:</strong> <?= $po['expected_delivery'] ? date('d M Y', strtotime($po['expected_delivery'])) : 'Immediate' ?></p>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th style="width:5%;">#</th>
                    <th style="width:40%;">Item Description</th>
                    <th style="width:15%; text-align:center;">Qty Ordered</th>
                    <th style="width:15%; text-align:center;">Qty Received</th>
                    <th style="width:12%; text-align:right;">Unit Cost</th>
                    <th style="width:13%; text-align:right;">Line Total</th>
                </tr>
            </thead>
            <tbody>
                <?php $sn = 1; foreach ($items as $item): ?>
                <tr>
                    <td style="color:#64748b;"><?= $sn++ ?></td>
                    <td>
                        <?= htmlspecialchars($item['service_name']) ?><br>
                        <span style="font-size:11px; color:#64748b;">Brand: <?= htmlspecialchars($item['brand_name'] ?: 'Generic') ?> | Category: <?= htmlspecialchars($item['category_name']) ?></span>
                    </td>
                    <td style="text-align:center;"><?= number_format($item['quantity_ordered']) ?> <?= htmlspecialchars($item['unit_of_pricing']) ?></td>
                    <td style="text-align:center; color: <?= $item['quantity_received'] == $item['quantity_ordered'] ? '#16a34a' : '#b45309' ?>;">
                        <?= number_format($item['quantity_received']) ?>
                    </td>
                    <td class="text-right"><?= number_format($item['expected_unit_cost'], 2) ?></td>
                    <td class="text-right"><?= number_format($item['total_line_cost'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="totals-box">
            <div class="totals-row">
                <span>Subtotal:</span>
                <span>GHS <?= number_format($po['total_estimated_cost'], 2) ?></span>
            </div>
            <div class="totals-row">
                <span>Tax/VAT:</span>
                <span>GHS 0.00</span>
            </div>
            <div class="totals-grand">
                <span>Total PO Value:</span>
                <span>GHS <?= number_format($po['total_estimated_cost'], 2) ?></span>
            </div>
        </div>

        <?php if(!empty($po['remarks'])): ?>
        <div class="remarks-box">
            <strong style="color:#b45309; text-transform:uppercase; font-size:12px;">Procurement Remarks:</strong>
            <p style="margin:5px 0 0 0; font-size:14px; color:#78350f;"><?= nl2br(htmlspecialchars($po['remarks'])) ?></p>
        </div>
        <?php endif; ?>

    </div>
</div>
</body>
</html>