<?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'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions - only administrators can reverse payments']);
    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;
$reversal_reason = isset($_POST['reversal_reason']) ? mysqli_real_escape_string($conn, $_POST['reversal_reason']) : '';
$reversal_notes = isset($_POST['reversal_notes']) ? mysqli_real_escape_string($conn, $_POST['reversal_notes']) : '';

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

if (empty($reversal_reason) || empty($reversal_notes)) {
    echo json_encode(['success' => false, 'message' => 'Reversal reason and notes are required']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    // Get payment details
    $payment_query = "SELECT p.*, i.invoice_id, 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 reversed");
    }
    
    $payment = mysqli_fetch_assoc($payment_result);
    $reversal_amount = $payment['amount'];
    $invoice_id = $payment['invoice_id'];
    
    // Update payment status to REVERSED
    $update_payment = "UPDATE payments 
                      SET status = 'REVERSED',
                          notes = CONCAT(COALESCE(notes, ''), '\n\nREVERSED: $reversal_reason - $reversal_notes\nReversed by: {$_SESSION['full_name']}\nReversed on: " . date('Y-m-d H:i:s') . "'),
                          updated_at = NOW()
                      WHERE payment_id = $payment_id";
    
    if (!mysqli_query($conn, $update_payment)) {
        throw new Exception("Failed to reverse payment");
    }
    
    // Update invoice amounts
    $update_invoice = "UPDATE invoices 
                      SET amount_paid = GREATEST(0, amount_paid - $reversal_amount),
                          balance = LEAST(total_amount, balance + $reversal_amount),
                          status = CASE 
                              WHEN (amount_paid - $reversal_amount) <= 0 THEN 'PENDING'
                              WHEN (amount_paid - $reversal_amount) < total_amount THEN 'PARTIAL'
                              ELSE status
                          END,
                          updated_at = NOW()
                      WHERE invoice_id = $invoice_id";
    
    if (!mysqli_query($conn, $update_invoice)) {
        throw new Exception("Failed to update invoice");
    }
    
    // Create reversal journal entry
    $account_query = "SELECT account_id FROM chart_of_accounts 
                     WHERE account_code = '1010' LIMIT 1"; // Cash account
    $account_result = mysqli_query($conn, $account_query);
    $cash_account = mysqli_fetch_assoc($account_result);
    
    $receivable_query = "SELECT account_id FROM chart_of_accounts 
                        WHERE account_code = '1200' LIMIT 1"; // Accounts Receivable
    $receivable_result = mysqli_query($conn, $receivable_query);
    $receivable_account = mysqli_fetch_assoc($receivable_result);
    
    if ($cash_account && $receivable_account) {
        // Generate journal number
        $journal_prefix = "JE-" . date('Y') . "-";
        $journal_number = $journal_prefix . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);
        
        // Create journal entry
        $journal_insert = "INSERT INTO journal_entries 
                          (journal_number, entry_date, entry_type, reference_type, reference_id, description, created_by)
                          VALUES 
                          ('$journal_number', CURDATE(), 'AUTO_PAYMENT', 'REVERSAL', $payment_id, 
                           'Payment reversal for {$payment['payment_number']} - $reversal_reason', {$_SESSION['user_id']})";
        
        if (!mysqli_query($conn, $journal_insert)) {
            throw new Exception("Failed to create journal entry");
        }
        
        $journal_id = mysqli_insert_id($conn);
        
        // Debit: Accounts Receivable (increases debt)
        $debit_entry = "INSERT INTO journal_entry_lines 
                       (journal_id, account_id, debit_amount, credit_amount, description)
                       VALUES 
                       ($journal_id, {$receivable_account['account_id']}, $reversal_amount, 0, 
                        'Payment reversal - Invoice {$payment['invoice_number']}')";
        mysqli_query($conn, $debit_entry);
        
        // Credit: Cash (decreases)
        $credit_entry = "INSERT INTO journal_entry_lines 
                        (journal_id, account_id, debit_amount, credit_amount, description)
                        VALUES 
                        ($journal_id, {$cash_account['account_id']}, 0, $reversal_amount, 
                         'Payment reversal - {$payment['payment_number']}')";
        mysqli_query($conn, $credit_entry);
        
        // Post the journal entry
        mysqli_query($conn, "UPDATE journal_entries SET status = 'POSTED', posted_at = NOW() WHERE journal_id = $journal_id");
    }
    
    // Log activity
    $log_query = "INSERT INTO activity_logs 
                 (user_id, action, entity_type, entity_id, description, ip_address)
                 VALUES 
                 ({$_SESSION['user_id']}, 'REVERSE', 'PAYMENT', $payment_id, 
                  'Reversed payment: KES " . number_format($reversal_amount, 2) . " - Reason: $reversal_reason', 
                  '{$_SERVER['REMOTE_ADDR']}')";
    mysqli_query($conn, $log_query);
    
    mysqli_commit($conn);
    
    echo json_encode([
        'success' => true,
        'message' => 'Payment successfully reversed',
        'reversal_amount' => $reversal_amount,
        'payment_number' => $payment['payment_number']
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);
?>