<?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();
}

// Get form data
$payment_id = intval($_POST['payment_id']);
$refund_reason = mysqli_real_escape_string($conn, $_POST['refund_reason']);
$refund_notes = mysqli_real_escape_string($conn, $_POST['refund_notes']);
$refund_method = mysqli_real_escape_string($conn, $_POST['refund_method']);

mysqli_begin_transaction($conn);

try {
    // Get payment details
    $payment_query = "SELECT p.*, i.invoice_id, i.invoice_number, i.total_amount as invoice_total
                     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 refunded");
    }
    
    $payment = mysqli_fetch_assoc($payment_result);
    $refund_amount = $payment['amount'];
    $invoice_id = $payment['invoice_id'];
    
    // Check if payment is within refund window (90 days)
    $payment_date = new DateTime($payment['payment_date']);
    $current_date = new DateTime();
    $days_diff = $current_date->diff($payment_date)->days;
    
    if ($days_diff > 90) {
        throw new Exception("Payment is older than 90 days and cannot be refunded through this system. Please contact accounting.");
    }
    
    // Update payment status to REFUNDED
    $update_payment = "UPDATE payments 
                      SET status = 'REFUNDED',
                          notes = CONCAT(COALESCE(notes, ''), '\n\nREFUND: $refund_reason - $refund_notes'),
                          updated_at = NOW()
                      WHERE payment_id = $payment_id";
    
    if (!mysqli_query($conn, $update_payment)) {
        throw new Exception("Failed to update payment status");
    }
    
    // Update invoice amounts
    $update_invoice = "UPDATE invoices 
                      SET amount_paid = amount_paid - $refund_amount,
                          balance = total_amount - (amount_paid - $refund_amount),
                          status = CASE 
                              WHEN (amount_paid - $refund_amount) = 0 THEN 'PENDING'
                              WHEN (amount_paid - $refund_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 refund 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', 'REFUND', $payment_id, 
                           'Refund for payment {$payment['payment_number']} - $refund_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)
        $debit_entry = "INSERT INTO journal_entry_lines 
                       (journal_id, account_id, debit_amount, credit_amount, description)
                       VALUES 
                       ($journal_id, {$receivable_account['account_id']}, $refund_amount, 0, 
                        'Refund - 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, $refund_amount, 
                         'Cash refund - Payment {$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']}, 'REFUND', 'PAYMENT', $payment_id, 
                  'Processed refund: KES " . number_format($refund_amount, 2) . " - Reason: $refund_reason', 
                  '{$_SERVER['REMOTE_ADDR']}')";
    mysqli_query($conn, $log_query);
    
    mysqli_commit($conn);
    
    echo json_encode([
        'success' => true,
        'message' => 'Refund processed successfully',
        'refund_amount' => $refund_amount,
        'payment_number' => $payment['payment_number']
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);
?>