<?php
session_start();
include '../layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$user_id = $_SESSION['user_id'];
$visit_id = $_POST['visit_id'] ?? '';
$doctor_id = $_POST['doctor_id'] ?? '';
$priority = $_POST['priority'] ?? 'ROUTINE';
$notes = $_POST['notes'] ?? '';

// Validate input
if (empty($visit_id) || empty($doctor_id)) {
    echo json_encode(['success' => false, 'message' => 'Visit ID and Doctor ID are required']);
    exit();
}

try {
    $conn->begin_transaction();
    
    // Check if visit exists and is in correct status
    $visit_check = "SELECT visit_id, patient_id, status FROM patient_visits WHERE visit_id = ?";
    $stmt = $conn->prepare($visit_check);
    $stmt->bind_param("i", $visit_id);
    $stmt->execute();
    $visit = $stmt->get_result()->fetch_assoc();
    
    if (!$visit) {
        throw new Exception("Visit not found");
    }
    
    if ($visit['status'] !== 'REGISTERED') {
        throw new Exception("Visit is not in the correct status for doctor assignment");
    }
    
    // Check if doctor exists and is active
    $doctor_check = "SELECT d.doctor_id, d.consultation_fee, u.full_name, u.status 
                     FROM doctors d 
                     INNER JOIN users u ON d.user_id = u.user_id 
                     WHERE d.doctor_id = ? AND d.is_active = 1 AND u.status = 'ACTIVE'";
    $stmt = $conn->prepare($doctor_check);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $doctor = $stmt->get_result()->fetch_assoc();
    
    if (!$doctor) {
        throw new Exception("Doctor not found or inactive");
    }
    
    // Check if there's already a consultation for this visit
    $existing_consultation = "SELECT consultation_id FROM consultations WHERE visit_id = ?";
    $stmt = $conn->prepare($existing_consultation);
    $stmt->bind_param("i", $visit_id);
    $stmt->execute();
    $existing = $stmt->get_result()->fetch_assoc();
    
    if ($existing) {
        throw new Exception("A consultation is already assigned to this visit");
    }
    
    // Create consultation record
    $consultation_number = 'CON' . date('Ymd') . str_pad($visit_id, 6, '0', STR_PAD_LEFT);
    
    $insert_consultation = "INSERT INTO consultations (
        consultation_number, visit_id, patient_id, doctor_id, 
        consultation_fee, status, started_at
    ) VALUES (?, ?, ?, ?, ?, 'IN_PROGRESS', NOW())";
    
    $stmt = $conn->prepare($insert_consultation);
    $stmt->bind_param("siids", 
        $consultation_number, $visit_id, $visit['patient_id'], 
        $doctor_id, $doctor['consultation_fee']
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to create consultation record");
    }
    
    $consultation_id = $conn->insert_id();
    
    // Update visit status to IN_CONSULTATION
    $update_visit = "UPDATE patient_visits SET status = 'IN_CONSULTATION' WHERE visit_id = ?";
    $stmt = $conn->prepare($update_visit);
    $stmt->bind_param("i", $visit_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to update visit status");
    }
    
    // Log the activity
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent) 
               VALUES (?, 'ASSIGN_DOCTOR', 'CONSULTATIONS', ?, 'CONSULTATION', ?, ?, ?)";
    
    $log_values = json_encode([
        'visit_id' => $visit_id,
        'doctor_id' => $doctor_id,
        'doctor_name' => $doctor['full_name'],
        'consultation_id' => $consultation_id,
        'priority' => $priority,
        'notes' => $notes
    ]);
    
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    
    $log_stmt = $conn->prepare($log_sql);
    $log_stmt->bind_param("iisss", $user_id, $consultation_id, $log_values, $ip_address, $user_agent);
    $log_stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Doctor assigned successfully',
        'consultation_id' => $consultation_id,
        'doctor_name' => $doctor['full_name']
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    error_log("Doctor assignment error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

$conn->close();
?>