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

// Allowed roles
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$purchase_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($purchase_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:120px;font-family:Inter;'>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:120px;'>Purchase Entry not found.</h2>");
}

// Fetch Items with Serial Numbers
$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 #<?= str_pad($purchase_id, 6, '0', STR_PAD_LEFT) ?> - View</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.09);
            --glass-border: rgba(255,255,255,0.18);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.82), rgba(0,0,0,0.95)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            min-height: 100vh;
            padding: 20px 15px;
        }
        .container { max-width: 1400px; margin: 0 auto; }
        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(28px);
            border-radius: 28px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 30px 90px rgba(0,0,0,0.7);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.4), rgba(147,51,234,0.3));
            padding: 50px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }
        .header h1 { font-size: clamp(26px, 5vw, 38px); font-weight: 700; }
        .back-link { color: #c4b5fd; text-decoration: none; font-weight: 500; }
        .print-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 14px 32px;
            border-radius: 9999px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }
        .content { padding: 45px 40px; }
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 24px;
            margin-bottom: 45px;
        }
        .info-card {
            background: rgba(255,255,255,0.06);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            padding: 24px;
        }
        .info-label { font-size: 0.95rem; opacity: 0.75; margin-bottom: 8px; }
        .info-value { font-size: 1.18rem; font-weight: 600; color: #ddd6fe; }

        table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(255,255,255,0.04);
            border-radius: 20px;
            overflow: hidden;
        }
        th {
            background: rgba(168,85,247,0.35);
            padding: 18px 16px;
            text-align: left;
            color: #e0e7ff;
        }
        td {
            padding: 18px 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        tr:hover { background: rgba(255,255,255,0.06); }
        .serial-list {
            font-size: 0.92rem;
            color: #c4b5fd;
            max-height: 120px;
            overflow-y: auto;
            background: rgba(0,0,0,0.2);
            padding: 8px;
            border-radius: 8px;
        }
        .grand-total-row {
            background: rgba(168,85,247,0.25) !important;
            font-size: 1.3rem;
            font-weight: 700;
        }
        .footer {
            text-align: center;
            margin-top: 60px;
            padding: 30px;
            opacity: 0.7;
            font-size: 0.95rem;
        }
        @media (max-width: 768px) {
            .content { padding: 30px 20px; }
            table { font-size: 0.95rem; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="glass-container">

        <!-- Header -->
        <div class="header">
            <div>
                <a href="purchase_list.php" class="back-link">← Back to Purchase List</a>
                <h1><i class="fas fa-receipt"></i> Purchase #<?= str_pad($purchase_id, 6, '0', STR_PAD_LEFT) ?></h1>
            </div>
            <a href="purchase_print.php?id=<?= $purchase_id ?>" target="_blank" class="print-btn">
                <i class="fas fa-print"></i> Print / PDF
            </a>
        </div>

        <div class="content">

            <!-- Info Cards -->
            <div class="info-grid">
                <div class="info-card">
                    <div class="info-label">Warehouse</div>
                    <div class="info-value"><?= htmlspecialchars($purchase['warehouse_name'] ?? '—') ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">Project</div>
                    <div class="info-value"><?= htmlspecialchars($purchase['project_name'] ?? '—') ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">Invoice Number</div>
                    <div class="info-value"><?= htmlspecialchars($purchase['invoice_id'] ?? '—') ?></div>
                </div>
                <div class="info-card">
                    <div class="info-label">Date</div>
                    <div class="info-value"><?= date('d M Y', strtotime($purchase['created_at'])) ?></div>
                </div>
            </div>

            <!-- Items Table -->
            <h3 class="section-title"><i class="fas fa-boxes"></i> Purchased Materials</h3>

            <table>
                <thead>
                    <tr>
                        <th style="width:50px;">Sr.</th>
                        <th>SKU</th>
                        <th>Model No</th>
                        <th>Item Name</th>
                        <th>Description</th>
                        <th>HSN/SAC</th>
                        <th style="text-align:center;">Qty</th>
                        <th style="text-align:right;">Rate</th>
                        <th style="text-align:right;">Discount</th>
                        <th style="text-align:right;">Amount</th>
                        <th style="width:220px;">Serial Numbers</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;

                        // Fetch Serial Numbers for this item
                        $serial_query = "SELECT serial_number FROM purchase_item_serials 
                                         WHERE purchase_entry_item_id = ? ORDER BY serial_number ASC";
                        $s_stmt = $conn->prepare($serial_query);
                        $s_stmt->bind_param("i", $item['id']);
                        $s_stmt->execute();
                        $serials_result = $s_stmt->get_result();
                        $serials = [];
                        while ($s = $serials_result->fetch_assoc()) {
                            $serials[] = $s['serial_number'];
                        }
                        $s_stmt->close();
                    ?>
                    <tr>
                        <td><?= $sr++ ?></td>
                        <td><?= htmlspecialchars($item['sku'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($item['model_no'] ?: '—') ?></td>
                        <td><strong><?= htmlspecialchars($item['item_name']) ?></strong></td>
                        <td><?= htmlspecialchars($item['description'] ?? '—') ?></td>
                        <td><?= htmlspecialchars($item['hsn_sac'] ?: '—') ?></td>
                        <td style="text-align:center;"><?= number_format($item['quantity'] ?? 0, 3) ?></td>
                        <td style="text-align:right;">₹ <?= number_format($item['rate'] ?? 0, 2) ?></td>
                        <td style="text-align:right;">₹ <?= number_format($item['discount'] ?? 0, 2) ?></td>
                        <td style="text-align:right;">₹ <?= number_format($line_total, 2) ?></td>
                        <td>
                            <?php if (!empty($serials)): ?>
                                <div class="serial-list">
                                    <?= implode('<br>', array_map('htmlspecialchars', $serials)) ?>
                                </div>
                            <?php else: ?>
                                <em style="color:#94a3b8;">No serials</em>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="grand-total-row">
                        <td colspan="9" style="text-align:right; padding-right:20px; font-weight:600;">Grand Total</td>
                        <td colspan="2" style="text-align:right; padding-right:20px; font-weight:700;">
                            ₹ <?= number_format($grand_total, 2) ?>
                        </td>
                    </tr>
                </tfoot>
            </table>

        </div>

        <div class="footer">
            Generated on <?= date('d M Y \a\t h:i A') ?> • Technocool HVAC Engineers
        </div>

    </div>
</div>

</body>
</html>

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