<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Set a title for the page, which will be used in header.php
$page_title = "ড্যাশবোর্ড";

// This is the most important line for security. It ensures only logged-in admins can see this page.
// It also contains our database connection ($conn) and the log_activity() function.
require_once 'includes/auth_check.php';

// Include the header and sidebar layout.
include 'includes/header.php';

// --- Fetch stats for the dashboard summary cards (Safe Code) ---

// Initialize variables with default values
$total_users = 0;
$pending_requests = 0;
$total_balance = 0;
$today_sales = 0;

// Check if the database connection object is valid before running queries
if ($conn) {
    // Total users with the 'user' role
    $total_users_res = $conn->query("SELECT COUNT(id) AS count FROM users WHERE role='user'");
    if ($total_users_res) $total_users = $total_users_res->fetch_assoc()['count'];

    // Pending balance requests
    $pending_requests_res = $conn->query("SELECT COUNT(id) AS count FROM add_balance_requests WHERE status='Pending'");
    if ($pending_requests_res) $pending_requests = $pending_requests_res->fetch_assoc()['count'];

    // Total balance of all users in the system
    $total_balance_res = $conn->query("SELECT SUM(balance) AS total FROM users");
    if ($total_balance_res) $total_balance = $total_balance_res->fetch_assoc()['total'];

    // Total successful transactions today
    $today_date = date('Y-m-d');
    $stmt = $conn->prepare("SELECT SUM(amount) AS total FROM transactions WHERE DATE(created_at) = ? AND type IN ('Recharge', 'Package Purchase', 'Bill Payment')");
    $stmt->bind_param("s", $today_date);
    $stmt->execute();
    $today_sales_res = $stmt->get_result();
    if ($today_sales_res) $today_sales = $today_sales_res->fetch_assoc()['total'];
    $stmt->close();
}
?>

<div class="container-fluid">
    <h2 class="mb-4">ড্যাশবোর্ড</h2>
    
    <div class="row">
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="stat-card bg-primary p-3 rounded text-white shadow-sm">
                <h4>মোট ইউজার</h4>
                <h2><i class="fas fa-users me-2"></i><?php echo $total_users; ?></h2>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="stat-card bg-warning p-3 rounded text-white shadow-sm">
                <h4>পেন্ডিং রিকুয়েস্ট</h4>
                <h2><i class="fas fa-hourglass-half me-2"></i><?php echo $pending_requests; ?></h2>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="stat-card bg-success p-3 rounded text-white shadow-sm">
                <h4>আজকের সেলস</h4>
                <h2><i class="fas fa-wallet me-2"></i>৳<?php echo number_format($today_sales ?? 0, 2); ?></h2>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="stat-card bg-info p-3 rounded text-white shadow-sm">
                <h4>সিস্টেম ব্যালেন্স</h4>
                <h2><i class="fas fa-university me-2"></i>৳<?php echo number_format($total_balance ?? 0, 2); ?></h2>
            </div>
        </div>
    </div>

    <div class="row mt-4">
        <div class="col-lg-6 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title">দৈনিক ব্যবহারকারী নিবন্ধন (গত ৭ দিন)</h5>
                    <canvas id="userRegistrationChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-6 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title">দৈনিক লেনদেন (গত ৭ দিন)</h5>
                    <canvas id="dailyTransactionChart"></canvas>
                </div>
            </div>
        </div>
    </div>

</div>

<?php
// Include the footer layout.
include 'includes/footer.php';
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // Fetch data from our API endpoint
    fetch('api/dashboard_data.php')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Chart 1: User Registrations (Bar Chart)
            const regCtx = document.getElementById('userRegistrationChart').getContext('2d');
            new Chart(regCtx, {
                type: 'bar',
                data: {
                    labels: data.registrations.labels,
                    datasets: [{
                        label: 'নতুন ইউজার',
                        data: data.registrations.data,
                        backgroundColor: 'rgba(54, 162, 235, 0.6)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: { 
                    scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } },
                    responsive: true,
                    plugins: { legend: { display: false } }
                }
            });

            // Chart 2: Daily Transactions (Line Chart)
            const txnCtx = document.getElementById('dailyTransactionChart').getContext('2d');
            new Chart(txnCtx, {
                type: 'line',
                data: {
                    labels: data.transactions.labels,
                    datasets: [{
                        label: 'লেনদেন',
                        data: data.transactions.data,
                        fill: true,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.2
                    }]
                },
                options: { 
                    scales: { y: { beginAtZero: true } },
                    responsive: true,
                    plugins: { legend: { display: false } }
                }
            });
        })
        .catch(error => console.error('Error fetching dashboard data:', error));
});
</script>

<?php
// Close the database connection.
$conn->close();
?>