<?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();
}

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

// Fetch PO 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);
?>

<!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) ?> | 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.10);
            --glass-border: rgba(255,255,255,0.20);
        }

        * { 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.78), rgba(0,0,0,0.92)), 
                        url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }

        .container { max-width: 1250px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
            position: relative;
        }
        .header h1 {
            font-size: clamp(28px, 5vw, 42px);
            font-weight: 700;
        }

        .top-bar {
            padding: 20px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            background: rgba(255,255,255,0.05);
        }

        .card-content { padding: 40px; }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .info-item label {
            display: block;
            font-size: 0.95rem;
            opacity: 0.75;
            margin-bottom: 6px;
        }

        .info-item p {
            font-size: 1.1rem;
            font-weight: 600;
            word-break: break-word;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 30px 0;
            background: rgba(255,255,255,0.03);
            border-radius: 16px;
            overflow: hidden;
        }

        th {
            background: rgba(168,85,247,0.3);
            padding: 18px 14px;
            text-align: left;
            font-weight: 600;
        }

        td {
            padding: 16px 14px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        tr:hover {
            background: rgba(255,255,255,0.06);
        }

        .total-row {
            background: rgba(168,85,247,0.2);
            font-weight: 700;
            font-size: 1.25rem;
        }

        .remarks-box {
            margin-top: 40px;
            padding: 25px;
            background: rgba(255,255,255,0.06);
            border-left: 5px solid var(--primary);
            border-radius: 16px;
        }

        .btn {
            padding: 12px 28px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }

        .btn-print {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            box-shadow: 0 10px 25px rgba(168,85,247,0.4);
        }

        @media (max-width: 768px) {
            .glass-container { border-radius: 24px; }
            .header, .top-bar, .card-content { padding: 30px 20px; }
            .info-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

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

        <!-- Header -->
        <div class="header">
            <a href="po_list.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                ← Back to Purchase Orders
            </a>
            <h1><i class="fas fa-file-invoice"></i> Purchase Order</h1>
            <p style="margin-top:12px; opacity:0.9;">PO-<?= str_pad($po_id, 5, '0', STR_PAD_LEFT) ?></p>
        </div>

        <div class="top-bar">
            <div></div>
            <a href="po_print.php?id=<?= $po_id ?>" target="_blank" class="btn btn-print">
                <i class="fas fa-print"></i> Print / Download PDF
            </a>
        </div>

        <div class="card-content">

            <!-- PO Information -->
            <div class="info-grid">
                <div class="info-item">
                    <label>PO Date</label>
                    <p><?= date('d M Y', strtotime($po['po_date'])) ?></p>
                </div>
                <div class="info-item">
                    <label>Vendor</label>
                    <p><?= htmlspecialchars($po['vendor']) ?></p>
                </div>
                <div class="info-item">
                    <label>Project</label>
                    <p>
                        <?php if ($po['project_code']): ?>
                            <?= htmlspecialchars($po['project_code']) ?> - <?= htmlspecialchars($po['project_name']) ?>
                        <?php else: ?>
                            <em>Central / General Purchase</em>
                        <?php endif; ?>
                    </p>
                </div>
                <div class="info-item">
                    <label>Expected Delivery</label>
                    <p><?= $po['delivery_date'] ? date('d M Y', strtotime($po['delivery_date'])) : '—' ?></p>
                </div>
            </div>

            <div class="info-grid">
                <div class="info-item">
                    <label>Ship To Address</label>
                    <p><?= nl2br(htmlspecialchars($po['ship_to_address'] ?: '—')) ?></p>
                </div>
                <div class="info-item">
                    <label>Created By</label>
                    <p><?= htmlspecialchars($po['created_by_name'] ?? 'System') ?></p>
                    <small style="opacity:0.7;"><?= date('d M Y h:i A', strtotime($po['created_at'])) ?></small>
                </div>
            </div>

            <!-- Items Table -->
            <h3 style="margin:35px 0 15px; color:#ddd6fe;">Items</h3>
            <table>
                <thead>
                    <tr>
                        <th style="width:50px;">Sr.</th>
                        <th>Model No</th>
                        <th>Description</th>
                        <th>HSN/SAC</th>
                        <th>Qty</th>
                        <th>Rate (₹)</th>
                        <th>UOM</th>
                        <th>Basic Amount</th>
                        <th>CGST %</th>
                        <th>SGST %</th>
                        <th>IGST %</th>
                        <th style="text-align:right;">Line Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $sr = 1; 
                    $grand_total = 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);
                        $line_total = $basic + $gst_amount;
                        $grand_total += $line_total;
                    ?>
                    <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;">₹ <?= number_format($line_total, 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="total-row">
                        <td colspan="11" style="text-align:right;">Grand Total</td>
                        <td style="text-align:right;">₹ <?= number_format($grand_total, 2) ?></td>
                    </tr>
                </tfoot>
            </table>

            <?php if (!empty($po['remarks'])): ?>
            <div class="remarks-box">
                <strong>Remarks / Special Notes:</strong><br><br>
                <?= nl2br(htmlspecialchars($po['remarks'])) ?>
            </div>
            <?php endif; ?>

        </div>
    </div>
</div>

</body>
</html>

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