<?php
// smart/smart_handler.php
session_start();
require_once('../layouts/dbconn.php');
require_once('../layouts/session.php');
require_once('../layouts/smart_config.php');

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

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'fetch_pending_session':
        fetchPendingSession($conn);
        break;
        
    case 'activate_session':
        activateSession($conn);
        break;
        
    case 'fetch_member_benefits':
        fetchMemberBenefits($conn);
        break;
        
    case 'check_sbb_rules':
        checkSBBRules($conn);
        break;
        
    case 'submit_preauth':
        submitPreauth($conn);
        break;
        
    case 'fetch_preauth_feedback':
        fetchPreauthFeedback($conn);
        break;
        
    case 'upload_claim':
        uploadClaim($conn);
        break;
        
    case 'check_claim_status':
        checkClaimStatus($conn);
        break;
        
    case 'close_session':
        closeSession($conn);
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}

/**
 * Fetch Pending Smart Session
 */
function fetchPendingSession($conn) {
    $patient_id = $_POST['patient_id'] ?? 0;
    
    // Get patient's insurance member number
    $stmt = $conn->prepare("
        SELECT p.patient_number, pi.member_number 
        FROM patients p
        LEFT JOIN patient_insurance pi ON p.patient_id = pi.patient_id
        WHERE p.patient_id = ?
    ");
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    
    if (!$result) {
        echo json_encode(['success' => false, 'message' => 'Patient not found']);
        return;
    }
    
    $patientNumber = $result['patient_number'] ?? $result['member_number'];
    
    // Call Smart API to fetch pending session
    $response = makeSmartAPIRequest(
        "/api/visit?patientNumber={$patientNumber}&sessionStatus=PENDING",
        'GET',
        null,
        $conn
    );
    
    if ($response['success'] && isset($response['data']['content'])) {
        $sessions = $response['data']['content'];
        
        if (!empty($sessions)) {
            // Store session in database
            foreach ($sessions as $session) {
                $smartSessionId = $session['session_id'] ?? null;
                $smartPatientNumber = $session['patient_number'] ?? null;
                $smartMemberNumber = $session['member_number'] ?? null;
                $smartGlobalId = $session['global_id'] ?? null;
                $sessionType = $session['session_type'] ?? 'Outpatient';
                
                // Check if session already exists
                $checkStmt = $conn->prepare("
                    SELECT id FROM smart_sessions 
                    WHERE smart_session_id = ? AND patient_id = ?
                ");
                $checkStmt->bind_param("si", $smartSessionId, $patient_id);
                $checkStmt->execute();
                $existing = $checkStmt->get_result()->fetch_assoc();
                
                if (!$existing) {
                    // Insert new session
                    $insertStmt = $conn->prepare("
                        INSERT INTO smart_sessions (
                            patient_id, smart_session_id, smart_patient_number,
                            smart_member_number, smart_global_id, session_status,
                            session_type
                        ) VALUES (?, ?, ?, ?, ?, 'PENDING', ?)
                    ");
                    $insertStmt->bind_param(
                        "isssss",
                        $patient_id, $smartSessionId, $smartPatientNumber,
                        $smartMemberNumber, $smartGlobalId, $sessionType
                    );
                    $insertStmt->execute();
                }
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Pending sessions fetched successfully',
                'sessions' => $sessions
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'No pending sessions found. Please forward card on SmartLink.'
            ]);
        }
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to fetch sessions'
        ]);
    }
}

/**
 * Activate Smart Session with Visit Number
 */
function activateSession($conn) {
    $smart_session_id = $_POST['smart_session_id'] ?? '';
    $visit_id = $_POST['visit_id'] ?? 0;
    $visit_number = $_POST['visit_number'] ?? '';
    
    if (!$smart_session_id || !$visit_number) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        return;
    }
    
    // Call Smart API to activate session
    $response = makeSmartAPIRequest(
        "/api/visit/{$smart_session_id}/visit-number/{$visit_number}",
        'PUT',
        null,
        $conn
    );
    
    if ($response['success']) {
        // Update local session record
        $stmt = $conn->prepare("
            UPDATE smart_sessions 
            SET session_status = 'ACTIVE', visit_id = ?, updated_at = NOW()
            WHERE smart_session_id = ?
        ");
        $stmt->bind_param("is", $visit_id, $smart_session_id);
        $stmt->execute();
        
        // Update visit record
        $updateVisit = $conn->prepare("
            UPDATE visits 
            SET smart_session_id = (
                SELECT id FROM smart_sessions WHERE smart_session_id = ?
            )
            WHERE visit_id = ?
        ");
        $updateVisit->bind_param("si", $smart_session_id, $visit_id);
        $updateVisit->execute();
        
        echo json_encode([
            'success' => true,
            'message' => 'Session activated successfully'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to activate session'
        ]);
    }
}

/**
 * Fetch Member Benefits
 */
function fetchMemberBenefits($conn) {
    $patient_number = $_POST['patient_number'] ?? '';
    $session_id = $_POST['session_id'] ?? '';
    
    if (!$patient_number || !$session_id) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        return;
    }
    
    // Call Smart API
    $response = makeSmartAPIRequest(
        "/api/member?patientNumber={$patient_number}&sessionId={$session_id}",
        'GET',
        null,
        $conn
    );
    
    if ($response['success'] && isset($response['data']['content'])) {
        $memberData = $response['data']['content'][0] ?? null;
        
        if ($memberData) {
            // Get local session ID
            $stmt = $conn->prepare("
                SELECT id FROM smart_sessions WHERE smart_session_id = ?
            ");
            $stmt->bind_param("s", $session_id);
            $stmt->execute();
            $localSession = $stmt->get_result()->fetch_assoc();
            
            if ($localSession) {
                $localSessionId = $localSession['id'];
                
                // Store benefits data
                $benefitsJson = json_encode($memberData['benefits'] ?? []);
                $updateStmt = $conn->prepare("
                    UPDATE smart_sessions 
                    SET benefits_data = ?, updated_at = NOW()
                    WHERE id = ?
                ");
                $updateStmt->bind_param("si", $benefitsJson, $localSessionId);
                $updateStmt->execute();
                
                // Store individual benefits
                foreach ($memberData['benefits'] as $benefit) {
                    $poolNumber = $benefit['pool_nr'] ?? '';
                    $poolDesc = $benefit['pool_desc'] ?? '';
                    $amount = $benefit['amount'] ?? 0;
                    $claimable = $benefit['claimable'] ? 1 : 0;
                    $parentPoolNumber = $benefit['parent_pool_nr'] ?? null;
                    $serviceGroups = json_encode($benefit['groups'] ?? []);
                    
                    // Check if benefit exists
                    $checkBenefit = $conn->prepare("
                        SELECT id FROM smart_benefits 
                        WHERE session_id = ? AND pool_number = ?
                    ");
                    $checkBenefit->bind_param("is", $localSessionId, $poolNumber);
                    $checkBenefit->execute();
                    $existingBenefit = $checkBenefit->get_result()->fetch_assoc();
                    
                    if (!$existingBenefit) {
                        $insertBenefit = $conn->prepare("
                            INSERT INTO smart_benefits (
                                session_id, pool_number, pool_description, amount,
                                claimable, parent_pool_number, service_groups
                            ) VALUES (?, ?, ?, ?, ?, ?, ?)
                        ");
                        $insertBenefit->bind_param(
                            "isssdss",
                            $localSessionId, $poolNumber, $poolDesc, $amount,
                            $claimable, $parentPoolNumber, $serviceGroups
                        );
                        $insertBenefit->execute();
                    }
                }
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Benefits fetched successfully',
                'data' => $memberData
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'No member data found'
            ]);
        }
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to fetch benefits'
        ]);
    }
}

/**
 * Check SBB Rules (Pre-authorization check)
 */
function checkSBBRules($conn) {
    $items = json_decode($_POST['items'] ?? '[]', true);
    $medical_aid_code = $_POST['medical_aid_code'] ?? '';
    $medical_aid_number = $_POST['medical_aid_number'] ?? '';
    $medical_aid_plan = $_POST['medical_aid_plan'] ?? '';
    $policy_id = $_POST['policy_id'] ?? '';
    
    if (empty($items)) {
        echo json_encode(['success' => false, 'message' => 'No items provided']);
        return;
    }
    
    $requestData = [
        'items' => $items,
        'medical_aid_code' => $medical_aid_code,
        'medical_aid_number' => $medical_aid_number,
        'medical_aid_plan' => $medical_aid_plan,
        'policy_id' => $policy_id
    ];
    
    // Call Smart API
    $response = makeSmartAPIRequest(
        "/api/sbb-rules",
        'POST',
        $requestData,
        $conn
    );
    
    if ($response['success']) {
        echo json_encode([
            'success' => true,
            'message' => 'Rules fetched successfully',
            'data' => $response['data']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to check rules'
        ]);
    }
}

/**
 * Submit Pre-authorization Request
 */
function submitPreauth($conn) {
    $visit_id = $_POST['visit_id'] ?? 0;
    $preauthData = json_decode($_POST['preauth_data'] ?? '{}', true);
    
    if (!$visit_id || empty($preauthData)) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        return;
    }
    
    // Call Smart API
    $response = makeSmartAPIRequest(
        "/api/preauth-request",
        'POST',
        $preauthData,
        $conn
    );
    
    if ($response['success']) {
        // Get smart session
        $stmt = $conn->prepare("
            SELECT ss.id as session_id
            FROM visits v
            JOIN smart_sessions ss ON v.smart_session_id = ss.id
            WHERE v.visit_id = ?
        ");
        $stmt->bind_param("i", $visit_id);
        $stmt->execute();
        $session = $stmt->get_result()->fetch_assoc();
        
        if ($session) {
            // Store preauth request
            $preauthCode = $response['data']['content'][0]['preauth_request_code'] ?? '';
            $invoiceNumber = $preauthData['invoice_number'] ?? '';
            $preauthType = $preauthData['preauth_type'] ?? 'ZERO';
            $requestedAmount = $preauthData['treatment_cost_estimate'] ?? 0;
            $requestDataJson = json_encode($preauthData);
            $responseDataJson = json_encode($response['data']);
            
            $insertPreauth = $conn->prepare("
                INSERT INTO smart_preauth (
                    visit_id, smart_session_id, preauth_request_code,
                    invoice_number, preauth_type, requested_amount,
                    request_data, response_data, preauth_status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')
            ");
            $insertPreauth->bind_param(
                "iisssdss",
                $visit_id, $session['session_id'], $preauthCode,
                $invoiceNumber, $preauthType, $requestedAmount,
                $requestDataJson, $responseDataJson
            );
            $insertPreauth->execute();
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Pre-authorization submitted successfully',
            'data' => $response['data']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to submit pre-authorization'
        ]);
    }
}

/**
 * Fetch Pre-authorization Feedback
 */
function fetchPreauthFeedback($conn) {
    $visit_number = $_POST['visit_number'] ?? '';
    $invoice_number = $_POST['invoice_number'] ?? '';
    
    if (!$visit_number) {
        echo json_encode(['success' => false, 'message' => 'Missing visit number']);
        return;
    }
    
    $endpoint = "/api/preauth-request?visitNo={$visit_number}";
    if ($invoice_number) {
        $endpoint .= "&invoiceNo={$invoice_number}";
    }
    
    // Call Smart API
    $response = makeSmartAPIRequest($endpoint, 'GET', null, $conn);
    
    if ($response['success'] && isset($response['data']['content'])) {
        $feedbackData = $response['data']['content'][0] ?? null;
        
        if ($feedbackData) {
            // Update preauth record
            $preauthCode = $feedbackData['preauth_request_code'] ?? '';
            $consumedAmount = $feedbackData['consumed_amount'] ?? 0;
            $responseDataJson = json_encode($feedbackData);
            
            // Determine status based on rules
            $preauthStatus = 'PENDING';
            if (isset($feedbackData['rules']) && !empty($feedbackData['rules'])) {
                $firstRule = $feedbackData['rules'][0];
                $approvedAmount = $firstRule['approved_amount'] ?? 0;
                $declinedAmount = $firstRule['declined_amount'] ?? 0;
                $requestedAmount = $firstRule['requested_amount'] ?? 0;
                
                if ($approvedAmount == $requestedAmount && $declinedAmount == 0) {
                    $preauthStatus = 'APPROVED';
                } elseif ($approvedAmount > 0 && $declinedAmount > 0) {
                    $preauthStatus = 'PARTIAL';
                } elseif ($approvedAmount == 0 && $declinedAmount > 0) {
                    $preauthStatus = 'DECLINED';
                }
                
                $updatePreauth = $conn->prepare("
                    UPDATE smart_preauth 
                    SET approved_amount = ?, declined_amount = ?,
                        preauth_status = ?, response_data = ?,
                        updated_at = NOW()
                    WHERE preauth_request_code = ?
                ");
                $updatePreauth->bind_param(
                    "ddsss",
                    $approvedAmount, $declinedAmount, $preauthStatus,
                    $responseDataJson, $preauthCode
                );
                $updatePreauth->execute();
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Pre-authorization feedback fetched',
                'data' => $feedbackData,
                'status' => $preauthStatus
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'No pre-authorization feedback found'
            ]);
        }
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to fetch feedback'
        ]);
    }
}

/**
 * Upload Claim to Smart
 */
function uploadClaim($conn) {
    $invoice_id = $_POST['invoice_id'] ?? 0;
    $visit_id = $_POST['visit_id'] ?? 0;
    
    if (!$invoice_id || !$visit_id) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        return;
    }
    
    // Build claim data
    $claimData = buildClaimData($conn, $invoice_id, $visit_id);
    
    if (!$claimData) {
        echo json_encode(['success' => false, 'message' => 'Failed to build claim data']);
        return;
    }
    
    // Get session details
    $stmt = $conn->prepare("
        SELECT ss.smart_patient_number, ss.smart_session_id
        FROM visits v
        JOIN smart_sessions ss ON v.smart_session_id = ss.id
        WHERE v.visit_id = ?
    ");
    $stmt->bind_param("i", $visit_id);
    $stmt->execute();
    $session = $stmt->get_result()->fetch_assoc();
    
    if (!$session) {
        echo json_encode(['success' => false, 'message' => 'Smart session not found']);
        return;
    }
    
    $patientNumber = $session['smart_patient_number'];
    $sessionId = $session['smart_session_id'];
    
    // Call Smart API
    $response = makeSmartAPIRequest(
        "/api/claims?patientNumber={$patientNumber}&sessionId={$sessionId}",
        'POST',
        $claimData,
        $conn
    );
    
    if ($response['success']) {
        // Update invoice record
        $smartClaimCode = $claimData['claim_code'] ?? '';
        $smartInvoiceNumber = $claimData['visit_number'] ?? '';
        
        $updateInvoice = $conn->prepare("
            UPDATE invoices 
            SET smart_claim_code = ?, smart_invoice_number = ?,
                smart_uploaded = 1, smart_upload_date = NOW(),
                smart_claim_status = 'Pending'
            WHERE invoice_id = ?
        ");
        $updateInvoice->bind_param("ssi", $smartClaimCode, $smartInvoiceNumber, $invoice_id);
        $updateInvoice->execute();
        
        echo json_encode([
            'success' => true,
            'message' => 'Claim uploaded successfully to Smart'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to upload claim'
        ]);
    }
}

/**
 * Build Claim Data for Smart API
 */
function buildClaimData($conn, $invoice_id, $visit_id) {
    // Get invoice details
    $stmt = $conn->prepare("
        SELECT i.*, p.full_name as patient_name, p.patient_number,
               pi.member_number, pi.policy_number,
               ic.company_name, ic.smart_medical_aid_code,
               v.visit_date, v.visit_number,
               d.full_name as doctor_name,
               ss.smart_session_id, ss.smart_patient_number
        FROM invoices i
        JOIN patients p ON i.patient_id = p.patient_id
        LEFT JOIN patient_insurance pi ON p.patient_id = pi.patient_id
        LEFT JOIN insurance_companies ic ON pi.insurance_id = ic.insurance_id
        LEFT JOIN visits v ON i.visit_id = v.visit_id
        LEFT JOIN users d ON v.doctor_id = d.user_id
        LEFT JOIN smart_sessions ss ON v.smart_session_id = ss.id
        WHERE i.invoice_id = ?
    ");
    $stmt->bind_param("i", $invoice_id);
    $stmt->execute();
    $invoice = $stmt->get_result()->fetch_assoc();
    
    if (!$invoice) return null;
    
    // Get invoice items
    $itemsStmt = $conn->prepare("
        SELECT ii.*, s.service_name, s.service_code, sg.group_name
        FROM invoice_items ii
        JOIN services s ON ii.service_id = s.service_id
        LEFT JOIN service_groups sg ON s.group_id = sg.group_id
        WHERE ii.invoice_id = ?
    ");
    $itemsStmt->bind_param("i", $invoice_id);
    $itemsStmt->execute();
    $items = $itemsStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Get diagnoses
    $diagnosisStmt = $conn->prepare("
        SELECT d.diagnosis_code, d.diagnosis_name
        FROM visit_diagnoses vd
        JOIN diagnoses d ON vd.diagnosis_id = d.diagnosis_id
        WHERE vd.visit_id = ?
    ");
    $diagnosisStmt->bind_param("i", $visit_id);
    $diagnosisStmt->execute();
    $diagnoses = $diagnosisStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Get pre-authorization if exists
    $preauthStmt = $conn->prepare("
        SELECT preauth_request_code, approved_amount
        FROM smart_preauth
        WHERE visit_id = ? AND preauth_status IN ('APPROVED', 'PARTIAL')
        ORDER BY created_at DESC LIMIT 1
    ");
    $preauthStmt->bind_param("i", $visit_id);
    $preauthStmt->execute();
    $preauth = $preauthStmt->get_result()->fetch_assoc();
    
    // Get copay information
    $copayStmt = $conn->prepare("
        SELECT * FROM smart_copay_rules
        WHERE session_id = (
            SELECT id FROM smart_sessions WHERE smart_session_id = ?
        )
        ORDER BY created_at DESC LIMIT 1
    ");
    $copayStmt->bind_param("s", $invoice['smart_session_id']);
    $copayStmt->execute();
    $copay = $copayStmt->get_result()->fetch_assoc();
    
    // Build diagnosis array
    $diagnosisArray = [];
    foreach ($diagnoses as $diag) {
        $diagnosisArray[] = [
            'code' => $diag['diagnosis_code'],
            'coding_standard' => 'ICD10',
            'is_added_with_claim' => true,
            'name' => $diag['diagnosis_name'],
            'is_primary' => true
        ];
    }
    
    // Build invoice lines
    $invoiceLines = [];
    foreach ($items as $item) {
        $invoiceLines[] = [
            'additional_info' => $item['notes'] ?? '',
            'amount' => floatval($item['total_amount']),
            'charge_date' => date('Y-m-d', strtotime($invoice['created_at'])),
            'charge_time' => date('H:i', strtotime($invoice['created_at'])),
            'item_code' => $item['service_code'],
            'item_name' => $item['service_name'],
            'pre_authorization_code' => $preauth['preauth_request_code'] ?? '',
            'quantity' => intval($item['quantity']),
            'service_group' => $item['group_name'] ?? 'GENERAL',
            'unit_price' => floatval($item['unit_price'])
        ];
    }
    
    // Build payment modifiers
    $paymentModifiers = [];
    
    // Add copay if exists
    if ($copay) {
        $copayType = $copay['copay_type'] == 'PERCENTAGE' ? '2' : '1';
        $paymentModifiers[] = [
            'type' => $copayType,
            'amount' => floatval($copay['amount']),
            'reference_number' => $copay['receipt_number'] ?? ''
        ];
    }
    
    // Check for cash amount (over limit)
    if ($invoice['cash_amount'] > 0) {
        $paymentModifiers[] = [
            'type' => '0',
            'amount' => floatval($invoice['cash_amount']),
            'reference_number' => $invoice['invoice_number']
        ];
    }
    
    // Build pre-authorization array
    $preAuthArray = [];
    if ($preauth) {
        $preAuthArray[] = [
            'code' => $preauth['preauth_request_code'],
            'amount' => floatval($preauth['approved_amount']),
            'authorized_by' => 'Smart System',
            'message' => 'Authorized up to ' . $preauth['approved_amount']
        ];
    }
    
    // Build main claim data
    $claimData = [
        'claim_code' => $invoice['invoice_number'] . '_' . time(),
        'payer_code' => $invoice['smart_medical_aid_code'] ?? '',
        'payer_name' => $invoice['company_name'] ?? '',
        'medicalaid_code' => $invoice['smart_medical_aid_code'] ?? '',
        'amount' => floatval($invoice['insurance_amount']),
        'gross_amount' => floatval($invoice['total_amount']),
        'batch_number' => date('Ymd') . '_' . $invoice_id,
        'dispatch_date' => date('Y-m-d H:i:s'),
        'patient_number' => $invoice['smart_patient_number'] ?? $invoice['patient_number'],
        'patient_name' => $invoice['patient_name'],
        'location_code' => '1',
        'location_name' => 'ENT CLINIC',
        'scheme_code' => $invoice['smart_medical_aid_code'] ?? '',
        'scheme_name' => $invoice['company_name'] ?? '',
        'member_number' => $invoice['member_number'] ?? '',
        'visit_number' => $invoice['visit_number'],
        'visit_start' => date('Y-m-d H:i:s', strtotime($invoice['visit_date'])),
        'visit_end' => date('Y-m-d H:i:s'),
        'currency' => 'KES',
        'doctor_name' => $invoice['doctor_name'] ?? 'ENT Specialist',
        'sp_id' => 569, // Your provider SP ID
        'session_id' => intval($invoice['smart_session_id']),
        'diagnosis' => $diagnosisArray,
        'pre_authorization' => $preAuthArray,
        'admission' => [
            'additional_info' => '',
            'admission_date' => date('Y-m-d H:i:s', strtotime($invoice['visit_date'])),
            'admission_number' => $invoice['visit_number'],
            'discharge_summary' => ''
        ],
        'invoices' => [
            [
                'amount' => floatval($invoice['insurance_amount']),
                'gross_amount' => floatval($invoice['total_amount']),
                'invoice_date' => date('Y-m-d H:i:s', strtotime($invoice['created_at'])),
                'invoice_number' => $invoice['invoice_number'],
                'invoice_ref_number' => $invoice['invoice_number'],
                'lines' => $invoiceLines,
                'payment_modifiers' => $paymentModifiers,
                'pool_number' => '1',
                'service_type' => 'Outpatient'
            ]
        ]
    ];
    
    return $claimData;
}

/**
 * Check Claim Status
 */
function checkClaimStatus($conn) {
    $visit_number = $_POST['visit_number'] ?? '';
    $invoice_number = $_POST['invoice_number'] ?? '';
    
    if (!$visit_number) {
        echo json_encode(['success' => false, 'message' => 'Missing visit number']);
        return;
    }
    
    $endpoint = "/api/claim-status?visitNumber={$visit_number}";
    if ($invoice_number) {
        $endpoint .= "&invoiceNumber={$invoice_number}";
    }
    
    // Call Smart API
    $response = makeSmartAPIRequest($endpoint, 'GET', null, $conn);
    
    if ($response['success']) {
        $statusData = $response['data'];
        $claimStatus = $statusData['claim_status'] ?? 'Pending';
        
        // Update local invoice status
        if ($invoice_number) {
            $updateStmt = $conn->prepare("
                UPDATE invoices 
                SET smart_claim_status = ?
                WHERE smart_invoice_number = ?
            ");
            $updateStmt->bind_param("ss", $claimStatus, $invoice_number);
            $updateStmt->execute();
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Claim status retrieved',
            'status' => $claimStatus,
            'data' => $statusData
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to check claim status'
        ]);
    }
}

/**
 * Close Smart Session
 */
function closeSession($conn) {
    $smart_session_id = $_POST['smart_session_id'] ?? '';
    
    if (!$smart_session_id) {
        echo json_encode(['success' => false, 'message' => 'Missing session ID']);
        return;
    }
    
    // Call Smart API
    $response = makeSmartAPIRequest(
        "/api/visit/{$smart_session_id}/close-session",
        'PUT',
        null,
        $conn
    );
    
    if ($response['success']) {
        // Update local session
        $updateStmt = $conn->prepare("
            UPDATE smart_sessions 
            SET session_status = 'CLOSED', updated_at = NOW()
            WHERE smart_session_id = ?
        ");
        $updateStmt->bind_param("s", $smart_session_id);
        $updateStmt->execute();
        
        echo json_encode([
            'success' => true,
            'message' => 'Session closed successfully'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => $response['data']['message'] ?? 'Failed to close session'
        ]);
    }
}
?>