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

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

// Fetch Delivery Challan Header
$query = "
    SELECT 
        dc.*,
        p.project_code,
        p.project_name,
        u.full_name AS issued_by_name
    FROM delivery_challan dc
    LEFT JOIN project_master p ON dc.project_id = p.id
    LEFT JOIN users u ON dc.issued_by = u.id
    WHERE dc.id = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $dc_id);
$stmt->execute();
$dc = $stmt->get_result()->fetch_assoc();

if (!$dc) {
    die("<h2 style='color:#ef4444;text-align:center;padding:120px;'>Delivery Challan not found.</h2>");
}

// Fetch Items
$items_query = "
    SELECT 
        dci.*,
        i.name AS item_name,
        i.model_no AS item_model,
        i.description AS item_description
    FROM delivery_challan_items dci
    INNER JOIN inventory_master i ON dci.item_id = i.id
    WHERE dci.dc_id = ?
    ORDER BY i.name ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $dc_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>Delivery Challan #<?= str_pad($dc_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.09);
            --glass-border: rgba(255,255,255,0.18);
            --text: #f1f5f9;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, 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: var(--text);
            min-height: 100vh;
            padding: 20px 15px;
        }

        .container {
            max-width: 1200px;
            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;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .back-link {
            color: #c4b5fd;
            text-decoration: none;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .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;
            box-shadow: 0 12px 30px rgba(168,85,247,0.4);
            transition: all 0.3s ease;
        }

        .print-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 18px 40px rgba(168,85,247,0.5);
        }

        .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;
        }

        .section-title {
            font-size: 1.45rem;
            margin: 40px 0 20px;
            color: #e0e7ff;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(255,255,255,0.04);
            border-radius: 20px;
            overflow: hidden;
            margin-bottom: 30px;
        }

        th {
            background: rgba(168,85,247,0.35);
            padding: 18px 16px;
            text-align: left;
            font-weight: 600;
            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);
        }

        .status-badge {
            padding: 8px 20px;
            border-radius: 9999px;
            font-size: 0.95rem;
            font-weight: 700;
        }
        .status-Issued    { background: #f59e0b; color: white; }
        .status-Delivered { background: #22c55e; color: white; }
        .status-Cancelled { background: #ef4444; color: white; }

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

        .remarks-box {
            background: rgba(168,85,247,0.1);
            border-left: 6px solid var(--primary);
            border-radius: 16px;
            padding: 28px;
            margin-top: 40px;
        }

        .footer {
            text-align: center;
            margin-top: 60px;
            padding: 30px;
            opacity: 0.7;
            font-size: 0.95rem;
        }

        @media (max-width: 992px) {
            .info-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .content { padding: 30px 25px; }
            .header { padding: 40px 25px; }
            table { font-size: 0.95rem; }
            th, td { padding: 14px 12px; }
        }

        /* Horizontal scroll for table on mobile */
        @media (max-width: 640px) {
            .content { overflow-x: auto; }
            table { min-width: 1000px; }
        }
    </style>
</head>
<body>

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

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

        <!-- Header -->
        <div class="header">
            <div>
                <a href="dc_list.php" class="back-link">
                    ← Back to Delivery Challans
                </a>
                <h1><i class="fas fa-truck"></i> Delivery Challan</h1>
            </div>
            <a href="dc_print.php?id=<?= $dc_id ?>" target="_blank" class="print-btn">
                <i class="fas fa-print"></i> Print Challan
            </a>
        </div>

        <div class="content">

            <!-- Challan Info -->
            <div style="margin-bottom: 30px;">
                <h2 style="color:#ddd6fe;">DC-<?= str_pad($dc_id, 5, '0', STR_PAD_LEFT) ?></h2>
                <span class="status-badge status-<?= htmlspecialchars($dc['status']) ?>">
                    <?= htmlspecialchars($dc['status']) ?>
                </span>
            </div>

            <!-- Information Grid -->
            <div class="info-grid">
                <div class="info-card">
                    <div class="info-label">DC Date</div>
                    <div class="info-value"><?= date('d M Y', strtotime($dc['dc_date'])) ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">Project / Site</div>
                    <div class="info-value">
                        <?= $dc['project_code'] 
                            ? htmlspecialchars($dc['project_code']) . ' - ' . htmlspecialchars($dc['project_name']) 
                            : 'Central / General' ?>
                    </div>
                </div>

                <div class="info-card">
                    <div class="info-label">Receiver Name</div>
                    <div class="info-value"><?= htmlspecialchars($dc['receiver_name']) ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">Receiver Mobile</div>
                    <div class="info-value"><?= htmlspecialchars($dc['receiver_mobile'] ?: '—') ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">Delivery Address</div>
                    <div class="info-value"><?= nl2br(htmlspecialchars($dc['delivery_address'] ?: '—')) ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">Client GST Number</div>
                    <div class="info-value"><?= htmlspecialchars($dc['client_gst_number'] ?: '—') ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">Vehicle Number</div>
                    <div class="info-value"><?= htmlspecialchars($dc['vehicle_no'] ?: '—') ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">Issued By</div>
                    <div class="info-value"><?= htmlspecialchars($dc['issued_by_name'] ?? 'Store Team') ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">PO Number</div>
                    <div class="info-value"><?= htmlspecialchars($dc['po_no'] ?: '—') ?></div>
                </div>

                <div class="info-card">
                    <div class="info-label">Eway Bill No.</div>
                    <div class="info-value"><?= htmlspecialchars($dc['eway_bill_no'] ?: '—') ?></div>
                </div>
            </div>

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

            <table>
                <thead>
                    <tr>
                        <th>Model No</th>
                        <th>Serial No</th>
                        <th>Item Name</th>
                        <th>Description</th>
                        <th>Billing Type</th>
                        <th style="text-align:center;">Issued Qty</th>
                        <th>Unit</th>
                        <th style="text-align:right;">Rate (₹)</th>
                        <th style="text-align:right;">Total Value (₹)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $grand_total = 0;
                    foreach ($items as $item): 
                        $line_total = $item['issued_qty'] * ($item['rate'] ?? 0);
                        $grand_total += $line_total;
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($item['item_model'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($item['serial_number'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($item['item_name']) ?></td>
                        <td><?= htmlspecialchars($item['item_description'] ?: '—') ?></td>
                        <td>
                            <span style="padding:6px 16px; border-radius:9999px; background:rgba(168,85,247,0.25); font-size:0.9rem;">
                                <?= htmlspecialchars($item['billing_type'] ?? 'Billable') ?>
                            </span>
                        </td>
                        <td style="text-align:center;"><?= number_format($item['issued_qty'], 3) ?></td>
                        <td><?= htmlspecialchars($item['unit'] ?? 'NOS') ?></td>
                        <td style="text-align:right;">₹ <?= number_format($item['rate'] ?? 0, 2) ?></td>
                        <td style="text-align:right;">₹ <?= number_format($line_total, 2) ?></td>
                    </tr>
                    <?php endforeach; ?>

                    <?php if (empty($items)): ?>
                    <tr>
                        <td colspan="8" style="text-align:center; padding:60px; opacity:0.7;">
                            No items found in this challan.
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
                <tfoot>
                    <tr class="total-row">
                        <td colspan="8" style="text-align:right; padding-right:25px;">Grand Total</td>
                        <td style="text-align:right; padding-right:25px;">₹ <?= number_format($grand_total, 2) ?></td>
                    </tr>
                </tfoot>
            </table>

            <!-- Remarks -->
            <?php if (!empty($dc['remarks'])): ?>
            <div class="remarks-box">
                <strong style="color:#ddd6fe;">Remarks / Purpose of Delivery:</strong><br><br>
                <?= nl2br(htmlspecialchars($dc['remarks'])) ?>
            </div>
            <?php endif; ?>

        </div>

        <div class="footer">
            This is a computer-generated Delivery Challan • Generated on <?= date('d M Y \a\t h:i A') ?>
        </div>

    </div>
</div>

</body>
</html>

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