<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

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

// Check permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    $matched_count = 0;
    
    // Find invoices with outstanding balances
    $invoices_query = "SELECT i.invoice_id, i.invoice_number, i.balance, i.patient_id
                      FROM invoices i
                      WHERE i.balance > 0 AND i.status != 'CANCELLED'
                      ORDER BY i.invoice_date DESC";
    $invoices_result = mysqli_query($conn, $invoices_query);
    
    // Find unallocated payments
    $payments_query = "SELECT p.payment_id, p.payment_number, p.amount, p.patient_id, p.invoice_id
                      FROM payments p
                      WHERE p.status = 'COMPLETED'
                      ORDER BY p.payment_date DESC";
    $payments_result = mysqli_query($conn, $payments_query);
    
    // Create arrays for matching
    $invoices = [];
    while ($invoice = mysqli_fetch_assoc($invoices_result)) {
        $invoices[] = $invoice;
    }
    
    $payments = [];
    while ($payment = mysqli_fetch_assoc($payments_result)) {
        $payments[] = $payment;
    }
    
    // Match payments to invoices based on exact amount and same patient
    foreach ($invoices as $invoice) {
        foreach ($payments as $payment) {
            // Check if amounts match exactly and same patient
            if (abs($invoice['balance'] - $payment['amount']) < 0.01 && 
                $invoice['patient_id'] == $payment['patient_id']) {
                
                // Verify invoice still has balance
                $check_query = "SELECT balance FROM invoices WHERE invoice_id = {$invoice['invoice_id']}";
                $check_result = mysqli_query($conn, $check_query);
                $current_invoice = mysqli_fetch_assoc($check_result);
                
                if ($current_invoice['balance'] > 0) {
                    // Update invoice - add payment amount to amount_paid and recalculate balance
                    $update_invoice = "UPDATE invoices 
                                     SET amount_paid = amount_paid + {$payment['amount']},
                                         balance = total_amount - (amount_paid + {$payment['amount']}),
                                         status = CASE 
                                             WHEN (amount_paid + {$payment['amount']}) >= total_amount THEN 'PAID'
                                             WHEN (amount_paid + {$payment['amount']}) > 0 THEN 'PARTIAL'
                                             ELSE status
                                         END,
                                         updated_at = NOW()
                                     WHERE invoice_id = {$invoice['invoice_id']}";
                    
                    if (mysqli_query($conn, $update_invoice)) {
                        $matched_count++;
                        
                        // Log the reconciliation
                        $log_query = "INSERT INTO activity_logs 
                                     (user_id, action, entity_type, entity_id, description, ip_address)
                                     VALUES 
                                     ({$_SESSION['user_id']}, 'RECONCILE', 'INVOICE', {$invoice['invoice_id']}, 
                                      'Auto-reconciled payment {$payment['payment_number']} with invoice {$invoice['invoice_number']}', 
                                      '{$_SERVER['REMOTE_ADDR']}')";
                        mysqli_query($conn, $log_query);
                        
                        // Remove matched payment from array
                        $payments = array_filter($payments, function($p) use ($payment) {
                            return $p['payment_id'] != $payment['payment_id'];
                        });
                        
                        break; // Move to next invoice
                    }
                }
            }
        }
    }
    
    mysqli_commit($conn);
    
    if ($matched_count > 0) {
        echo json_encode([
            'success' => true,
            'matched' => $matched_count,
            'message' => "$matched_count payment(s) successfully reconciled"
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'matched' => 0,
            'message' => 'No exact matches found for automatic reconciliation'
        ]);
    }
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);
?>