<?php
session_start();
include '../layouts/dbconn.php';
include '../config/security_config.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'];
$client_id = isset($_POST['client_id']) ? intval($_POST['client_id']) : null;

try {
    $conn->begin_transaction();
    
    // Initialize database security
    initializeDatabaseSecurity($conn, $user_id);
    
    // Validate all required consents
    $required_consents = [
        'consent_data_collection',
        'consent_data_sharing',
        'consent_medical_data',
        'consent_emergency',
        'acknowledge_rights'
    ];
    
    foreach ($required_consents as $consent) {
        if (!isset($_POST[$consent]) || $_POST[$consent] !== 'on') {
            echo json_encode(['success' => false, 'message' => 'All consents are required']);
            exit();
        }
    }
    
    // Validate signature
    $signature = trim($_POST['signature'] ?? '');
    if (empty($signature)) {
        echo json_encode(['success' => false, 'message' => 'Electronic signature is required']);
        exit();
    }
    
    // Get IP and user agent
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    
    // Data categories being consented to
    $data_categories = json_encode([
        'personal_information',
        'medical_information',
        'insurance_information',
        'emergency_contacts',
        'care_preferences',
        'service_records'
    ]);
    
    // Insert consent records for each type
    $consent_types = [
        [
            'type' => 'DATA_COLLECTION',
            'purpose' => 'Collection and processing of personal health information for care services',
            'field' => 'consent_data_collection'
        ],
        [
            'type' => 'DATA_SHARING',
            'purpose' => 'Sharing information with healthcare providers, caregivers, and insurance companies',
            'field' => 'consent_data_sharing'
        ],
        [
            'type' => 'MEDICAL_DATA',
            'purpose' => 'Processing of medical data for treatment, payment, and healthcare operations',
            'field' => 'consent_medical_data'
        ]
    ];
    
    foreach ($consent_types as $consent_info) {
        $consent_sql = "INSERT INTO data_consent (
            user_id, consent_type, consent_status, consent_method,
            purpose_description, data_categories, retention_period_days,
            consent_granted_at, ip_address, user_agent, legal_basis,
            version, created_at, updated_at
        ) VALUES (?, ?, 'GRANTED', 'EXPLICIT', ?, ?, ?, NOW(), ?, ?, 'CONSENT', '1.0', NOW(), NOW())";
        
        $stmt = $conn->prepare($consent_sql);
        $retention_days = CLIENT_DATA_RETENTION_DAYS;
        
        $stmt->bind_param("isssiss",
            $user_id,
            $consent_info['type'],
            $consent_info['purpose'],
            $data_categories,
            $retention_days,
            $ip_address,
            $user_agent
        );
        
        $stmt->execute();
    }
    
    // Log the consent in audit trail
    $audit_sql = "INSERT INTO audit_log (
        user_id, action_type, entity_type, entity_id,
        description, ip_address, user_agent,
        old_values, new_values, status, created_at
    ) VALUES (?, 'CONSENT', 'data_consent', ?, ?, ?, ?, ?, ?, 'SUCCESS', NOW())";
    
    $stmt = $conn->prepare($audit_sql);
    $description = "Client provided data protection consent with electronic signature";
    $consent_details = json_encode([
        'signature' => $signature,
        'consent_types' => array_column($consent_types, 'type'),
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    $empty_json = json_encode([]);
    
    $stmt->bind_param("sisssss",
        $user_id,
        $user_id,
        $description,
        $ip_address,
        $user_agent,
        $empty_json,
        $consent_details
    );
    
    $stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Consent recorded successfully',
        'client_id' => $client_id
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Error recording consent: ' . $e->getMessage()
    ]);
}

$conn->close();
?>