<?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';

// Get summary statistics
$stats = [];

// Total Purchases Today
$result = $conn->query("SELECT COUNT(*) as count, COALESCE(SUM(grand_total), 0) as total 
                       FROM purchase_entries WHERE DATE(created_at) = CURDATE()");
$today = $result->fetch_assoc();
$stats['today_count'] = $today['count'];
$stats['today_total'] = $today['total'] ?? 0;

// Total Purchases This Month
$result = $conn->query("SELECT COUNT(*) as count, COALESCE(SUM(grand_total), 0) as total 
                       FROM purchase_entries WHERE MONTH(created_at) = MONTH(CURDATE()) 
                       AND YEAR(created_at) = YEAR(CURDATE())");
$month = $result->fetch_assoc();
$stats['month_count'] = $month['count'];
$stats['month_total'] = $month['total'] ?? 0;

// Total Materials in Inventory
$total_materials = $conn->query("SELECT COUNT(*) FROM inventory_master")->fetch_row()[0];

// Recent Purchases
$recent = $conn->query("SELECT pe.id, pe.invoice_id, pe.created_at, pe.grand_total, 
                              p.project_name, w.warehouse_name
                       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
                       ORDER BY pe.created_at DESC LIMIT 8")->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 Management</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;
            --text-light: #cbd5e1;
        }

        * {
            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: 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: 55px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .header h1 {
            font-size: clamp(28px, 5.5vw, 42px);
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-info {
            text-align: right;
            font-size: 1.05rem;
            opacity: 0.9;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 22px;
            padding: 40px;
        }

        .stat-card {
            background: rgba(255,255,255,0.07);
            border: 1px solid var(--glass-border);
            border-radius: 22px;
            padding: 32px 28px;
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-6px);
        }

        .stat-card h3 {
            font-size: 1.05rem;
            opacity: 0.85;
            margin-bottom: 12px;
            font-weight: 500;
        }

        .stat-value {
            font-size: 2.6rem;
            font-weight: 700;
            color: #ddd6fe;
            margin-bottom: 6px;
        }

        .stat-sub {
            color: #a5b4fc;
            font-size: 1.05rem;
        }

        .quick-links {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 20px;
            padding: 0 40px 40px;
        }

        .link-card {
            background: rgba(255,255,255,0.07);
            border: 1px solid var(--glass-border);
            border-radius: 22px;
            padding: 32px 28px;
            text-align: center;
            text-decoration: none;
            color: var(--text);
            transition: all 0.4s ease;
        }

        .link-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 20px 45px rgba(168,85,247,0.35);
            border-color: var(--primary);
        }

        .link-card i {
            font-size: 3.2rem;
            margin-bottom: 18px;
            color: #c4b5fd;
        }

        .recent-section {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 22px;
            margin: 0 40px 50px;
            padding: 35px;
            border: 1px solid var(--glass-border);
        }

        .recent-section h2 {
            margin-bottom: 25px;
            font-size: 1.6rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }

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

        th {
            background: rgba(168,85,247,0.25);
            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);
        }

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

        .action-btn {
            padding: 10px 20px;
            border-radius: 12px;
            text-decoration: none;
            font-weight: 600;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            transition: all 0.3s ease;
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(168,85,247,0.4);
        }

        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 4.5rem;
            opacity: 0.3;
            margin-bottom: 20px;
        }

        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            .user-info {
                text-align: center;
            }
            .stats-grid, .quick-links {
                padding-left: 25px;
                padding-right: 25px;
            }
            .recent-section {
                margin: 0 25px 40px;
                padding: 25px;
            }
        }

        @media (max-width: 480px) {
            .stat-card {
                padding: 25px 20px;
            }
            .stat-value {
                font-size: 2.2rem;
            }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>
<div class="container">
    <div class="glass-container">

        <!-- Header -->
        <div class="header">
            <h1><i class="fas fa-shopping-cart"></i> Purchase Management</h1>
            <div class="user-info">
                <?= htmlspecialchars($full_name) ?> • <?= ucfirst($user_role) ?>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <h3>Today's Purchases</h3>
                <div class="stat-value"><?= number_format($stats['today_count']) ?></div>
                <div class="stat-sub">₹ <?= number_format($stats['today_total'], 2) ?></div>
            </div>

            <div class="stat-card">
                <h3>This Month</h3>
                <div class="stat-value"><?= number_format($stats['month_count']) ?></div>
                <div class="stat-sub">₹ <?= number_format($stats['month_total'], 2) ?></div>
            </div>

            <div class="stat-card">
                <h3>Total Materials</h3>
                <div class="stat-value"><?= number_format($total_materials) ?></div>
                <div class="stat-sub" style="color:#86efac;">In Stock</div>
            </div>
        </div>

        <!-- Quick Links -->
        <div class="quick-links">
            <a href="add-purchase.php" class="link-card">
                <i class="fas fa-plus"></i>
                <h3>New Purchase Entry</h3>
                <p style="opacity:0.8; margin-top:10px;">Create new purchase & update inventory</p>
            </a>

            <a href="purchase_list.php" class="link-card">
                <i class="fas fa-list"></i>
                <h3>All Purchases</h3>
                <p style="opacity:0.8; margin-top:10px;">View complete purchase history</p>
            </a>

            <a href="../inventory/inventory_list.php" class="link-card">
                <i class="fas fa-boxes"></i>
                <h3>Inventory Overview</h3>
                <p style="opacity:0.8; margin-top:10px;">Check current stock levels</p>
            </a>
        </div>

        <!-- Recent Purchases -->
        <div class="recent-section">
            <h2><i class="fas fa-clock"></i> Recent Purchases</h2>

            <?php if (!empty($recent)): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Invoice ID</th>
                            <th>Project</th>
                            <th>Warehouse</th>
                            <th>Amount</th>
                            <th style="text-align: center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recent as $row): ?>
                        <tr>
                            <td><?= date('d M Y', strtotime($row['created_at'])) ?></td>
                            <td><strong><?= htmlspecialchars($row['invoice_id'] ?: '—') ?></strong></td>
                            <td><?= htmlspecialchars($row['project_name'] ?: '—') ?></td>
                            <td><?= htmlspecialchars($row['warehouse_name'] ?: '—') ?></td>
                            <td class="amount">₹ <?= number_format($row['grand_total'], 2) ?></td>
                            <td style="text-align: center;">
                                <a href="purchase_view.php?id=<?= (int)$row['id'] ?>" 
                                   class="action-btn">View Details</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-shopping-cart"></i>
                    <h3>No Purchases Yet</h3>
                    <p>Start by creating your first purchase entry.</p>
                </div>
            <?php endif; ?>
        </div>

    </div>
</div>

</body>
</html>

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