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

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

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

// Get the operation type
$operation = isset($_POST['operation']) ? $_POST['operation'] : '';

try {
    switch ($operation) {
        case 'toggle_status':
            togglePatientStatus($conn);
            break;
            
        case 'check_duplicate':
            checkDuplicatePatient($conn);
            break;
            
        case 'get_insurance_info':
            getInsuranceInfo($conn);
            break;
            
        case 'quick_search':
            quickSearchPatient($conn);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid operation']);
            break;
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

/**
 * Toggle patient active status
 */
function togglePatientStatus($conn) {
    $allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
    if (!in_array($_SESSION['role_code'], $allowed_roles)) {
        echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
        return;
    }
    
    $patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;
    $status = isset($_POST['status']) ? (int)$_POST['status'] : 0;
    
    if (!$patient_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid patient ID']);
        return;
    }
    
    $sql = "UPDATE patients SET is_active = ?, updated_at = NOW() WHERE patient_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ii', $status, $patient_id);
    
    if ($stmt->execute()) {
        // Log the activity
        $activity_sql = "INSERT INTO activity_log (user_id, action_type, action_description, ip_address, created_at) 
                        VALUES (?, 'PATIENT_STATUS_CHANGE', ?, ?, NOW())";
        $activity_stmt = $conn->prepare($activity_sql);
        $description = "Changed patient status to " . ($status ? 'active' : 'inactive') . " for patient ID: " . $patient_id;
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $activity_stmt->bind_param('iss', $_SESSION['user_id'], $description, $ip_address);
        $activity_stmt->execute();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Patient status updated successfully',
            'new_status' => $status
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update status']);
    }
}

/**
 * Check for duplicate patient by phone or email
 */
function checkDuplicatePatient($conn) {
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $exclude_user_id = isset($_POST['exclude_user_id']) ? (int)$_POST['exclude_user_id'] : 0;
    
    $duplicates = [];
    
    // Check phone
    if (!empty($phone)) {
        $sql = "SELECT u.user_id, u.full_name, u.phone_primary, p.patient_number 
                FROM users u 
                INNER JOIN patients p ON u.user_id = p.user_id 
                WHERE u.phone_primary = ? AND u.user_id != ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('si', $phone, $exclude_user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $duplicates['phone'] = $result->fetch_assoc();
        }
    }
    
    // Check email
    if (!empty($email)) {
        $sql = "SELECT u.user_id, u.full_name, u.email, p.patient_number 
                FROM users u 
                INNER JOIN patients p ON u.user_id = p.user_id 
                WHERE u.email = ? AND u.user_id != ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('si', $email, $exclude_user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $duplicates['email'] = $result->fetch_assoc();
        }
    }
    
    if (count($duplicates) > 0) {
        echo json_encode([
            'success' => false,
            'has_duplicates' => true,
            'duplicates' => $duplicates
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'has_duplicates' => false
        ]);
    }
}

/**
 * Get insurance provider information
 */
function getInsuranceInfo($conn) {
    $provider_id = isset($_POST['provider_id']) ? (int)$_POST['provider_id'] : 0;
    
    if (!$provider_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid provider ID']);
        return;
    }
    
    $sql = "SELECT provider_id, provider_name, provider_code, phone, email, 
            coverage_percentage, claim_processing_days 
            FROM insurance_providers 
            WHERE provider_id = ? AND is_active = 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $provider_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $provider = $result->fetch_assoc();
        echo json_encode([
            'success' => true,
            'provider' => $provider
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Provider not found']);
    }
}

/**
 * Quick search for patients
 */
function quickSearchPatient($conn) {
    $search_term = isset($_POST['search']) ? trim($_POST['search']) : '';
    
    if (strlen($search_term) < 2) {
        echo json_encode(['success' => false, 'message' => 'Search term too short']);
        return;
    }
    
    $search_param = "%{$search_term}%";
    
    $sql = "SELECT 
                p.patient_id,
                p.patient_number,
                u.full_name,
                u.phone_primary,
                u.email,
                u.gender,
                DATE_FORMAT(u.date_of_birth, '%Y-%m-%d') as date_of_birth,
                TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age,
                p.registration_type,
                p.is_active,
                ip.provider_name
            FROM patients p
            INNER JOIN users u ON p.user_id = u.user_id
            LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
            WHERE (
                u.full_name LIKE ? OR 
                u.phone_primary LIKE ? OR 
                u.email LIKE ? OR 
                p.patient_number LIKE ?
            )
            AND p.is_active = 1
            ORDER BY u.full_name ASC
            LIMIT 10";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssss', $search_param, $search_param, $search_param, $search_param);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $patients = [];
    while ($row = $result->fetch_assoc()) {
        $patients[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'count' => count($patients),
        'patients' => $patients
    ]);
}
?>