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

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

try {
    // Validate required fields
    $required_fields = ['code', 'member_no', 'provider', 'date_reported', 'reported_by', 
                       'pre_diagnosis', 'authority_type', 'available_limit', 'reserve', 'family_no'];
                       
    foreach ($required_fields as $field) {
        if (!isset($_POST[$field]) || empty($_POST[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }

    // Start transaction
    $conn->begin_transaction();

    // Create pre-auth code
    $pre_auth_code = 'PA' . str_pad($_POST['code'], 6, '0', STR_PAD_LEFT);

    // Get current anniversary for member based on report date
    $sql_anniv = "SELECT anniv 
                  FROM member_anniversary 
                  WHERE member_no = ? 
                  AND start_date <= ? 
                  AND end_date >= ?
                  LIMIT 1";
    
    $stmt = $conn->prepare($sql_anniv);
    $stmt->bind_param("sss", 
        $_POST['member_no'], 
        $_POST['date_reported'], 
        $_POST['date_reported']
    );
    $stmt->execute();
    $anniv_result = $stmt->get_result();
    
    if ($anniv_row = $anniv_result->fetch_assoc()) {
        $anniv = $anniv_row['anniv'];
    } else {
        throw new Exception("No valid anniversary found for member on the reported date");
    }

    // Prepare local variables for binding
    $code = $_POST['code'];
    $member_no = $_POST['member_no'];
    $provider = $_POST['provider'];
    $date_reported = $_POST['date_reported'];
    $reported_by = $_POST['reported_by'];
    $pre_diagnosis = $_POST['pre_diagnosis'];
    $authority_type = $_POST['authority_type'];
    $ward = $_POST['ward'] ?: null;
    $available_limit = $_POST['available_limit'];
    $admit_days = $_POST['admit_days'] ?: null;
    $reserve = $_POST['reserve'];
    $notes = $_POST['notes'];
    $doctor_attending = $_POST['doctor_attending'];
    $family_no = $_POST['family_no'];

    // Validate numeric values
    if (!is_numeric($reserve) || floatval($reserve) <= 0) {
        throw new Exception("Invalid reserve amount");
    }

    if (!is_numeric($available_limit) || floatval($available_limit) <= 0) {
        throw new Exception("Invalid available limit");
    }

    if ($reserve > $available_limit) {
        throw new Exception("Reserve amount cannot exceed available limit");
    }

    // Insert into pre_authorization table
    $sql = "INSERT INTO pre_authorization (
        code, 
        member_no, 
        provider, 
        date_reported, 
        reported_by,
        pre_diagnosis, 
        authority_type, 
        ward, 
        available_limit,
        admit_days, 
        reserve, 
        notes, 
        anniv, 
        doctor_attending,
        date_entered, 
        family_no, 
        pre_auth_code,
        service
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), ?, ?, ?)";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Failed to prepare statement: " . $conn->error);
    }

    // Default service to null for now
    $service = null;

    $stmt->bind_param(
        "isssssiiidiissssi",
        $code,              // code (integer)
        $member_no,         // member_no (string)
        $provider,          // provider (string)
        $date_reported,     // date_reported (string)
        $reported_by,       // reported_by (string)
        $pre_diagnosis,     // pre_diagnosis (string)
        $authority_type,    // authority_type (integer)
        $ward,             // ward (integer)
        $available_limit,   // available_limit (integer)
        $admit_days,       // admit_days (integer)
        $reserve,          // reserve (double)
        $notes,            // notes (string)
        $anniv,            // anniv (integer)
        $doctor_attending, // doctor_attending (string)
        $family_no,        // family_no (string)
        $pre_auth_code,    // pre_auth_code (string)
        $service          // service (integer)
    );

    if (!$stmt->execute()) {
        throw new Exception("Failed to save pre-authorization: " . $stmt->error);
    }

    // Log activity
    $activity_sql = "INSERT INTO activity_log (
        user_id, 
        action, 
        table_name,
        record_id,
        new_values,
        ip_address,
        user_agent,
        action_date,
        additional_info
    ) VALUES (?, 'CREATE', 'pre_authorization', ?, ?, ?, ?, NOW(), ?)";

    $log_details = json_encode([
        'pre_auth_code' => $pre_auth_code,
        'member_no' => $member_no,
        'reserve' => $reserve,
        'authority_type' => $authority_type,
        'available_limit' => $available_limit,
        'anniv' => $anniv
    ]);

    $additional_info = "Pre-authorization created with reserve amount: " . number_format($reserve, 2);

    $stmt = $conn->prepare($activity_sql);
    if (!$stmt) {
        throw new Exception("Failed to prepare activity log statement: " . $conn->error);
    }

    // Bind parameters
    $stmt->bind_param(
        "sissss",  // 7 placeholders: s (string), i (integer), s (string), s (string), s (string), s (string), s (string)
        $_SESSION['user_id'],  // user_id (string)
        $code,                 // record_id (integer)
        $log_details,          // new_values (string)
        $_SERVER['REMOTE_ADDR'],  // ip_address (string)
        $_SERVER['HTTP_USER_AGENT'],  // user_agent (string)
        $additional_info       // additional_info (string)
    );

    if (!$stmt->execute()) {
        throw new Exception("Failed to log activity: " . $stmt->error);
    }

    // Commit transaction
    $conn->commit();

    echo json_encode([
        'success' => true,
        'code' => $code,
        'pre_auth_code' => $pre_auth_code,
        'message' => 'Pre-authorization created successfully'
    ]);

} catch (Exception $e) {
    if ($conn->connect_error) {
        error_log("Connection failed: " . $conn->connect_error);
    }
    
    if (isset($conn) && $conn->errno) {
        error_log("MySQL Error: " . $conn->error);
    }
    
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    
    error_log("Error saving pre-auth: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>