<?php
session_start();
require_once("../config/config.php");

// Only allow admin role
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$full_name = $_SESSION['full_name'] ?? 'Administrator';

// ───────────────────────────────────────────────
// Key Metrics (same as before)
 // ───────────────────────────────────────────────
// Key Metrics (customize queries based on your exact table/column names)

// 1. Total active projects
$total_projects = $conn->query("
    SELECT COUNT(*) AS count 
    FROM project_master 
    WHERE project_status IN ('Active', 'In Progress')
")->fetch_assoc()['count'] ?? 0;

// 2. Pending PRs (all projects)
$pending_prs = $conn->query("
    SELECT COUNT(*) AS count 
    FROM procurement_request 
    WHERE status = 'Pending'
")->fetch_assoc()['count'] ?? 0;

// 3. Issued / Pending POs
$pending_pos = $conn->query("
    SELECT COUNT(*) AS count 
    FROM purchase_order 
    WHERE status IN ('Issued', 'Pending Approval')
")->fetch_assoc()['count'] ?? 0;

// 4. Recent GRNs (last 7 days)
$recent_grns = $conn->query("
    SELECT COUNT(*) AS count 
    FROM goods_received_note 
    WHERE grn_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
")->fetch_assoc()['count'] ?? 0;

// 5. Low stock items (across all projects) - threshold example: < 10 units
$low_stock = $conn->query("
    SELECT COUNT(*) AS count 
    FROM project_inventory 
    WHERE current_stock <= 10 AND current_stock > 0
")->fetch_assoc()['count'] ?? 0;

// 6. Total stock value (all projects)
$total_stock_value = $conn->query("
    SELECT COALESCE(SUM(current_stock * avg_rate), 0) AS value 
    FROM project_inventory
")->fetch_assoc()['value'] ?? 0;
   
// ... (keep your existing metrics queries: total_projects, pending_prs, pending_pos, recent_grns, low_stock, total_stock_value)

// ───────────────────────────────────────────────
// Real Activity Feed (last 10 events)
$activity_query = "
    -- PR Created
    SELECT 
        'PR Created' AS action_type,
        pr.created_at AS timestamp,
        u.full_name AS performed_by,
        CONCAT('PR-', LPAD(pr.id, 5, '0')) AS reference,
        CONCAT('for Project ', COALESCE(p.project_code, 'Central')) AS description
    FROM procurement_request pr
    LEFT JOIN users u ON pr.requested_by = u.id
    LEFT JOIN project_master p ON pr.project_id = p.id

    UNION ALL

    -- PR Approved/Rejected
    SELECT 
        CONCAT('PR ', pr.status) AS action_type,
        pr.approved_at AS timestamp,
        ua.full_name AS performed_by,
        CONCAT('PR-', LPAD(pr.id, 5, '0')) AS reference,
        CONCAT('by ', ua.full_name) AS description
    FROM procurement_request pr
    LEFT JOIN users ua ON pr.approved_by = ua.id
    WHERE pr.approved_at IS NOT NULL

    UNION ALL

    -- PO Issued
    SELECT 
        'PO Issued' AS action_type,
        po.created_at AS timestamp,
        u.full_name AS performed_by,
        CONCAT('PO-', LPAD(po.id, 5, '0')) AS reference,
        CONCAT('from PR-', LPAD(COALESCE(po.pr_id, 0), 5, '0')) AS description
    FROM purchase_order po
    LEFT JOIN users u ON po.created_by = u.id

    UNION ALL

    -- GRN Received
    SELECT 
        'GRN Received' AS action_type,
        grn.grn_date AS timestamp,
        u.full_name AS performed_by,
        CONCAT('GRN-', LPAD(grn.id, 5, '0')) AS reference,
        CONCAT('against PO-', LPAD(COALESCE(grn.po_id, 0), 5, '0')) AS description
    FROM goods_received_note grn
    LEFT JOIN users u ON grn.received_by = u.id

    ORDER BY timestamp DESC
    LIMIT 10
";

$activity_result = $conn->query($activity_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #8b5cf6;
            --primary-dark: #7c3aed;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --info: #60a5fa;
            --glass: rgba(255,255,255,0.08);
            --border: rgba(255,255,255,0.15);
            --dark-glass: rgba(30,30,50,0.7);
        }
        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: linear-gradient(rgba(0,0,0,0.8), rgba(0,0,0,0.95)),
                        url('../background.jpeg') center/cover fixed;
            color: white;
            margin: 0;
            padding: 20px 15px;
        }
        .container { max-width: 1400px; margin: 0 auto; }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }
        h1 { margin: 0; font-size: 2.4rem; }

        .welcome {
            opacity: 0.9;
            font-size: 1.1rem;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        .stat-card {
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 24px;
            text-align: center;
            transition: all 0.25s;
        }
        .stat-card:hover {
            transform: translateY(-6px);
            box-shadow: 0 15px 35px rgba(0,0,0,0.4);
        }
        .stat-icon { font-size: 2.5rem; margin-bottom: 12px; }
        .stat-value { font-size: 2.1rem; font-weight: 700; margin: 8px 0; }
        .stat-label { font-size: 0.9rem; opacity: 0.85; }

        .quick-links {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin: 50px 0;
        }
        .link-card {
            background: var(--dark-glass);
            border: 1px solid var(--border);
            border-radius: 14px;
            padding: 28px 20px;
            text-align: center;
            text-decoration: none;
            color: white;
            transition: all 0.3s;
        }
        .link-card:hover {
            background: rgba(139,92,246,0.18);
            transform: translateY(-5px);
            border-color: var(--primary);
        }
        .link-icon { font-size: 3rem; margin-bottom: 16px; color: var(--primary); }
        .link-title { font-size: 1.25rem; font-weight: 600; }

        .activity-feed {
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 14px;
            padding: 24px;
            margin-top: 40px;
        }
        .feed-item {
            padding: 12px 0;
            border-bottom: 1px solid var(--border);
        }
        .feed-item:last-child { border-bottom: none; }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>
<div class="container">
      <header>
        <div>
            <h1>Admin Dashboard</h1>
            <div class="welcome">Welcome back, <?= htmlspecialchars($full_name) ?></div>
        </div>
    </header>

    <!-- Key Metrics -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="color: var(--info);"><i class="fas fa-hard-hat"></i></div>
            <div class="stat-value"><?= $total_projects ?></div>
            <div class="stat-label">Active Projects</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: var(--warning);"><i class="fas fa-file-import"></i></div>
            <div class="stat-value"><?= $pending_prs ?></div>
            <div class="stat-label">Pending PRs</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: var(--primary);"><i class="fas fa-file-invoice"></i></div>
            <div class="stat-value"><?= $pending_pos ?></div>
            <div class="stat-label">Issued / Pending POs</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: var(--success);"><i class="fas fa-truck-loading"></i></div>
            <div class="stat-value"><?= $recent_grns ?></div>
            <div class="stat-label">GRNs (Last 7 Days)</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: var(--danger);"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="stat-value"><?= $low_stock ?></div>
            <div class="stat-label">Low Stock Items</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: #60a5fa;"><i class="fas fa-warehouse"></i></div>
            <div class="stat-value">₹ <?= number_format($total_stock_value, 0) ?></div>
            <div class="stat-label">Total Stock Value</div>
        </div>
    </div>

    <!-- Quick Management Links -->
    <h2 style="margin: 50px 0 25px; text-align:center; font-size: 1.8rem;">Quick Menus</h2>
    <div class="quick-links">
        <a href="../project/project-management.php" class="link-card">
            <div class="link-icon"><i class="fas fa-hard-hat"></i></div>
            <div class="link-title">Manage Projects</div>
        </a>
        <a href="../warehouse/warehouse-management.php" class="link-card">
            <div class="link-icon"><i class="fas fa-warehouse"></i></div>
            <div class="link-title">Manage Warehouses</div>
        </a>            
        <a href="../user-management/users-list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-users-cog"></i></div>
            <div class="link-title">User Management</div>
        </a>
        <a href="../planning/planning_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-chart-line"></i></div>
            <div class="link-title">Project Planning</div>
        </a>

        <a href="../pr/pr_approval_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-file-import"></i></div>
            <div class="link-title">Pending PR Approvals</div>
        </a>

        <a href="../po/po_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-file-invoice"></i></div>
            <div class="link-title">Purchase Orders</div>
        </a>
        <a href="../po_from_client/po_from_client_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-file-invoice"></i></div>
            <div class="link-title">Purchase Orders From Client</div>
        </a>
        <!-- <a href="../grn/grn_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-truck-loading"></i></div>
            <div class="link-title">Goods Received Notes</div>
        </a> -->
        <a href="../grn_warehouse/grn_warehouse_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-truck-loading"></i></div>
            <div class="link-title">Goods Received Notes From Warehouse</div>
        </a>
        <a href="../vendor/vendor-management.php" class="link-card">
            <div class="link-icon"><i class="fas fa-user-tie"></i></div>
            <div class="link-title">Manage Vendors</div>
        </a>
        <a href="../inventory/inventory_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-warehouse"></i></div>
            <div class="link-title">Inventory Overview</div>
        </a>
         <a href="../purchase/purchase_management.php" class="link-card">
            <div class="link-icon"><i class="fas fa-warehouse"></i></div>
            <div class="link-title">Purchase</div>
        </a>
        <a href="../delivery_challan/dc_list.php" class="link-card">
            <div class="link-icon"><i class="fas fa-shipping-fast"></i></div>
            <div class="link-title">Delivery Challans</div>
        </a>
        <a href="../bbu/billing_dashboard.php" class="link-card">
            <div class="link-icon"><i class="fas fa-file-invoice"></i></div>
            <div class="link-title">Billing</div>
        </a>
    </div>

    <!-- Real Activity Feed -->
    <div class="activity-feed">
        <h3 style="margin: 0 0 20px; font-size: 1.4rem;">Recent System Activity</h3>

        <?php if ($activity_result->num_rows > 0): ?>
            <?php while ($act = $activity_result->fetch_assoc()): ?>
                <div class="feed-item" style="display: flex; align-items: center; gap: 15px; padding: 12px 0; border-bottom: 1px solid var(--border);">
                    <div style="font-size: 1.8rem; opacity: 0.8; min-width: 40px; text-align: center;">
                        <?php
                        switch ($act['action_type']) {
                            case 'PR Created': echo '<i class="fas fa-file-import" style="color:var(--primary);"></i>'; break;
                            case 'PR Approved': echo '<i class="fas fa-check-circle" style="color:var(--success);"></i>'; break;
                            case 'PR Rejected': echo '<i class="fas fa-times-circle" style="color:var(--danger);"></i>'; break;
                            case 'PO Issued': echo '<i class="fas fa-file-invoice" style="color:var(--warning);"></i>'; break;
                            case 'GRN Received': echo '<i class="fas fa-truck-loading" style="color:var(--info);"></i>'; break;
                            default: echo '<i class="fas fa-info-circle"></i>';
                        }
                        ?>
                    </div>
                    <div style="flex: 1;">
                        <strong><?= htmlspecialchars($act['action_type']) ?></strong><br>
                        <small style="opacity: 0.8;">
                            <?= htmlspecialchars($act['performed_by']) ?> • 
                            <?= date('d M Y h:i A', strtotime($act['timestamp'])) ?>
                        </small>
                    </div>
                    <div style="text-align: right; min-width: 160px;">
                        <strong><?= htmlspecialchars($act['reference']) ?></strong><br>
                        <small style="opacity: 0.7;"><?= htmlspecialchars($act['description']) ?></small>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div style="text-align:center; padding: 40px; opacity: 0.8;">
                <i class="fas fa-history" style="font-size: 3rem; margin-bottom: 15px;"></i><br>
                No recent activity recorded yet.
            </div>
        <?php endif; ?>
    </div>
</div>

</body>
</html>