<?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;'>No project selected</h2>");
}

// Verify project belongs to this manager
$check = $conn->prepare("
   SELECT project_code, project_name 
    FROM project_master
    LEFT JOIN project_managers ON project_master.id = project_managers.project_id 
    WHERE  project_managers.project_id = ? AND   project_managers.user_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>");
}

// ───────────────────────────────────────────────
// Analytics Data

$current_year = date('Y');
$current_month = date('Y-m');

// 1. DPR count per month (last 12 months)
$monthly_dpr = $conn->query("
    SELECT DATE_FORMAT(report_date, '%Y-%m') AS month, COUNT(*) AS count
    FROM daily_progress_report
    WHERE project_id = $project_id
    AND report_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
    GROUP BY month
    ORDER BY month ASC
")->fetch_all(MYSQLI_ASSOC);

$months = [];
$counts = [];
foreach ($monthly_dpr as $row) {
    $months[] = date('M Y', strtotime($row['month'] . '-01'));
    $counts[] = (int)$row['count'];
}
$monthly_data_json = json_encode(['months' => $months, 'counts' => $counts]);

// 2. Status breakdown (all time)
$status_breakdown = $conn->query("
    SELECT status, COUNT(*) AS count
    FROM daily_progress_report
    WHERE project_id = $project_id
    GROUP BY status
")->fetch_all(MYSQLI_ASSOC);

$status_labels = [];
$status_values = [];
$status_colors = [];
foreach ($status_breakdown as $row) {
    $status_labels[] = $row['status'];
    $status_values[] = (int)$row['count'];
    switch ($row['status']) {
        case 'Submitted': case 'Approved': $status_colors[] = '#22c55e'; break;
        case 'Pending': $status_colors[] = '#f59e0b'; break;
        case 'Rejected': $status_colors[] = '#ef4444'; break;
        default: $status_colors[] = '#6b7280';
    }
}
$status_json = json_encode([
    'labels' => $status_labels,
    'values' => $status_values,
    'colors' => $status_colors
]);

// 3. Average manpower
$avg_manpower = $conn->query("
    SELECT AVG(manpower_count) AS avg
    FROM daily_progress_report
    WHERE project_id = $project_id AND manpower_count > 0
")->fetch_assoc()['avg'] ?? 0;
$avg_manpower = round($avg_manpower, 1);

// 4. Submission rate this month
$days_in_month = date('t');
$working_days_approx = ceil($days_in_month * 0.75); // rough estimate (exclude Sundays/holidays)
$dpr_this_month = $conn->query("
    SELECT COUNT(DISTINCT report_date) AS submitted_days
    FROM daily_progress_report
    WHERE project_id = $project_id
    AND report_date >= '$current_month-01'
    AND status IN ('Submitted', 'Approved')
")->fetch_assoc()['submitted_days'] ?? 0;
$submission_rate = $working_days_approx > 0 ? round(($dpr_this_month / $working_days_approx) * 100, 1) : 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DPR Analytics - <?= htmlspecialchars($project['project_name']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <!-- Chart.js CDN -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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: 1200px; 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; }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 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.6rem; margin-bottom: 12px; }
        .stat-value { font-size: 2.5rem; font-weight: 700; margin: 8px 0; }
        .stat-label { font-size: 1.05rem; opacity: 0.85; }

        .chart-card {
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 24px;
            margin: 30px 0;
        }
        .chart-title { font-size: 1.4rem; margin-bottom: 20px; text-align: center; }

        .progress-bar {
            height: 30px;
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            overflow: hidden;
            margin: 15px 0;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #ef4444, #f59e0b, #22c55e);
            transition: width 1s ease;
        }
    </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>DPR Analytics</h1>
    <div class="project-info">
        Project: <strong><?= htmlspecialchars($project['project_name']) ?></strong> 
        (<?= htmlspecialchars($project['project_code']) ?>)
    </div>

    <!-- Quick Stats -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="color: var(--info);"><i class="fas fa-calendar-check"></i></div>
            <div class="stat-value"><?= $submission_rate ?>%</div>
            <div class="stat-label">Submission Rate This Month</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: var(--success);"><i class="fas fa-check-circle"></i></div>
            <div class="stat-value"><?= $total_this_month ?></div>
            <div class="stat-label">DPRs Submitted This Month</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: var(--warning);"><i class="fas fa-clock"></i></div>
            <div class="stat-value"><?= $pending_dpr ?></div>
            <div class="stat-label">Pending DPRs</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="color: #60a5fa;"><i class="fas fa-users"></i></div>
            <div class="stat-value"><?= number_format($avg_manpower, 1) ?></div>
            <div class="stat-label">Avg. Manpower per Day</div>
        </div>
    </div>

    <!-- Submission Rate Progress -->
    <div class="chart-card">
        <div class="chart-title">Monthly DPR Submission Rate</div>
        <div class="progress-bar">
            <div class="progress-fill" style="width: <?= $submission_rate ?>%;"></div>
        </div>
        <div style="text-align:center; margin-top:10px;">
            <?= $submission_rate ?>% of expected working days reported this month
        </div>
    </div>

    <!-- Monthly DPR Trend Chart -->
    <div class="chart-card">
        <div class="chart-title">DPR Submission Trend (Last 12 Months)</div>
        <canvas id="dprTrendChart" height="100"></canvas>
    </div>

    <!-- Status Breakdown Chart -->
    <div class="chart-card">
        <div class="chart-title">DPR Status Breakdown</div>
        <canvas id="statusChart" height="180"></canvas>
    </div>
</div>

<!-- Chart.js Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Monthly Trend Chart (Bar)
const trendCtx = document.getElementById('dprTrendChart').getContext('2d');
new Chart(trendCtx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($months) ?>,
        datasets: [{
            label: 'DPRs Submitted',
            data: <?= json_encode($counts) ?>,
            backgroundColor: 'rgba(139, 92, 246, 0.7)',
            borderColor: '#8b5cf6',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: { beginAtZero: true, ticks: { color: '#ddd' } },
            x: { ticks: { color: '#ddd' } }
        },
        plugins: { legend: { labels: { color: '#ddd' } } }
    }
});

// Status Pie Chart
const statusCtx = document.getElementById('statusChart').getContext('2d');
new Chart(statusCtx, {
    type: 'pie',
    data: {
        labels: <?= json_encode($status_labels) ?>,
        datasets: [{
            data: <?= json_encode($status_values) ?>,
            backgroundColor: <?= json_encode($status_colors) ?>,
            borderWidth: 1
        }]
    },
    options: {
        plugins: {
            legend: { position: 'bottom', labels: { color: '#ddd' } }
        }
    }
});
</script>

</body>
</html>

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