<?php
session_start();
require_once("../config/config.php");

$po_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($po_id <= 0) {
    die("<h2 style='color:red;text-align:center;padding:100px;'>Invalid Purchase Order ID</h2>");
}

// Fetch PO Header
$query = "
    SELECT 
        po.*,
        p.project_code,
        p.project_name,
        u.full_name AS created_by_name
    FROM purchase_order po
    LEFT JOIN project_master p ON po.project_id = p.id
    LEFT JOIN users u ON po.created_by = u.id
    WHERE po.id = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $po_id);
$stmt->execute();
$po = $stmt->get_result()->fetch_assoc();

if (!$po) {
    die("<h2 style='color:red;text-align:center;padding:100px;'>Purchase Order not found.</h2>");
}

// Fetch Items
$items_query = "
    SELECT 
        poi.*,
        i.name AS item_name
    FROM purchase_order_items poi
    LEFT JOIN inventory_master i ON poi.item_id = i.id
    WHERE poi.po_id = ?
    ORDER BY poi.id ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $po_id);
$items_stmt->execute();
$items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Calculate Totals
$basic_total = 0;
$total_gst = 0;
foreach ($items as $item) {
    $basic = $item['ordered_qty'] * $item['rate'];
    $gst_rate = $item['cgst_rate'] + $item['sgst_rate'] + $item['igst_rate'];
    $gst_amount = $basic * ($gst_rate / 100);
    $basic_total += $basic;
    $total_gst += $gst_amount;
}
$grand_total = $basic_total + $total_gst;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PO-<?= str_pad($po_id, 5, '0', STR_PAD_LEFT) ?> | Purchase Order</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

        @page {
            size: A4 portrait;
            margin: 15mm;
        }

        body {
            font-family: 'Inter', Arial, sans-serif;
            font-size: 11pt;
            line-height: 1.5;
            color: #1f2937;
            background: #fff;
            margin: 0;
            padding: 0;
        }

        .container {
            max-width: 210mm;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 4px solid #8b5cf6;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }

        .logo {
            width: 180px;
            height: auto;
        }

        .company-info h1 {
            margin: 5px 0 0 0;
            font-size: 22pt;
            color: #6b21a8;
            font-weight: 700;
        }

        .po-info {
            text-align: right;
        }
        .po-info h2 {
            margin: 0;
            font-size: 20pt;
            color: #1f2937;
            font-weight: 700;
        }

        .info-table {
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
        }
        .info-table td {
            padding: 10px 12px;
            border: 1px solid #e5e7eb;
            vertical-align: top;
        }
        .info-table .label {
            background: #f3e8ff;
            font-weight: 600;
            width: 35%;
        }

        table.items {
            width: 100%;
            border-collapse: collapse;
            margin: 30px 0;
        }
        table.items th, table.items td {
            border: 1px solid #e5e7eb;
            padding: 10px 8px;
            text-align: left;
        }
        table.items th {
            background: #6b21a8;
            color: white;
            font-weight: 600;
        }

        .totals {
            width: 100%;
            margin-top: 30px;
            text-align: right;
        }
        .totals table {
            width: 50%;
            float: right;
            border-collapse: collapse;
        }
        .totals td {
            padding: 10px 15px;
            border: 1px solid #e5e7eb;
        }
        .totals .label {
            font-weight: 600;
            background: #f3e8ff;
        }
        .totals .grand {
            font-size: 15pt;
            font-weight: 700;
            background: #6b21a8;
            color: white;
        }

        .footer {
            margin-top: 80px;
            text-align: center;
            font-size: 10pt;
            color: #6b7280;
            border-top: 1px solid #e5e7eb;
            padding-top: 15px;
        }

        @media print {
            body { background: white; }
            .no-print { display: none; }
        }
    </style>
</head>
<body>

<div class="container">

    <!-- Header with Logo -->
    <div class="header">
        <div>
            <!-- Replace with your actual logo path -->
            <img src="../technocool-logo.png" alt="Technocool Logo" class="logo" 
                 onerror="this.src='https://via.placeholder.com/180x80/6b21a8/ffffff?text=TECHNOCOOL';">
            <div class="company-info">
                <h1>TECHNOCOOL HVAC ENGINEERS</h1>
                <p style="margin:5px 0 0 0; font-size:11pt;">Your Trusted Partner in HVAC Solutions</p>
            </div>
        </div>

        <div class="po-info">
            <h2>PURCHASE ORDER</h2>
            <p><strong>PO-<?= str_pad($po_id, 5, '0', STR_PAD_LEFT) ?></strong></p>
            <p>Date: <?= date('d M Y', strtotime($po['po_date'])) ?></p>
        </div>
    </div>

    <!-- Vendor & Project Info -->
    <table class="info-table">
        <tr>
            <td class="label">Vendor / Supplier</td>
            <td><?= htmlspecialchars($po['vendor']) ?></td>
        </tr>
        <tr>
            <td class="label">Project</td>
            <td>
                <?php if ($po['project_code']): ?>
                    <?= htmlspecialchars($po['project_code']) ?> - <?= htmlspecialchars($po['project_name']) ?>
                <?php else: ?>
                    Central / General Purchase
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td class="label">Ship To Address</td>
            <td><?= nl2br(htmlspecialchars($po['ship_to_address'] ?: '—')) ?></td>
        </tr>
        <tr>
            <td class="label">Expected Delivery</td>
            <td><?= $po['delivery_date'] ? date('d M Y', strtotime($po['delivery_date'])) : '—' ?></td>
        </tr>
    </table>

    <!-- Items Table -->
    <table class="items">
        <thead>
            <tr>
                <th style="width:5%">Sr.</th>
                <th style="width:12%">Model No</th>
                <th>Description</th>
                <th style="width:10%">HSN/SAC</th>
                <th style="width:10%">Qty</th>
                <th style="width:10%">Rate (₹)</th>
                <th style="width:8%">UOM</th>
                <th style="width:10%">Basic Amount</th>
                <th style="width:8%">CGST %</th>
                <th style="width:8%">SGST %</th>
                <th style="width:8%">IGST %</th>
                <th style="width:12%">Line Total</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $sr = 1;
            foreach ($items as $item): 
                $basic = $item['ordered_qty'] * $item['rate'];
                $gst_rate = $item['cgst_rate'] + $item['sgst_rate'] + $item['igst_rate'];
                $gst_amount = $basic * ($gst_rate / 100);
                $line_total = $basic + $gst_amount;
            ?>
            <tr>
                <td><?= $sr++ ?></td>
                <td><?= htmlspecialchars($item['model_no'] ?: '—') ?></td>
                <td><?= htmlspecialchars($item['description'] ?: $item['item_name']) ?></td>
                <td><?= htmlspecialchars($item['hsn_sac'] ?: '—') ?></td>
                <td><?= number_format($item['ordered_qty'], 3) ?></td>
                <td>₹ <?= number_format($item['rate'], 2) ?></td>
                <td><?= htmlspecialchars($item['unit']) ?></td>
                <td>₹ <?= number_format($basic, 2) ?></td>
                <td><?= number_format($item['cgst_rate'], 2) ?>%</td>
                <td><?= number_format($item['sgst_rate'], 2) ?>%</td>
                <td><?= number_format($item['igst_rate'], 2) ?>%</td>
                <td style="text-align:right; font-weight:600;">₹ <?= number_format($line_total, 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Totals -->
    <div class="totals">
        <table>
            <tr>
                <td class="label">Basic Total</td>
                <td>₹ <?= number_format($basic_total, 2) ?></td>
            </tr>
            <tr>
                <td class="label">Taxable Amount</td>
                <td>₹ <?= number_format($basic_total, 2) ?></td>
            </tr>
            <tr>
                <td class="label">Total GST</td>
                <td>₹ <?= number_format($total_gst, 2) ?></td>
            </tr>
            <tr class="grand">
                <td>Grand Total</td>
                <td>₹ <?= number_format($grand_total, 2) ?></td>
            </tr>
        </table>
    </div>

    <!-- Remarks -->
    <?php if (!empty($po['remarks'])): ?>
    <div style="margin-top:40px; padding:15px; border:1px solid #e5e7eb; border-radius:8px;">
        <strong>Remarks:</strong><br>
        <?= nl2br(htmlspecialchars($po['remarks'])) ?>
    </div>
    <?php endif; ?>

    <div class="footer">
        This is a computer-generated Purchase Order.<br>
        Generated on <?= date('d M Y h:i A') ?> | Thank you for your business.
    </div>

</div>

</body>
</html>

<?php
$stmt->close();
$items_stmt->close();
$conn->close();
?>