<?php
session_start();
require("php_con.php");
//require("check_user.php");
if(isset($_COOKIE['user_id'])){
$head_user_qury=mysqli_query($connation,"SELECT * FROM user_details WHERE user_id='$_COOKIE[user_id]'");
$head_user_resalt=mysqli_fetch_array($head_user_qury);
}
else{
	echo "<script>window.location='logout';</script>";
	exit();
}
?>

<?php require("header.php"); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <title>Dashboard</title>
</head>
<body>
<?php include 'navbar.php'; ?>
<?php
include 'php_con.php'; // Use your provided database connection file

// Initialize variables for card data
$active_plans = 0;
$upcoming_payments = 0;
$overdue_payments = 0;

// Get total active installment plans
try {
    $query = $connation->query("SELECT COUNT(*) AS total FROM installment_plans WHERE status = 'active'");
    $result = $query->fetch_assoc();
    $active_plans = $result['total'];
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Error fetching active plans: " . $e->getMessage() . "</div>";
}

// Get total upcoming payments for the current month
try {
    $current_month = date('Y-m');
    $query = $connation->query("SELECT COUNT(*) AS upcoming FROM installment_payments WHERE DATE_FORMAT(payment_date, '%Y-%m') = '$current_month'");
    $result = $query->fetch_assoc();
    $upcoming_payments = $result['upcoming'];
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Error fetching upcoming payments: " . $e->getMessage() . "</div>";
}

// Get total overdue payments
try {
    $today = date('Y-m-d');
    $query = $connation->query("SELECT COUNT(*) AS overdue FROM installment_payments WHERE payment_date < '$today'");
    $result = $query->fetch_assoc();
    $overdue_payments = $result['overdue'];
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Error fetching overdue payments: " . $e->getMessage() . "</div>";
}

// Get monthly payment data for the chart
$payments_data = [];
try {
    for ($month = 1; $month <= 12; $month++) {
        $month_string = str_pad($month, 2, '0', STR_PAD_LEFT);
        $year_month = date('Y') . '-' . $month_string;
        $query = $connation->query("SELECT SUM(amount_paid) AS monthly_total FROM installment_payments WHERE DATE_FORMAT(payment_date, '%Y-%m') = '$year_month'");
        $result = $query->fetch_assoc();
        $payments_data[] = $result['monthly_total'] ? $result['monthly_total'] : 0;
    }
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Error fetching payment data: " . $e->getMessage() . "</div>";
}
?>

<div class="container mt-5">
    <h2>Dashboard</h2>
    <div class="row">
        <!-- Card 1: Total Active Plans -->
        <div class="col-md-4">
            <div class="card text-white bg-primary mb-3">
                <div class="card-body">
                    <h5 class="card-title">Active Installment Plans</h5>
                    <p class="card-text">
                        <?php echo $active_plans; ?>
                    </p>
                </div>
            </div>
        </div>

        <!-- Card 2: Total Upcoming Payments -->
        <div class="col-md-4">
            <div class="card text-white bg-success mb-3">
                <div class="card-body">
                    <h5 class="card-title">Upcoming Payments (This Month)</h5>
                    <p class="card-text">
                        <?php echo $upcoming_payments; ?>
                    </p>
                </div>
            </div>
        </div>

        <!-- Card 3: Overdue Payments -->
        <div class="col-md-4">
            <div class="card text-white bg-danger mb-3">
                <div class="card-body">
                    <h5 class="card-title">Overdue Payments</h5>
                    <p class="card-text">
                        <?php echo $overdue_payments; ?>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Chart Section -->
    <div class="row">
        <div class="col-md-12">
            <canvas id="monthlyPaymentsChart" height="100"></canvas>
        </div>
    </div>
</div>

<!-- Bootstrap and Chart.js -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Chart.js Script -->
<script>
    var ctx = document.getElementById('monthlyPaymentsChart').getContext('2d');
    var monthlyPaymentsChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            datasets: [{
                label: 'Monthly Payments',
                data: <?php echo json_encode($payments_data); ?>,
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
    });
</script>
</body>
</html>
