<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('dashboard.view');

require_once __DIR__ . '/../config/database.php';

/* =====================================================
   GLOBAL KPI CALCULATIONS
===================================================== */

// Total Projects
$totalProjects = $pdo->query("
    SELECT COUNT(*) FROM projects
")->fetchColumn();

// Active Projects
$activeProjects = $pdo->query("
    SELECT COUNT(*) FROM projects
    WHERE status = 'ACTIVE'
")->fetchColumn();

// Financial Summary
$financial = $pdo->query("
    SELECT 
        IFNULL(SUM(quantity * unit_cost),0) AS total_cost,
        IFNULL(SUM(quantity * unit_price),0) AS total_revenue
    FROM project_tasks
")->fetch(PDO::FETCH_ASSOC);

$totalCost     = $financial['total_cost'] ?? 0;
$totalRevenue  = $financial['total_revenue'] ?? 0;
$totalProfit   = $totalRevenue - $totalCost;

/* =====================================================
   TASK STATUS SUMMARY (KANBAN STYLE)
===================================================== */

$taskSummary = $pdo->query("
    SELECT status, COUNT(*) as total
    FROM project_tasks
    GROUP BY status
")->fetchAll(PDO::FETCH_KEY_PAIR);

/* =====================================================
   PROJECT ENTERPRISE SUMMARY
===================================================== */

$projects = $pdo->query("
    SELECT 
        p.id,
        p.project_name,
        IFNULL(p.client_name,'—') AS client_name,
        IFNULL(p.budget,0) AS budget,
        p.status,
        IFNULL(SUM(t.quantity * t.unit_cost),0) AS cost,
        IFNULL(SUM(t.quantity * t.unit_price),0) AS revenue,
        (IFNULL(p.budget,0) - IFNULL(SUM(t.quantity * t.unit_cost),0)) AS variance,
        IFNULL(AVG(
            CASE 
                WHEN t.status = 'COMPLETED' THEN 100
                WHEN t.status = 'IN_PROGRESS' THEN 50
                ELSE 0
            END
        ),0) AS progress
    FROM projects p
    LEFT JOIN project_tasks t ON t.project_id = p.id
    GROUP BY p.id
    ORDER BY p.created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>Executive Dashboard</h2>
        <p class="page-subtitle">Enterprise Performance Overview</p>
    </div>

    <!-- ================= KPI GRID ================= -->
    <div class="dashboard-grid">

        <div class="stat-card">
            <h4>Total Projects</h4>
            <div class="number"><?= $totalProjects ?></div>
        </div>

        <div class="stat-card blue">
            <h4>Active Projects</h4>
            <div class="number"><?= $activeProjects ?></div>
        </div>

        <div class="stat-card red">
            <h4>Total Cost</h4>
            <div class="number">R <?= number_format($totalCost,2) ?></div>
        </div>

        <div class="stat-card green">
            <h4>Total Revenue</h4>
            <div class="number">R <?= number_format($totalRevenue,2) ?></div>
        </div>

        <div class="stat-card">
            <h4>Gross Profit</h4>
            <div class="number">R <?= number_format($totalProfit,2) ?></div>
        </div>

    </div>

    <br><br>

    <!-- ================= TASK STATUS BOARD ================= -->
    <div class="dashboard-grid">

        <div class="stat-card">
            <h4>Pending Tasks</h4>
            <div class="number">
                <?= $taskSummary['PENDING'] ?? 0 ?>
            </div>
        </div>

        <div class="stat-card blue">
            <h4>In Progress</h4>
            <div class="number">
                <?= $taskSummary['IN_PROGRESS'] ?? 0 ?>
            </div>
        </div>

        <div class="stat-card green">
            <h4>Completed</h4>
            <div class="number">
                <?= $taskSummary['COMPLETED'] ?? 0 ?>
            </div>
        </div>

    </div>

    <br><br>

    <!-- ================= PROJECT TABLE ================= -->
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Project</th>
                    <th>Client</th>
                    <th>Budget</th>
                    <th>Cost</th>
                    <th>Revenue</th>
                    <th>Profit</th>
                    <th>Variance</th>
                    <th>Progress</th>
                    <th>Status</th>
                    <th>Health</th>
                </tr>
            </thead>
            <tbody>

            <?php if (empty($projects)): ?>
                <tr>
                    <td colspan="10" style="text-align:center;">
                        No projects available yet.
                    </td>
                </tr>
            <?php else: ?>

                <?php foreach ($projects as $p): 
                    $profit   = $p['revenue'] - $p['cost'];
                    $variance = $p['variance'];

                    // Project Health Logic
                    if ($variance < 0) {
                        $health = 'Over Budget';
                        $healthColor = 'red';
                    } elseif ($p['progress'] < 50 && $p['status'] == 'ACTIVE') {
                        $health = 'Slow Progress';
                        $healthColor = 'orange';
                    } else {
                        $health = 'Healthy';
                        $healthColor = 'green';
                    }
                ?>
                    <tr>
                        <td><?= htmlspecialchars($p['project_name']) ?></td>
                        <td><?= htmlspecialchars($p['client_name']) ?></td>
                        <td>R <?= number_format($p['budget'],2) ?></td>
                        <td>R <?= number_format($p['cost'],2) ?></td>
                        <td>R <?= number_format($p['revenue'],2) ?></td>
                        <td>R <?= number_format($profit,2) ?></td>

                        <td style="color: <?= $variance < 0 ? 'red' : 'green' ?>; font-weight:bold;">
                            R <?= number_format($variance,2) ?>
                        </td>

                        <td><?= round($p['progress']) ?>%</td>
                        <td><?= htmlspecialchars($p['status']) ?></td>

                        <td style="color: <?= $healthColor ?>; font-weight:bold;">
                            <?= $health ?>
                        </td>
                    </tr>
                <?php endforeach; ?>

            <?php endif; ?>

            </tbody>
        </table>
    </div>

</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>