<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if user is ENT doctor
if ($_SESSION['role_code'] !== 'ENT_DOCTOR') {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

$doctor_id = $_SESSION['user_id'];
$period = isset($_POST['period']) ? $_POST['period'] : 'month';

// Calculate date range based on period
$end_date = date('Y-m-d');
switch ($period) {
    case 'week':
        $start_date = date('Y-m-d', strtotime('-7 days'));
        break;
    case 'month':
        $start_date = date('Y-m-d', strtotime('-30 days'));
        break;
    case 'quarter':
        $start_date = date('Y-m-d', strtotime('-90 days'));
        break;
    case 'year':
        $start_date = date('Y-m-d', strtotime('-365 days'));
        break;
    default:
        $start_date = date('Y-m-d', strtotime('-30 days'));
}

// Get consultation revenue
$consultation_query = "SELECT 
    COUNT(*) as total_consultations,
    SUM(consultation_fee) as total_revenue
FROM consultations
WHERE doctor_id = ? 
AND DATE(consultation_date) BETWEEN ? AND ?
AND status = 'COMPLETED'";

$stmt = $conn->prepare($consultation_query);
$stmt->bind_param("iss", $doctor_id, $start_date, $end_date);
$stmt->execute();
$consultation_result = $stmt->get_result()->fetch_assoc();

// Get procedure revenue
$procedure_query = "SELECT 
    COUNT(*) as total_procedures,
    SUM(cost) as total_revenue
FROM medical_procedures
WHERE scheduled_by = ? 
AND DATE(scheduled_date) BETWEEN ? AND ?
AND status = 'COMPLETED'";

$stmt = $conn->prepare($procedure_query);
$stmt->bind_param("iss", $doctor_id, $start_date, $end_date);
$stmt->execute();
$procedure_result = $stmt->get_result()->fetch_assoc();

// Get daily revenue for chart
$daily_query = "SELECT 
    DATE(consultation_date) as date,
    SUM(consultation_fee) as revenue
FROM consultations
WHERE doctor_id = ? 
AND DATE(consultation_date) BETWEEN ? AND ?
AND status = 'COMPLETED'
GROUP BY DATE(consultation_date)
ORDER BY date ASC";

$stmt = $conn->prepare($daily_query);
$stmt->bind_param("iss", $doctor_id, $start_date, $end_date);
$stmt->execute();
$daily_result = $stmt->get_result();

$chart_data = [];
while ($row = $daily_result->fetch_assoc()) {
    $chart_data[] = [
        'date' => date('M d', strtotime($row['date'])),
        'revenue' => floatval($row['revenue'])
    ];
}

$response = [
    'success' => true,
    'consultations' => [
        'count' => intval($consultation_result['total_consultations']),
        'revenue' => floatval($consultation_result['total_revenue'])
    ],
    'procedures' => [
        'count' => intval($procedure_result['total_procedures']),
        'revenue' => floatval($procedure_result['total_revenue'])
    ],
    'total_revenue' => floatval($consultation_result['total_revenue']) + floatval($procedure_result['total_revenue']),
    'chart_data' => $chart_data
];

echo json_encode($response);

$conn->close();
?>