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

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

// Set security headers
setSecurityHeaders();

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

// Check session timeout
checkSessionTimeout();

$user_id = $_SESSION['user_id'];

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Initialize database security (CRITICAL for encryption)
    initializeDatabaseSecurity($conn, $user_id);
    
    // Check if user has permission to create clients
    if (!canAccessPHI($conn, $user_id, 'clients')) {
        throw new Exception('You do not have permission to create client records');
    }
    
    // Sanitize all inputs
    $_POST = sanitizeInput($_POST);
    
    // Generate client number using the database function
    $client_number_query = "SELECT GenerateClientNumber() as client_number";
    $result = $conn->query($client_number_query);
    $client_number = $result->fetch_assoc()['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 (will be encrypted by trigger)
    $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 (will be encrypted by trigger)
    $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';
    
    // Insert client record (encryption trigger will fire automatically)
    $sql = "INSERT INTO clients (
        client_number,
        personal_info,
        address_info,
        emergency_contacts,
        medical_info,
        insurance_info,
        preferences,
        status,
        risk_level,
        created_at,
        updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
    
    $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("sssssssss",
        $client_number,
        $personal_info_json,
        $address_info_json,
        $emergency_contacts_json,
        $medical_info_json,
        $insurance_info_json,
        $preferences_json,
        $status,
        $risk_level
    );
    
    if ($stmt->execute()) {
        $client_id = $conn->insert_id;
        
        // Log PHI access
        logPHIAccess(
            $conn,
            $user_id,
            'clients',
            $client_id,
            'CREATE',
            ['personal_info', 'medical_info', 'insurance_info', 'emergency_contacts'],
            'Creating new client record'
        );
        
        // Check if consent was provided (required before creating client)
        $consent_check_sql = "SELECT COUNT(*) as consent_count 
                              FROM data_consent 
                              WHERE user_id = ? 
                              AND consent_type = 'MEDICAL_DATA' 
                              AND consent_status = 'GRANTED'";
        $consent_stmt = $conn->prepare($consent_check_sql);
        $consent_stmt->bind_param("i", $user_id);
        $consent_stmt->execute();
        $consent_result = $consent_stmt->get_result()->fetch_assoc();
        
        if ($consent_result['consent_count'] == 0) {
            // No consent found - log warning but allow creation (consent may be provided separately)
            $warning_sql = "INSERT INTO audit_log (
                user_id, action_type, entity_type, entity_id,
                description, status, created_at
            ) VALUES (?, 'WARNING', 'clients', ?, 'Client created without documented consent', 'WARNING', NOW())";
            
            $warning_stmt = $conn->prepare($warning_sql);
            $warning_stmt->bind_param("ii", $user_id, $client_id);
            $warning_stmt->execute();
        }
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Client added successfully',
            'client_id' => $client_id,
            'client_number' => $client_number,
            'consent_required' => $consent_result['consent_count'] == 0,
            'redirect_consent' => $consent_result['consent_count'] == 0 ? 'client_consent.php?client_id=' . $client_id : null
        ]);
    } else {
        $conn->rollback();
        echo json_encode([
            'success' => false,
            'message' => 'Failed to save client: ' . $stmt->error
        ]);
    }
    
} catch (Exception $e) {
    $conn->rollback();
    
    // Log the error
    detectSecurityIncident($conn, $user_id, 'DATA_BREACH', 'Failed client creation: ' . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>