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

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

// Fetch Purchase Header
$query = "
    SELECT 
        pe.*,
        w.warehouse_name,
        w.location AS warehouse_location,
        p.project_code,
        p.project_name
        
    FROM purchase_entries pe
    LEFT JOIN warehouse_master w ON pe.warehouse_id = w.id
    LEFT JOIN project_master p ON pe.project_id = p.id
    
    WHERE pe.id = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $purchase_id);
$stmt->execute();
$purchase = $stmt->get_result()->fetch_assoc();

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

// Fetch Items
$items_query = "
    SELECT 
        pei.*,
        COALESCE(i.name, pei.name) AS item_name,
        COALESCE(i.model_no, pei.model_no) AS model_no,
        COALESCE(i.hsn_sac, pei.hsn_sac) AS hsn_sac,
        COALESCE(i.sku, pei.sku) AS sku
    FROM purchase_entry_items pei
    LEFT JOIN inventory_master i ON i.sku = pei.sku
    WHERE pei.purchase_entry_id = ?
    ORDER BY pei.serial_no ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $purchase_id);
$items_stmt->execute();
$items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase Entry #<?= str_pad($purchase_id, 6, '0', STR_PAD_LEFT) ?> | Technocool</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;
            padding: 10mm;
        }

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

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

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

        .company-info p {
            margin: 0;
            font-size: 11pt;
            color: #64748b;
        }

        .doc-title {
            text-align: right;
        }
        .doc-title h2 {
            margin: 0;
            font-size: 22pt;
            color: #1e2937;
        }
        .doc-title p {
            margin: 5px 0 0 0;
            font-size: 13pt;
        }

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin: 30px 0;
        }
        .info-item {
            padding: 12px 0;
        }
        .info-item label {
            font-size: 10pt;
            color: #64748b;
            display: block;
            margin-bottom: 4px;
        }
        .info-item p {
            font-size: 11.5pt;
            font-weight: 600;
            margin: 0;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 30px 0;
        }
        th, td {
            border: 1px solid #cbd5e1;
            padding: 10px 12px;
            text-align: left;
            vertical-align: top;
        }
        th {
            background: #6b21a8;
            color: white;
            font-weight: 600;
        }
        td {
            font-size: 10.5pt;
        }

        .totals {
            width: 100%;
            margin-top: 40px;
            text-align: right;
        }
        .totals table {
            width: 45%;
            margin-left: auto;
            border-collapse: collapse;
        }
        .totals td {
            padding: 10px 15px;
            border: 1px solid #cbd5e1;
        }
        .totals .label {
            font-weight: 600;
            background: #f8fafc;
            text-align: right;
        }
        .totals .grand {
            font-size: 15pt;
            font-weight: 700;
            background: #6b21a8;
            color: white;
        }

        .footer {
            margin-top: 60px;
            text-align: center;
            font-size: 9.5pt;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
            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>
            <!-- Update this path to your actual logo file -->
            <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>Your Trusted Partner in HVAC Solutions</p>
            </div>
        </div>

        <div class="doc-title">
            <h2>PURCHASE ENTRY</h2>
            <p># <?= str_pad($purchase_id, 6, '0', STR_PAD_LEFT) ?></p>
            <p>Date: <?= date('d M Y', strtotime($purchase['created_at'] ?? date('Y-m-d'))) ?></p>
        </div>
    </div>

    <!-- Info Section -->
    <div class="info-grid">
        <div class="info-item">
            <label>Warehouse</label>
            <p><?= htmlspecialchars($purchase['warehouse_name'] ?? '—') ?> 
               (<?= htmlspecialchars($purchase['warehouse_location'] ?? '') ?>)</p>
        </div>
        <div class="info-item">
            <label>Project</label>
            <p><?= htmlspecialchars($purchase['project_name'] ?? 'Central Purchase') ?> 
               <?= $purchase['project_code'] ? '(' . htmlspecialchars($purchase['project_code']) . ')' : '' ?></p>
        </div>
        <div class="info-item">
            <label>Invoice Number</label>
            <p><?= htmlspecialchars($purchase['invoice_id'] ?? '—') ?></p>
        </div>
        <div class="info-item">
            <label>Created By</label>
            <p><?= htmlspecialchars($purchase['created_by_name'] ?? 'System') ?></p>
        </div>
    </div>

    <!-- Items Table -->
    <table>
        <thead>
            <tr>
                <th style="width:5%">Sr.</th>
                <th style="width:12%">SKU</th>
                <th style="width:12%">Model No</th>
                <th>Item Name</th>
                <th>Description</th>
                <th style="width:10%">HSN/SAC</th>
                <th style="width:8%">Qty</th>
                <th style="width:10%">Rate (₹)</th>
                <th style="width:10%">Discount (₹)</th>
                <th style="width:12%">Basic Amount</th>
                <th style="width:10%">Line Total</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $sr = 1;
            $grand_total = 0;
            foreach ($items as $item): 
                $basic = ($item['quantity'] ?? 0) * ($item['rate'] ?? 0);
                $line_total = $basic - ($item['discount'] ?? 0);
                $grand_total += $line_total;
            ?>
            <tr>
                <td><?= $sr++ ?></td>
                <td><?= htmlspecialchars($item['sku'] ?: '—') ?></td>
                <td><?= htmlspecialchars($item['model_no'] ?: '—') ?></td>
                <td><?= htmlspecialchars($item['item_name']) ?></td>
                <td><?= htmlspecialchars($item['description'] ?? '—') ?></td>
                <td><?= htmlspecialchars($item['hsn_sac'] ?: '—') ?></td>
                <td><?= number_format($item['quantity'] ?? 0, 3) ?></td>
                <td>₹ <?= number_format($item['rate'] ?? 0, 2) ?></td>
                <td>₹ <?= number_format($item['discount'] ?? 0, 2) ?></td>
                <td>₹ <?= number_format($basic, 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(array_sum(array_column($items, 'quantity')) * array_sum(array_column($items, 'rate')), 2) ?></td>
            </tr>
            <tr>
                <td class="label">Total Discount</td>
                <td>₹ <?= number_format(array_sum(array_column($items, 'discount')), 2) ?></td>
            </tr>
            <tr>
                <td class="label">Taxable Amount</td>
                <td>₹ <?= number_format($grand_total, 2) ?></td>
            </tr>
            <tr>
                <td class="label">GST (18%)</td>
                <td>₹ <?= number_format($grand_total * 0.18, 2) ?></td>
            </tr>
            <tr class="grand">
                <td>Grand Total</td>
                <td>₹ <?= number_format($grand_total + ($grand_total * 0.18), 2) ?></td>
            </tr>
        </table>
    </div>

    <!-- Footer -->
    <div class="footer">
        This is a computer-generated Purchase Entry • Original Copy<br>
        Generated on <?= date('d M Y h:i A') ?> | Thank you for choosing Technocool HVAC Engineers
    </div>

</div>

</body>
</html>

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