<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../includes/actions.php'; // For permissions if needed

header('Content-Type: application/json');

$action = $_GET['action'] ?? '';
$lang = $_GET['lang'] ?? 'en';

try {
    $db = db();

    // --- ADD TOKEN ---
    if ($action === 'add') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            throw new Exception('Invalid request method');
        }

        $patient_id = $_POST['patient_id'] ?? null;
        $department_id = $_POST['department_id'] ?? null;
        $doctor_id = $_POST['doctor_id'] ?? null;

        if (!$patient_id || !$department_id) {
            throw new Exception('Patient and Department are required');
        }

        // Get next token number for this department today
        $today = date('Y-m-d');
        $stmt = $db->prepare("
            SELECT MAX(token_number) 
            FROM patient_queue 
            WHERE department_id = ? 
            AND DATE(created_at) = ?
        ");
        $stmt->execute([$department_id, $today]);
        $max_token = $stmt->fetchColumn();
        $next_token = ($max_token) ? $max_token + 1 : 1;

        // Insert
        $stmt = $db->prepare("
            INSERT INTO patient_queue (patient_id, department_id, doctor_id, token_number, status, created_at)
            VALUES (?, ?, ?, ?, 'waiting', NOW())
        ");
        $stmt->execute([$patient_id, $department_id, $doctor_id ?: null, $next_token]);
        $queue_id = $db->lastInsertId();

        echo json_encode(['success' => true, 'message' => 'Token generated', 'token_number' => $next_token, 'queue_id' => $queue_id]);
        exit;
    }

    // --- LIST QUEUE ---
    if ($action === 'list') {
        $dept_id = $_GET['department_id'] ?? null;
        $doc_id = $_GET['doctor_id'] ?? null;
        $status = $_GET['status'] ?? null; // Can be comma separated 'waiting,serving'
        $today = date('Y-m-d');

        $where = "WHERE DATE(q.created_at) = ?";
        $params = [$today];

        if ($dept_id) {
            $where .= " AND q.department_id = ?";
            $params[] = $dept_id;
        }
        if ($doc_id) {
            $where .= " AND (q.doctor_id = ? OR q.doctor_id IS NULL)";
            $params[] = $doc_id;
        }
        if ($status) {
            $statuses = explode(',', $status);
            $placeholders = implode(',', array_fill(0, count($statuses), '?'));
            $where .= " AND q.status IN ($placeholders)";
            $params = array_merge($params, $statuses);
        }

        $sql = "
            SELECT q.*, td.name_$lang as target_department_name, 
                   p.name as patient_name, 
                   d.name_$lang as doctor_name, 
                   d.name_en as doctor_name_en, 
                   d.name_ar as doctor_name_ar,
                   d.room_number,
                   dept.name_$lang as department_name,
                   dept.name_en as department_name_en,
                   dept.name_ar as department_name_ar
            FROM patient_queue q
            JOIN patients p ON q.patient_id = p.id
            JOIN departments dept ON q.department_id = dept.id
            LEFT JOIN departments td ON q.target_department_id = td.id
            LEFT JOIN employees d ON q.doctor_id = d.id
            $where
            ORDER BY 
                CASE WHEN q.status = 'serving' THEN 1 WHEN q.status = 'waiting' THEN 2 ELSE 3 END,
                q.token_number ASC
        ";

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

        echo json_encode(['success' => true, 'data' => $queue]);
        exit;
    }

    // --- UPDATE STATUS ---
    if ($action === 'update_status') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            throw new Exception('Invalid request method');
        }

        $queue_id = $_POST['queue_id'] ?? null;
        $new_status = $_POST['status'] ?? null;
        $doctor_id = $_POST['doctor_id'] ?? null; // If a doctor picks up a general department token

        if (!$queue_id || !$new_status) {
            throw new Exception('Queue ID and Status are required');
        }

        if (!in_array($new_status, ['waiting', 'serving', 'completed', 'cancelled'])) {
            throw new Exception('Invalid status');
        }

        // Logic: If setting to 'serving', update doctor_id if provided
        $sql = "UPDATE patient_queue SET status = ?, updated_at = NOW()";
        $params = [$new_status];

        if ($new_status === 'serving' && $doctor_id) {
            $sql .= ", doctor_id = ?";
            $params[] = $doctor_id;
        }
        
        $sql .= " WHERE id = ?";
        $params[] = $queue_id;

        $stmt = $db->prepare($sql);
        $stmt->execute($params);

        echo json_encode(['success' => true, 'message' => 'Status updated']);
        exit;
    }
    
    
    // --- TRANSFER TOKEN ---
    if ($action === 'transfer') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            throw new Exception('Invalid request method');
        }

        $queue_id = $_POST['queue_id'] ?? null;
        $new_department_id = $_POST['department_id'] ?? null;
        $new_doctor_id = $_POST['doctor_id'] ?? null;

        if (!$queue_id || !$new_department_id) {
            throw new Exception('Queue ID and Target Department are required');
        }

        // Get current queue token
        $stmt = $db->prepare("SELECT patient_id FROM patient_queue WHERE id = ?");
        $stmt->execute([$queue_id]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$current) {
            throw new Exception('Queue token not found');
        }

        // Complete the old token
        $stmt = $db->prepare("UPDATE patient_queue SET status = 'completed', updated_at = NOW() WHERE id = ?");
        $stmt->execute([$queue_id]);

        // Create new token
        $today = date('Y-m-d');
        $stmt = $db->prepare("
            SELECT MAX(token_number) 
            FROM patient_queue 
            WHERE department_id = ? 
            AND DATE(created_at) = ?
        ");
        $stmt->execute([$new_department_id, $today]);
        $max_token = $stmt->fetchColumn();
        $next_token = ($max_token) ? $max_token + 1 : 1;

        $stmt = $db->prepare("
            INSERT INTO patient_queue (patient_id, department_id, doctor_id, token_number, status, created_at)
            VALUES (?, ?, ?, ?, 'waiting', NOW())
        ");
        $stmt->execute([$current['patient_id'], $new_department_id, $new_doctor_id ?: null, $next_token]);
        $new_queue_id = $db->lastInsertId();

        echo json_encode(['success' => true, 'message' => 'Token transferred', 'token_number' => $next_token, 'new_queue_id' => $new_queue_id]);
        exit;
    }

    // --- SUMMARY ---
    if ($action === 'summary') {
        $today = date('Y-m-d');
        $dept_id = $_GET['department_id'] ?? null;
        
        $where = "WHERE DATE(q.created_at) = ?";
        $params = [$today];
        
        if ($dept_id) {
            $where .= " AND q.department_id = ?";
            $params[] = $dept_id;
        }

        $sql = "
            SELECT 
                dept.name_$lang as department_name,
                dept.id as department_id,
                SUM(CASE WHEN q.status = 'waiting' THEN 1 ELSE 0 END) as waiting,
                SUM(CASE WHEN q.status = 'serving' THEN 1 ELSE 0 END) as serving,
                SUM(CASE WHEN q.status = 'completed' THEN 1 ELSE 0 END) as completed
            FROM patient_queue q
            JOIN departments dept ON q.department_id = dept.id
            LEFT JOIN departments td ON q.target_department_id = td.id
            $where
            GROUP BY dept.id
        ";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $summary = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'data' => $summary]);
        exit;
    }

    // --- GET ADS ---
    if ($action === 'get_ads') {
        $stmt = $db->query("SELECT * FROM queue_ads WHERE active = 1 ORDER BY created_at DESC");
        $ads = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Return both languages
        $data = array_map(function($ad) {
            return [
                'id' => $ad['id'],
                'text_en' => $ad['text_en'],
                'text_ar' => $ad['text_ar']
            ];
        }, $ads);

        echo json_encode(['success' => true, 'data' => $data]);
        exit;
    }

    throw new Exception('Invalid action');

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}