<?php
// public/api/get_dashboard_data.php
// API Endpoint for Dashboard Charts & Metrics

header('Content-Type: application/json');
require_once '../config.php';

// Authentication Check
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'] ?? 'user';
$period = $_GET['period'] ?? 'weekly'; // daily, weekly, monthly

// Date Range Logic
$startDate = date('Y-m-d H:i:s');
$dateFormat = '%Y-%m-%d';
$interval = 'P7D';

switch ($period) {
    case 'daily':
        // Last 24 hours stats (grouped by hour)
        $startDate = date('Y-m-d H:i:s', strtotime('-1 day'));
        $dateFormat = '%H:00'; // Group by hour
        $groupBy = "DATE_FORMAT(sent_at, '%H:00')";
        break;
    case 'monthly':
        // Last 30 days stats (grouped by day)
        $startDate = date('Y-m-d H:i:s', strtotime('-30 days'));
        $dateFormat = '%Y-%m-%d';
        $groupBy = "DATE(sent_at)";
        break;
    case 'weekly':
    default:
        // Last 7 days stats
        $startDate = date('Y-m-d H:i:s', strtotime('-7 days'));
        $dateFormat = '%Y-%m-%d';
        $groupBy = "DATE(sent_at)";
        break;
}

try {
    // 1. Metrics (Total Counts) - Time independent for total, but could be filtered. 
    // Keeping totals global for the top cards as per standard dashboard design.
    $metrics = [];

    if ($role === 'admin') {
        $stmt = $pdo->query("SELECT COUNT(*) FROM users");
        $metrics['total_users'] = $stmt->fetchColumn();

        $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs");
        $metrics['total_sms'] = $stmt->fetchColumn();

        $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs WHERE status = 'sent'");
        $metrics['sms_sent'] = $stmt->fetchColumn();

        $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs WHERE status = 'failed'");
        $metrics['sms_failed'] = $stmt->fetchColumn();
    } else {
        // User specific metrics
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM sms_logs WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $metrics['total_sms'] = $stmt->fetchColumn();

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM sms_logs WHERE user_id = ? AND status = 'sent'");
        $stmt->execute([$user_id]);
        $metrics['sms_sent'] = $stmt->fetchColumn();

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM sms_logs WHERE user_id = ? AND status = 'failed'");
        $stmt->execute([$user_id]);
        $metrics['sms_failed'] = $stmt->fetchColumn();

        // Fetch Balance
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $metrics['balance'] = $stmt->fetchColumn();
    }

    // 2. Chart Data (Filtered by Period)
    // Structure: { labels: ['Mon', 'Tue'...], sent: [10, 20...], failed: [1, 0...] }

    $chartData = [
        'labels' => [],
        'sent' => [],
        'failed' => []
    ];

    // Helper to generate time series labels
    // Simplified: Query db and fill gaps in PHP or just return existing data points
    // For simplicity, returning existing data points.

    $sql = "SELECT $groupBy as label, status, COUNT(*) as count 
            FROM sms_logs 
            WHERE sent_at >= ? ";
    $params = [$startDate];

    if ($role !== 'admin') {
        $sql .= " AND user_id = ? ";
        $params[] = $user_id;
    }

    $sql .= " GROUP BY label, status ORDER BY label ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Process rows into chart friendly format
    // Map: Label -> [sent, failed]
    $dataMap = [];
    foreach ($rows as $row) {
        $label = $row['label'];
        if (!isset($dataMap[$label])) {
            $dataMap[$label] = ['sent' => 0, 'failed' => 0];
        }
        $dataMap[$label][$row['status']] = (int) $row['count'];
    }

    foreach ($dataMap as $label => $counts) {
        $chartData['labels'][] = $label;
        $chartData['sent'][] = $counts['sent'];
        $chartData['failed'][] = $counts['failed'];
    }

    // 3. Status Distribution (Donut Chart) - Global or Period? usually global or last 30 days
    // Let's make it reflect the current period for consistency
    $distribution = [
        'sent' => array_sum($chartData['sent']),
        'failed' => array_sum($chartData['failed'])
    ];
    // Add pending if exists
    // (Optional implementation)

    // 4. Recent Logs
    $logSql = "SELECT id, receiver_number, message, status, sent_at FROM sms_logs ";
    $logParams = [];

    if ($role !== 'admin') {
        $logSql .= " WHERE user_id = ? ";
        $logParams[] = $user_id;
    }

    $logSql .= " ORDER BY sent_at DESC LIMIT 6";

    $stmt = $pdo->prepare($logSql);
    $stmt->execute($logParams);
    $recentLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'metrics' => $metrics,
        'chart' => $chartData,
        'distribution' => $distribution,
        'recent_logs' => $recentLogs
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
