<?php
// Start session to access session variables
session_start();

// Security Check: This is crucial. It ensures that only a logged-in admin
// can access this data. Without this, anyone could see your site's statistics.
if (!isset($_SESSION['admin_id'])) {
    // If not an admin, send an "Unauthorized" HTTP status code and stop execution.
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized Access']);
    exit;
}

// Include the database connection file. The path is '../../' because this file is two folders deep.
require_once '../../includes/db_connect.php';

// --- Prepare data arrays for the last 7 days to handle days with zero activity ---
$dates = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $dates[$date] = 0; // Initialize with 0
}


// --- 1. Fetch data for User Registrations over the last 7 days ---
$registrations_sql = "SELECT DATE(created_at) as date, COUNT(id) as count 
                      FROM users 
                      WHERE created_at >= CURDATE() - INTERVAL 6 DAY AND role = 'user'
                      GROUP BY DATE(created_at) 
                      ORDER BY date ASC";
$registrations_result = $conn->query($registrations_sql);

// Create a copy of the initialized dates array for registrations
$reg_counts = $dates;
if($registrations_result) {
    while ($row = $registrations_result->fetch_assoc()) {
        $reg_counts[$row['date']] = (int)$row['count'];
    }
}

// Prepare the final labels and data for the registrations chart
$reg_labels = [];
foreach (array_keys($reg_counts) as $date_str) {
    $reg_labels[] = date("d M", strtotime($date_str));
}
$reg_data = array_values($reg_counts);


// --- 2. Fetch data for key Transactions over the last 7 days ---
$transactions_sql = "SELECT DATE(created_at) as date, COUNT(id) as count 
                     FROM transactions 
                     WHERE created_at >= CURDATE() - INTERVAL 6 DAY 
                       AND type IN ('Recharge', 'Package Purchase', 'Bill Payment')
                     GROUP BY DATE(created_at) 
                     ORDER BY date ASC";
$transactions_result = $conn->query($transactions_sql);

// Create a copy of the initialized dates array for transactions
$txn_counts = $dates;
if($transactions_result) {
    while ($row = $transactions_result->fetch_assoc()) {
        $txn_counts[$row['date']] = (int)$row['count'];
    }
}

// Prepare the final labels and data for the transactions chart
$txn_labels = [];
foreach (array_keys($txn_counts) as $date_str) {
    $txn_labels[] = date("d M", strtotime($date_str));
}
$txn_data = array_values($txn_counts);


// --- 3. Prepare the final output structure ---
$output = [
    'registrations' => [
        'labels' => $reg_labels,
        'data' => $reg_data
    ],
    'transactions' => [
        'labels' => $txn_labels,
        'data' => $txn_data
    ]
];

// Close the database connection
$conn->close();

// Set the content type header to indicate that the response is JSON.
header('Content-Type: application/json');

// Encode the PHP array into a JSON string and echo it.
echo json_encode($output);
?>