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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$full_name = $_SESSION['full_name'] ?? 'User';

// Optional project filter
$project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;

// Build WHERE clause
$where = "";
$params = [];
$types = "";

if ($project_id > 0) {
    $where = " WHERE dc.project_id = ?";
    $params[] = $project_id;
    $types .= "i";
}

// Fetch Delivery Challan List
$query = "
    SELECT 
        dc.id,
        dc.dc_date,
        dc.receiver_name,
        dc.vehicle_no,
        dc.delivery_address,
        dc.client_gst_number,
        dc.status,
        p.project_code,
        p.project_name,
        COUNT(dci.id) AS item_count,
        COALESCE(SUM(dci.issued_qty * COALESCE(dci.rate, 0)), 0) AS total_value,
        COALESCE(SUM(dci.issued_qty), 0) AS total_qty
    FROM delivery_challan dc
    LEFT JOIN project_master p ON dc.project_id = p.id
    LEFT JOIN delivery_challan_items dci ON dc.id = dci.dc_id
    $where
    GROUP BY dc.id
    ORDER BY dc.dc_date DESC, dc.id DESC
    LIMIT 100
";

$stmt = $conn->prepare($query);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$challans = $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 List</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: 1480px;
            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-left h1 {
            font-size: clamp(28px, 5.5vw, 42px);
            font-weight: 700;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .add-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;
            white-space: nowrap;
        }

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

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

        .content {
            padding: 40px;
        }

        .table-container {
            background: rgba(255,255,255,0.06);
            border-radius: 20px;
            overflow: hidden;
            border: 1px solid var(--glass-border);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th {
            background: rgba(168,85,247,0.35);
            padding: 20px 18px;
            text-align: left;
            font-weight: 600;
            color: #e0e7ff;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        td {
            padding: 20px 18px;
            border-bottom: 1px solid rgba(255,255,255,0.08);
        }

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

        .status-badge {
            padding: 8px 20px;
            border-radius: 9999px;
            font-size: 0.9rem;
            font-weight: 700;
            display: inline-block;
        }

        .status-Issued    { background: #f59e0b; color: white; }
        .status-Delivered { background: #22c55e; color: white; }
        .status-Cancelled { background: #ef4444; color: white; }

        .btn-view  { background: rgba(59,130,246,0.25); color: #60a5fa; }
        .btn-edit  { background: rgba(234,179,8,0.25); color: #fde047; }
        .btn-print { background: rgba(34,197,94,0.25); color: #4ade80; }
        .btn-delete{ background: rgba(239,68,68,0.25); color: #f87171; }
        .no-records {
            text-align: center;
            padding: 100px 20px;
            color: #94a3b8;
        }

        .project-info {
            line-height: 1.4;
        }

        .project-code {
            font-weight: 600;
            color: #c4b5fd;
        }

        .amount {
            font-weight: 600;
            color: #a5b4fc;
        }

        .action-btns a {
           padding: 9px 13px;
    border-radius: 10px;
    margin: 0 4px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
            transition: all 0.2s;
        }
        
        .action-btns a:hover {
            color: #ddd6fe;
        }

        .no-records {
            text-align: center;
            padding: 100px 40px;
            color: #94a3b8;
        }

        .no-records i {
            font-size: 5rem;
            opacity: 0.25;
            margin-bottom: 25px;
        }

        @media (max-width: 992px) {
            .header {
                flex-direction: column;
                text-align: center;
            }
        }

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

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

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

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

        <!-- Header -->
        <div class="header">
            <div class="header-left">
                <a href="dashboard_store.php" class="back-link">
                    ← Back to Store Dashboard
                </a>
                <h1><i class="fas fa-truck"></i> Delivery Challans</h1>
            </div>
            
            <a href="delivery_challan.php" class="add-btn">
                <i class="fas fa-plus"></i> Create New Delivery Challan
            </a>
        </div>

        <!-- Content -->
        <div class="content">
            <?php if (empty($challans)): ?>
                <div class="no-records">
                    <i class="fas fa-truck"></i>
                    <h2>No Delivery Challans Yet</h2>
                    <p>Start issuing materials by creating your first delivery challan.</p>
                    <a href="delivery_challan.php" class="add-btn" style="margin-top: 25px; display: inline-flex;">
                        <i class="fas fa-plus"></i> Create First Challan
                    </a>
                </div>
            <?php else: ?>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>DC Date</th>
                                <th>Receiver Name</th>
                                <th>Project</th>
                                <th>Vehicle No</th>
                                <th>Items</th>
                                <th>Total Qty</th>
                                <th>Total Value (₹)</th>
                                <th>Status</th>
                                <th style="text-align: center; width: 160px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($challans as $row): ?>
                            <tr>
                                <td><?= date('d M Y', strtotime($row['dc_date'])) ?></td>
                                <td><?= htmlspecialchars($row['receiver_name']) ?></td>
                                <td>
                                    <div class="project-info">
                                        <?php if (!empty($row['project_code'])): ?>
                                            <span class="project-code"><?= htmlspecialchars($row['project_code']) ?></span><br>
                                            <small><?= htmlspecialchars($row['project_name'] ?? '—') ?></small>
                                        <?php else: ?>
                                            <em>Central / General</em>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td><?= htmlspecialchars($row['vehicle_no'] ?: '—') ?></td>
                                <td><strong><?= $row['item_count'] ?></strong></td>
                                <td><?= number_format($row['total_qty'], 2) ?></td>
                                <td class="amount">₹ <?= number_format($row['total_value'], 2) ?></td>
                                <td>
                                    <span class="status-badge status-<?= htmlspecialchars($row['status']) ?>">
                                        <?= htmlspecialchars($row['status']) ?>
                                    </span>
                                </td>
                                <td class="action-btns" style="text-align: center;">
                                    <a href="dc_view.php?id=<?= (int)$row['id'] ?>" title="View Details" class="btn-view">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="dc_print.php?id=<?= (int)$row['id'] ?>" target="_blank" title="Print Challan" class="btn-print">
                                        <i class="fas fa-print"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

    </div>
</div>

</body>
</html>

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