<?php
/**
 * AJAX: Get Dashboard Stats
 * Fetch real-time statistics for dashboard
 * Method: GET
 */

require_once '../config/config.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$pdo = getDB();
$userId = $_SESSION['user_id'];
$period = $_GET['period'] ?? 'month';
$dateRange = getDateRange($period);

if (isAdmin()) {
    // Admin statistics
    $stats = [];
    
    // User stats
    $stmt = $pdo->query("SELECT 
                        SUM(CASE WHEN role = 'doctor' THEN 1 ELSE 0 END) as doctors,
                        SUM(CASE WHEN role = 'doctor' AND is_active = 1 THEN 1 ELSE 0 END) as active_doctors
                        FROM users");
    $stats['users'] = $stmt->fetch();
    
    // Case stats
    $stmt = $pdo->query("SELECT 
                        COUNT(*) as total_cases,
                        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_cases,
                        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_cases
                        FROM cases");
    $stats['cases'] = $stmt->fetch();
    
    // Subscription stats
    $stmt = $pdo->query("SELECT 
                        COUNT(*) as total_subs,
                        SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_subs,
                        SUM(amount) as total_revenue
                        FROM subscriptions");
    $stats['subscriptions'] = $stmt->fetch();
    
    // Repertory stats
    $stmt = $pdo->query("SELECT 
                        COUNT(*) as total_rubrics,
                        (SELECT COUNT(*) FROM remedies) as total_remedies
                        FROM rubrics");
    $stats['repertory'] = $stmt->fetch();
    
    // Recent activities
    $stmt = $pdo->query("SELECT 'case' as type, id, created_at, patient_name as name 
                        FROM cases ORDER BY created_at DESC LIMIT 5");
    $stats['recent_activities'] = $stmt->fetchAll();
    
    echo json_encode(['success' => true, 'stats' => $stats, 'role' => 'admin']);
    
} else {
    // Doctor statistics
    $stats = [];
    
    // Case stats
    $stmt = $pdo->prepare("SELECT 
                          COUNT(*) as total_cases,
                          SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_cases,
                          SUM(CASE WHEN status = 'follow-up' THEN 1 ELSE 0 END) as follow_up_cases,
                          SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_cases,
                          COUNT(DISTINCT patient_mobile) as unique_patients
                          FROM cases WHERE user_id = ?");
    $stmt->execute([$userId]);
    $stats['cases'] = $stmt->fetch();
    
    // Monthly trend
    $stmt = $pdo->prepare("SELECT 
                          DATE_FORMAT(created_at, '%Y-%m') as month,
                          COUNT(*) as count
                          FROM cases 
                          WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
                          GROUP BY DATE_FORMAT(created_at, '%Y-%m')
                          ORDER BY month ASC");
    $stmt->execute([$userId]);
    $stats['monthly_trend'] = $stmt->fetchAll();
    
    // Top remedies
    $stmt = $pdo->prepare("SELECT r.name, COUNT(c.id) as count
                          FROM cases c
                          JOIN remedies r ON c.prescribed_remedy_id = r.id
                          WHERE c.user_id = ? AND c.prescribed_remedy_id IS NOT NULL
                          GROUP BY r.id
                          ORDER BY count DESC
                          LIMIT 5");
    $stmt->execute([$userId]);
    $stats['top_remedies'] = $stmt->fetchAll();
    
    // Pending follow-ups
    $stmt = $pdo->prepare("SELECT COUNT(*) as count 
                          FROM cases 
                          WHERE user_id = ? AND follow_up_date IS NOT NULL 
                          AND follow_up_date >= CURDATE() 
                          AND follow_up_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)");
    $stmt->execute([$userId]);
    $stats['pending_followups'] = $stmt->fetch()['count'];
    
    // Recent cases
    $stmt = $pdo->prepare("SELECT id, patient_name, created_at, status 
                          FROM cases 
                          WHERE user_id = ? 
                          ORDER BY created_at DESC 
                          LIMIT 5");
    $stmt->execute([$userId]);
    $stats['recent_cases'] = $stmt->fetchAll();
    
    // Subscription status
    $stmt = $pdo->prepare("SELECT plan_type, end_date, 
                          DATEDIFF(end_date, CURDATE()) as days_remaining
                          FROM subscriptions 
                          WHERE user_id = ? AND is_active = 1 
                          ORDER BY id DESC LIMIT 1");
    $stmt->execute([$userId]);
    $stats['subscription'] = $stmt->fetch();
    
    echo json_encode(['success' => true, 'stats' => $stats, 'role' => 'doctor']);
}
?>