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

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

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

$user_id = $_SESSION['user_id'];

// Validate client_id
if (!isset($_POST['client_id']) || empty($_POST['client_id'])) {
    echo json_encode(['success' => false, 'message' => 'Client ID is required']);
    exit();
}

$client_id = intval($_POST['client_id']);

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Check if client exists
    $check_query = "SELECT client_number FROM clients WHERE client_id = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("i", $client_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Client not found']);
        exit();
    }
    
    $client_data = $check_result->fetch_assoc();
    $client_number = $client_data['client_number'];
    
    // Prepare personal information JSON
    $personal_info = [
        'full_name' => $_POST['full_name'] ?? '',
        'date_of_birth' => $_POST['date_of_birth'] ?? '',
        'gender' => $_POST['gender'] ?? '',
        'national_id' => $_POST['national_id'] ?? '',
        'phone_primary' => $_POST['phone_primary'] ?? '',
        'phone_secondary' => $_POST['phone_secondary'] ?? '',
        'email' => $_POST['email'] ?? '',
        'marital_status' => $_POST['marital_status'] ?? ''
    ];
    
    // Prepare address information JSON
    $address_info = [
        'street_address' => $_POST['street_address'] ?? '',
        'city' => $_POST['city'] ?? '',
        'county' => $_POST['county'] ?? '',
        'postal_code' => $_POST['postal_code'] ?? ''
    ];
    
    // Prepare emergency contacts JSON
    $emergency_contacts = [[
        'name' => $_POST['emergency_name'] ?? '',
        'relationship' => $_POST['emergency_relationship'] ?? '',
        'phone' => $_POST['emergency_phone'] ?? ''
    ]];
    
    // Prepare medical information JSON
    $medical_info = [
        'medical_conditions' => $_POST['medical_conditions'] ?? '',
        'medications' => $_POST['medications'] ?? '',
        'blood_type' => $_POST['blood_type'] ?? '',
        'primary_physician' => $_POST['primary_physician'] ?? '',
        'physician_phone' => $_POST['physician_phone'] ?? ''
    ];
    
    // Prepare insurance information JSON
    $insurance_info = [
        'provider' => $_POST['insurance_provider'] ?? '',
        'policy_number' => $_POST['insurance_policy_number'] ?? '',
        'expiry_date' => $_POST['insurance_expiry'] ?? ''
    ];
    
    // Prepare preferences JSON
    $preferences = [
        'preferred_language' => $_POST['preferred_language'] ?? 'English',
        'special_needs' => $_POST['special_needs'] ?? ''
    ];
    
    // Get status and risk level
    $status = $_POST['status'] ?? 'active';
    $risk_level = $_POST['risk_level'] ?? 'low';
    
    // Update client record
    $sql = "UPDATE clients SET
        personal_info = ?,
        address_info = ?,
        emergency_contacts = ?,
        medical_info = ?,
        insurance_info = ?,
        preferences = ?,
        status = ?,
        risk_level = ?,
        updated_at = NOW()
        WHERE client_id = ?";
    
    $stmt = $conn->prepare($sql);
    
    $personal_info_json = json_encode($personal_info);
    $address_info_json = json_encode($address_info);
    $emergency_contacts_json = json_encode($emergency_contacts);
    $medical_info_json = json_encode($medical_info);
    $insurance_info_json = json_encode($insurance_info);
    $preferences_json = json_encode($preferences);
    
    $stmt->bind_param("ssssssssi",
        $personal_info_json,
        $address_info_json,
        $emergency_contacts_json,
        $medical_info_json,
        $insurance_info_json,
        $preferences_json,
        $status,
        $risk_level,
        $client_id
    );
    
    if ($stmt->execute()) {
        // Log the action in audit trail
        $audit_sql = "INSERT INTO audit_log (
            user_id, action_type, entity_type, entity_id,
            description, ip_address, status, created_at
        ) VALUES (?, 'UPDATE', 'clients', ?, ?, ?, 'SUCCESS', NOW())";
        
        $audit_stmt = $conn->prepare($audit_sql);
        $description = "Updated client: " . $client_number;
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        
        $audit_stmt->bind_param("iiss", 
            $user_id, 
            $client_id, 
            $description, 
            $ip_address
        );
        $audit_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Client updated successfully',
            'client_id' => $client_id,
            'client_number' => $client_number
        ]);
    } else {
        $conn->rollback();
        echo json_encode([
            'success' => false,
            'message' => 'Failed to update client: ' . $stmt->error
        ]);
    }
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>