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

include '../layouts/dbconn.php';
include '../includes/accounting_posting.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();
}

$payment_id = isset($_POST['payment_id']) ? intval($_POST['payment_id']) : 0;
$invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;

if ($payment_id == 0 || $invoice_id == 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid payment or invoice ID']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    accEnsureReconciliationAccounts($conn);
    // Get payment details
    $payment_query = "SELECT p.*, i.invoice_number 
                     FROM payments p
                     JOIN invoices i ON p.invoice_id = i.invoice_id
                     WHERE p.payment_id = $payment_id AND p.status = 'COMPLETED'";
    $payment_result = mysqli_query($conn, $payment_query);
    
    if (mysqli_num_rows($payment_result) == 0) {
        throw new Exception("Payment not found or already processed");
    }
    
    $payment = mysqli_fetch_assoc($payment_result);
    
    // Get invoice details
    $invoice_query = "SELECT * FROM invoices WHERE invoice_id = $invoice_id";
    $invoice_result = mysqli_query($conn, $invoice_query);
    
    if (mysqli_num_rows($invoice_result) == 0) {
        throw new Exception("Invoice not found");
    }
    
    $invoice = mysqli_fetch_assoc($invoice_result);
    
    // Check if payment amount is not greater than invoice balance
    if ($payment['amount'] > $invoice['balance']) {
        throw new Exception("Payment amount exceeds invoice balance");
    }
    
    // Update invoice with payment
    $new_amount_paid = $invoice['amount_paid'] + $payment['amount'];
    $new_balance = $invoice['total_amount'] - $new_amount_paid;
    
    $new_status = 'PARTIAL';
    if ($new_balance <= 0) {
        $new_status = 'PAID';
        $new_balance = 0;
    }
    
    $update_invoice = "UPDATE invoices 
                      SET amount_paid = $new_amount_paid,
                          balance = $new_balance,
                          status = '$new_status',
                          updated_at = NOW()
                      WHERE invoice_id = $invoice_id";
    
    if (!mysqli_query($conn, $update_invoice)) {
        throw new Exception("Failed to update invoice");
    }
    
    // Log activity
    $log_query = "INSERT INTO activity_logs 
                 (user_id, action, entity_type, entity_id, description, ip_address)
                 VALUES 
                 ({$_SESSION['user_id']}, 'RECONCILE', 'INVOICE', $invoice_id, 
                  'Reconciled payment {$payment['payment_number']} (KES {$payment['amount']}) with invoice {$invoice['invoice_number']}', 
                  '{$_SERVER['REMOTE_ADDR']}')";
    mysqli_query($conn, $log_query);
    
    mysqli_commit($conn);
    
    echo json_encode([
        'success' => true,
        'message' => 'Payment successfully reconciled with invoice',
        'new_balance' => $new_balance,
        'new_status' => $new_status
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);
?>