<?php
/**
 * API: Get Cases
 * Retrieve cases for mobile app with pagination and filters
 * Method: GET
 * Authentication: API Key or JWT Token
 */

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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key');

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

// ============================================
// AUTHENTICATION
// ============================================

function authenticateAPI() {
    $headers = getallheaders();
    $apiKey = $headers['X-API-Key'] ?? $_SERVER['HTTP_X_API_KEY'] ?? '';
    
    if (empty($apiKey)) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'API key required']);
        exit;
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT id, full_name, email FROM users WHERE api_key = ? AND role = 'doctor' AND is_active = 1");
    $stmt->execute([$apiKey]);
    $user = $stmt->fetch();
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Invalid API key']);
        exit;
    }
    
    return $user;
}

// ============================================
// MAIN PROCESSING
// ============================================

if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Authenticate user
$user = authenticateAPI();
$userId = $user['id'];

$pdo = getDB();

// Get query parameters
$page = (int)($_GET['page'] ?? 1);
$limit = (int)($_GET['limit'] ?? 20);
$status = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';
$offset = ($page - 1) * $limit;

// Build query
$where = "c.user_id = ?";
$params = [$userId];

if ($status != 'all') {
    $where .= " AND c.status = ?";
    $params[] = $status;
}

if (!empty($search)) {
    $where .= " AND (c.patient_name LIKE ? OR c.patient_mobile LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if (!empty($dateFrom)) {
    $where .= " AND DATE(c.created_at) >= ?";
    $params[] = $dateFrom;
}

if (!empty($dateTo)) {
    $where .= " AND DATE(c.created_at) <= ?";
    $params[] = $dateTo;
}

// Get total count
$countSql = "SELECT COUNT(*) as total FROM cases c WHERE $where";
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$total = $stmt->fetch()['total'];

// Get cases
$sql = "SELECT c.id, c.patient_name, c.patient_mobile, c.patient_age, c.patient_gender,
        c.chief_complaint, c.created_at, c.updated_at, c.status, c.follow_up_date,
        c.prescribed_remedy_id, c.prescription_potency,
        r.name as remedy_name, r.abbreviation as remedy_abbreviation
        FROM cases c
        LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
        WHERE $where
        ORDER BY c.created_at DESC
        LIMIT ? OFFSET ?";

$params[] = $limit;
$params[] = $offset;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$cases = $stmt->fetchAll();

// Format cases for mobile
$formattedCases = [];
foreach ($cases as $case) {
    // Get follow-ups for this case
    $stmt = $pdo->prepare("SELECT id, follow_up_date, progress, new_symptoms, remedy_repeated, created_at 
                          FROM follow_ups WHERE case_id = ? ORDER BY follow_up_date DESC");
    $stmt->execute([$case['id']]);
    $followUps = $stmt->fetchAll();
    
    // Get selected rubrics
    $stmt = $pdo->prepare("SELECT selected_rubrics, repertorization_result FROM cases WHERE id = ?");
    $stmt->execute([$case['id']]);
    $caseData = $stmt->fetch();
    
    $formattedCases[] = [
        'id' => $case['id'],
        'patient_name' => $case['patient_name'],
        'patient_mobile' => $case['patient_mobile'],
        'patient_age' => $case['patient_age'],
        'patient_gender' => $case['patient_gender'],
        'chief_complaint' => $case['chief_complaint'],
        'created_at' => $case['created_at'],
        'updated_at' => $case['updated_at'],
        'status' => $case['status'],
        'follow_up_date' => $case['follow_up_date'],
        'prescription' => $case['prescribed_remedy_id'] ? [
            'remedy_id' => $case['prescribed_remedy_id'],
            'remedy_name' => $case['remedy_name'],
            'remedy_abbreviation' => $case['remedy_abbreviation'],
            'potency' => $case['prescription_potency']
        ] : null,
        'follow_ups' => $followUps,
        'selected_rubrics' => json_decode($caseData['selected_rubrics'] ?? '[]', true),
        'repertorization_result' => json_decode($caseData['repertorization_result'] ?? '[]', true)
    ];
}

// Return response
echo json_encode([
    'success' => true,
    'data' => [
        'cases' => $formattedCases,
        'pagination' => [
            'current_page' => $page,
            'per_page' => $limit,
            'total' => $total,
            'total_pages' => ceil($total / $limit)
        ]
    ],
    'user' => [
        'id' => $user['id'],
        'name' => $user['full_name'],
        'email' => $user['email']
    ]
]);
?>