<?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 filters (you can expand this later)
$project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;
$from_date  = $_GET['from_date'] ?? '';
$to_date    = $_GET['to_date'] ?? '';

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

if ($project_id > 0) {
    $where .= " AND pe.project_id = ?";
    $params[] = $project_id;
    $types .= "i";
}
if ($from_date) {
    $where .= " AND DATE(pe.created_at) >= ?";
    $params[] = $from_date;
    $types .= "s";
}
if ($to_date) {
    $where .= " AND DATE(pe.created_at) <= ?";
    $params[] = $to_date;
    $types .= "s";
}

// Main Query
$query = "
    SELECT 
        pe.id,
        pe.invoice_id,
        pe.created_at,
        pe.total_basic,
        pe.total_discount,
        pe.total_gst,
        pe.grand_total,
        p.project_name,
        p.project_code,
        w.warehouse_name,
        COUNT(pei.id) AS item_count
    FROM purchase_entries pe
    LEFT JOIN project_master p ON pe.project_id = p.id
    LEFT JOIN warehouse_master w ON pe.warehouse_id = w.id
    LEFT JOIN purchase_entry_items pei ON pe.id = pei.purchase_entry_id
    $where
    GROUP BY pe.id
    ORDER BY pe.created_at DESC
    LIMIT 100
";

$stmt = $conn->prepare($query);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$purchases = $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 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;
            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);
        }

        .table-section {
            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);
        }

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

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

        .amount {
            font-weight: 600;
        }

        .grand-total {
            color: #a5b4fc;
            font-size: 1.05rem;
        }

        .action-btns a {
            color: var(--primary);
            text-decoration: none;
            margin-right: 16px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .action-btns a:hover {
            color: #ddd6fe;
        }

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

        .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) {
            .table-section {
                padding: 25px;
            }
            th, td {
                padding: 16px 12px;
                font-size: 0.95rem;
            }
        }

        /* Make table scrollable on mobile */
        @media (max-width: 640px) {
            .table-container {
                overflow-x: auto;
            }
            table {
                min-width: 900px;
            }
        }
    </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="purchase_management.php" class="back-link">
                    ← Back to Purchase Management
                </a>
                <h1><i class="fas fa-receipt"></i> Purchase Entries</h1>
            </div>
            
            <a href="add_purchase.php" class="add-btn">
                <i class="fas fa-plus"></i> New Purchase Entry
            </a>
        </div>

        <!-- Table Section -->
        <div class="table-section">
            <?php if (empty($purchases)): ?>
                <div class="no-records">
                    <i class="fas fa-receipt"></i>
                    <h2>No Purchase Entries Found</h2>
                    <p>Start by creating your first purchase entry.</p>
                    <a href="add-purchase.php" class="add-btn" style="margin-top: 25px; display: inline-flex;">
                        <i class="fas fa-plus"></i> Create New Purchase
                    </a>
                </div>
            <?php else: ?>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Invoice No</th>
                                <th>Project</th>
                                <th>Warehouse</th>
                                <th>Items</th>
                                <th>Basic Amount</th>
                                <th>Discount</th>
                                <th>Grand Total</th>
                                <th style="text-align: center; width: 120px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($purchases as $row): ?>
                            <tr>
                                <td><?= date('d M Y', strtotime($row['created_at'])) ?></td>
                                <td><strong><?= htmlspecialchars($row['invoice_id'] ?: '—') ?></strong></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>—</em>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td><?= htmlspecialchars($row['warehouse_name'] ?: '—') ?></td>
                                <td><strong><?= $row['item_count'] ?></strong></td>
                                <td class="amount">₹ <?= number_format($row['total_basic'], 2) ?></td>
                                <td class="amount">₹ <?= number_format($row['total_discount'] ?? 0, 2) ?></td>
                                <td class="grand-total"><strong>₹ <?= number_format($row['grand_total'], 2) ?></strong></td>
                                <td class="action-btns" style="text-align: center;">
                                    <a href="purchase_view.php?id=<?= (int)$row['id'] ?>" title="View Details">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

    </div>
</div>

</body>
</html>

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