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

// Security check
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'project manager') {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

$project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;
if ($project_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Invalid Project</h2>");
}

// Verify project belongs to this manager
$check = $conn->prepare("
    SELECT 
        project_code, project_name, project_budget
    FROM project_master 
    WHERE id = ? AND project_manager_id = ?
");
$check->bind_param("ii", $project_id, $user_id);
$check->execute();
$project = $check->get_result()->fetch_assoc();

if (!$project) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Project not found or access denied</h2>");
}

// Get actual consumption (sum of all material used in this project)
// Adjust table/column names based on your actual consumption tracking
$consumption_query = "
    SELECT 
        COALESCE(SUM(quantity_used * rate), 0) AS total_used
    FROM material_consumption
    WHERE project_id = ?
";
$cons_stmt = $conn->prepare($consumption_query);
$cons_stmt->bind_param("i", $project_id);
$cons_stmt->execute();
$consumption = $cons_stmt->get_result()->fetch_assoc();
$total_used = $consumption['total_used'] ?? 0;

$total_budget = (float)$project['project_budget'] ?: 0;
$remaining = max(0, $total_budget - $total_used);
$percent_used = $total_budget > 0 ? round(($total_used / $total_budget) * 100, 1) : 0;

// Optional: Item-wise breakdown (top consumed items)
$item_breakdown_query = "
    SELECT 
        i.name AS item_name,
        SUM(mc.quantity_used) AS qty_used,
        SUM(mc.quantity_used * mc.rate) AS value_used
    FROM material_consumption mc
    INNER JOIN inventory_master i ON mc.item_id = i.id
    WHERE mc.project_id = ?
    GROUP BY mc.item_id, i.name
    ORDER BY value_used DESC
    LIMIT 10
";
$item_stmt = $conn->prepare($item_breakdown_query);
$item_stmt->bind_param("i", $project_id);
$item_stmt->execute();
$item_result = $item_stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Budget vs Actual - <?= htmlspecialchars($project['project_name']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #8b5cf6;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --glass: rgba(255,255,255,0.08);
            --border: rgba(255,255,255,0.15);
        }
        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: 1100px; margin: 0 auto; }
        .back {
            color: #c4b5fd;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 25px;
        }
        .back:hover { color: white; }

        h1 { margin: 0 0 8px; font-size: 2.2rem; }
        .project-info { opacity: 0.9; margin-bottom: 30px; font-size: 1.1rem; }

        .summary-card {
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 30px;
            text-align: center;
            margin-bottom: 35px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.4);
        }
        .budget-total {
            font-size: 2.8rem;
            font-weight: 700;
            color: var(--success);
            margin: 10px 0;
        }
        .budget-used {
            font-size: 2rem;
            color: var(--warning);
        }
        .budget-remaining {
            font-size: 2rem;
            color: var(--info);
        }
        .progress-bar {
            height: 30px;
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            margin: 20px 0;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #ef4444, #f59e0b, #22c55e);
            transition: width 0.6s ease;
        }
        .percent-label {
            font-size: 1.4rem;
            font-weight: 600;
            margin-top: 10px;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 30px 0;
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 14px;
            overflow: hidden;
        }
        .items-table th, .items-table td {
            padding: 14px 18px;
            text-align: left;
            border-bottom: 1px solid var(--border);
        }
        .items-table th { background: rgba(255,255,255,0.12); font-weight: 600; }
        .no-data {
            text-align: center;
            padding: 60px;
            opacity: 0.8;
        }
    </style>
</head>
<body>

<div class="container">
    <a href="project_dashboard.php?id=<?= $project_id ?>" class="back">
        <i class="fas fa-arrow-left"></i> Back to Project Dashboard
    </a>

    <h1>Budget vs Actual Consumption</h1>
    <div class="project-info">
        Project: <strong><?= htmlspecialchars($project['project_name']) ?></strong> 
        (<?= htmlspecialchars($project['project_code']) ?>)
    </div>

    <div class="summary-card">
        <div style="font-size: 1.2rem; opacity: 0.9; margin-bottom: 10px;">
            Approved Project Budget
        </div>
        <div class="budget-total">
            ₹ <?= number_format($total_budget, 0) ?>
        </div>

        <div style="margin: 25px 0;">
            <div style="font-size: 1.1rem; opacity: 0.9;">Spent So Far</div>
            <div class="budget-used">
                ₹ <?= number_format($total_used, 0) ?>
            </div>
        </div>

        <div>
            <div style="font-size: 1.1rem; opacity: 0.9;">Remaining Budget</div>
            <div class="budget-remaining">
                ₹ <?= number_format($remaining, 0) ?>
            </div>
        </div>

        <div class="progress-bar">
            <div class="progress-fill" style="width: <?= $percent_used ?>%;"></div>
        </div>

        <div class="percent-label">
            <?= $percent_used ?>% of Budget Used
            <?php if ($percent_used > 90): ?>
                <span style="color:#ef4444; margin-left:10px;">(Overrun Risk High)</span>
            <?php elseif ($percent_used > 75): ?>
                <span style="color:#f59e0b; margin-left:10px;">(Watch Closely)</span>
            <?php endif; ?>
        </div>
    </div>

    <div class="section-title" style="font-size:1.4rem;margin:40px 0 15px;">
        Top 10 Most Consumed Items
    </div>

    <?php if ($item_result->num_rows > 0): ?>
        <table class="items-table">
            <thead>
                <tr>
                    <th>Item Name</th>
                    <th>Quantity Used</th>
                    <th>Value Used (₹)</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($item = $item_result->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($item['item_name']) ?></td>
                    <td><?= number_format($item['qty_used'], 2) ?></td>
                    <td>₹ <?= number_format($item['value_used'], 2) ?></td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    <?php else: ?>
        <div class="no-data">
            <i class="fas fa-chart-bar" style="font-size:4rem;opacity:0.6;"></i><br><br>
            No consumption data recorded yet for this project.
        </div>
    <?php endif; ?>
</div>

</body>
</html>

<?php
$check->close();
$cons_stmt->close();
$item_stmt->close();
$conn->close();
?>