<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Record Payment - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/billing/payments/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/billing/payments/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define begin_transaction function if it doesn't exist
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $db->beginTransaction();
            }
        }
    }
}

// Define commit_transaction function if it doesn't exist
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->commit();
            }
        }
    }
}

// Define rollback_transaction function if it doesn't exist
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }
        }
    }
}

// Define audit_log function if it doesn't exist
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id, $old_values = null, $new_values = null) {
        // Simplified audit log - just log to error log
        error_log("AUDIT: User $user_id - $action on $table:$record_id");
    }
}

// Define log_message function if it doesn't exist
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        error_log("[$level] $message");
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('AUDIT_PAYMENT')) {
    define('AUDIT_PAYMENT', 'payment');
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('billing.payments.manage');
}

// Set page title
$page_title = 'Record Payment';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get invoice ID from URL if specified
$invoice_id = isset($_GET['invoice_id']) ? (int)$_GET['invoice_id'] : 0;

// Get guests for dropdown
$guests = [];
if (function_exists('db_fetch_all')) {
    try {
        $guests = db_fetch_all("
            SELECT guest_id, first_name, last_name, email 
            FROM guests 
            WHERE (is_blacklisted IS NULL OR is_blacklisted = 0)
            ORDER BY first_name, last_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching guests: " . $e->getMessage());
    }
}

// Get payment methods
$payment_methods = [];
if (function_exists('db_fetch_all')) {
    try {
        $payment_methods = db_fetch_all("SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY sort_order") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching payment methods: " . $e->getMessage());
    }
}

// If invoice specified, get invoice details
$selected_invoice = null;
if ($invoice_id && function_exists('db_fetch_one')) {
    try {
        $selected_invoice = db_fetch_one("
            SELECT i.*, g.first_name, g.last_name, g.guest_id
            FROM invoices i
            JOIN guests g ON i.guest_id = g.guest_id
            WHERE i.invoice_id = ?
        ", [$invoice_id]) ?: null;
    } catch (Exception $e) {
        error_log("Error fetching invoice: " . $e->getMessage());
    }
}

// Handle form submission
$errors = [];
$form_data = [
    'guest_id' => $selected_invoice['guest_id'] ?? 0,
    'invoice_id' => $invoice_id ?: null,
    'amount' => $selected_invoice ? (($selected_invoice['total_amount'] ?? 0) - ($selected_invoice['paid_amount'] ?? 0)) : '',
    'payment_method_id' => '',
    'reference_number' => '',
    'notes' => '',
    'payment_date' => date('Y-m-d H:i:s')
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $form_data['guest_id'] = isset($_POST['guest_id']) ? (int)$_POST['guest_id'] : 0;
        $form_data['invoice_id'] = !empty($_POST['invoice_id']) ? (int)$_POST['invoice_id'] : null;
        $form_data['amount'] = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
        $form_data['payment_method_id'] = isset($_POST['payment_method_id']) ? (int)$_POST['payment_method_id'] : 0;
        $form_data['reference_number'] = isset($_POST['reference_number']) ? sanitize_input($_POST['reference_number']) : '';
        $form_data['notes'] = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        $form_data['payment_date'] = isset($_POST['payment_date']) ? sanitize_input($_POST['payment_date']) : date('Y-m-d H:i:s');
        
        // Validate required fields
        if (!$form_data['guest_id']) {
            $errors[] = 'Please select a guest';
        }
        
        if ($form_data['amount'] <= 0) {
            $errors[] = 'Amount must be greater than 0';
        }
        
        if (!$form_data['payment_method_id']) {
            $errors[] = 'Please select a payment method';
        }
        
        // If invoice specified, validate amount doesn't exceed balance
        $invoice = null;
        if ($form_data['invoice_id'] && function_exists('db_fetch_one')) {
            try {
                $invoice = db_fetch_one("SELECT * FROM invoices WHERE invoice_id = ?", [$form_data['invoice_id']]);
            } catch (Exception $e) {
                error_log("Error fetching invoice for validation: " . $e->getMessage());
            }
            
            if ($invoice) {
                $balance = ($invoice['total_amount'] ?? 0) - ($invoice['paid_amount'] ?? 0);
                if ($form_data['amount'] > $balance) {
                    $errors[] = "Payment amount cannot exceed invoice balance of " . format_currency($balance);
                }
            }
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Generate payment number
                $payment_number = 'PAY-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                
                // Create payment
                $payment_id = null;
                if (function_exists('db_insert')) {
                    $payment_id = db_insert('payments', [
                        'payment_number' => $payment_number,
                        'invoice_id' => $form_data['invoice_id'],
                        'guest_id' => $form_data['guest_id'],
                        'payment_method_id' => $form_data['payment_method_id'],
                        'amount' => $form_data['amount'],
                        'payment_date' => $form_data['payment_date'],
                        'reference_number' => $form_data['reference_number'] ?: null,
                        'notes' => $form_data['notes'] ?: null,
                        'received_by' => $user_id,
                        'status' => 'completed',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // Update invoice if linked
                if ($form_data['invoice_id'] && $invoice && function_exists('db_update')) {
                    $new_paid = ($invoice['paid_amount'] ?? 0) + $form_data['amount'];
                    $new_status = $new_paid >= ($invoice['total_amount'] ?? 0) ? 'paid' : 'partial';
                    
                    db_update('invoices', [
                        'paid_amount' => $new_paid,
                        'status' => $new_status
                        // 'balance' field removed - this is a generated column in the database
                    ], 'invoice_id = ?', [$form_data['invoice_id']]);
                }
                
                // Create guest activity
                if (function_exists('db_insert')) {
                    db_insert('guest_activity', [
                        'guest_id' => $form_data['guest_id'],
                        'activity_type' => 'payment',
                        'description' => "Payment received: " . format_currency($form_data['amount']) . 
                                        ($form_data['invoice_id'] ? " for invoice #" . ($invoice['invoice_number'] ?? '') : ""),
                        'reference_id' => $payment_id,
                        'reference_type' => 'payment',
                        'created_by' => $user_id,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, AUDIT_PAYMENT, 'payments', $payment_id, null, $form_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Payment recorded successfully');
                }
                
                if (function_exists('redirect')) {
                    if ($form_data['invoice_id']) {
                        redirect('../invoices/view.php?id=' . $form_data['invoice_id']);
                    } else {
                        redirect('index.php');
                    }
                } else {
                    if ($form_data['invoice_id']) {
                        header('Location: ../invoices/view.php?id=' . $form_data['invoice_id']);
                    } else {
                        header('Location: index.php');
                    }
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to record payment: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Payment recording failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Record Payment</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Record Payment</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Record Payment</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/billing/dashboard.php">Billing</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Payments</a></li>
                    <li class="breadcrumb-item active">Record Payment</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Error Messages -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <strong>Please fix the following errors:</strong>
                <ul class="mt-2 mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Invoice Summary (if applicable) -->
                <?php if ($selected_invoice): ?>
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-file-invoice me-1"></i>
                            Invoice Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <strong>Invoice #:</strong><br>
                                <?php echo htmlspecialchars($selected_invoice['invoice_number'] ?? 'N/A'); ?>
                            </div>
                            <div class="col-md-4">
                                <strong>Guest:</strong><br>
                                <?php echo escape_html(($selected_invoice['first_name'] ?? '') . ' ' . ($selected_invoice['last_name'] ?? '')); ?>
                            </div>
                            <div class="col-md-4">
                                <strong>Due Date:</strong><br>
                                <?php echo isset($selected_invoice['due_date']) ? date('M d, Y', strtotime($selected_invoice['due_date'])) : 'N/A'; ?>
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-md-4">
                                <strong>Total Amount:</strong><br>
                                <?php echo format_currency($selected_invoice['total_amount'] ?? 0); ?>
                            </div>
                            <div class="col-md-4">
                                <strong>Paid Amount:</strong><br>
                                <?php echo format_currency($selected_invoice['paid_amount'] ?? 0); ?>
                            </div>
                            <div class="col-md-4">
                                <strong>Balance:</strong><br>
                                <span class="text-<?php echo (($selected_invoice['total_amount'] ?? 0) - ($selected_invoice['paid_amount'] ?? 0)) > 0 ? 'danger' : 'success'; ?>">
                                    <?php echo format_currency(($selected_invoice['total_amount'] ?? 0) - ($selected_invoice['paid_amount'] ?? 0)); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Payment Form -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-credit-card me-1"></i>
                            Payment Details
                        </h3>
                    </div>
                    
                    <form method="POST" id="paymentForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <div class="form-group mb-3">
                                <label for="guest_id">Guest <span class="text-danger">*</span></label>
                                <?php if ($selected_invoice): ?>
                                    <input type="hidden" name="guest_id" value="<?php echo $selected_invoice['guest_id'] ?? 0; ?>">
                                    <input type="text" class="form-control" 
                                           value="<?php echo escape_html(($selected_invoice['first_name'] ?? '') . ' ' . ($selected_invoice['last_name'] ?? '')); ?>" 
                                           readonly>
                                <?php else: ?>
                                    <select class="form-select select2" id="guest_id" name="guest_id" required>
                                        <option value="">Select Guest</option>
                                        <?php foreach ($guests as $guest): ?>
                                            <option value="<?php echo $guest['guest_id'] ?? 0; ?>" 
                                                    <?php echo $form_data['guest_id'] == ($guest['guest_id'] ?? 0) ? 'selected' : ''; ?>>
                                                <?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?>
                                                <?php if (!empty($guest['email'])): ?> - <?php echo htmlspecialchars($guest['email']); ?><?php endif; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php endif; ?>
                            </div>
                            
                            <?php if (!$selected_invoice): ?>
                            <div class="form-group mb-3">
                                <label for="invoice_id">Related Invoice (Optional)</label>
                                <select class="form-select select2" id="invoice_id" name="invoice_id">
                                    <option value="">No Invoice (Direct Payment)</option>
                                    <!-- Invoices will be loaded via AJAX when guest is selected -->
                                </select>
                            </div>
                            <?php else: ?>
                                <input type="hidden" name="invoice_id" value="<?php echo $invoice_id; ?>">
                            <?php endif; ?>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="amount">Amount <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                                            <input type="number" class="form-control" id="amount" name="amount" 
                                                   value="<?php echo htmlspecialchars($form_data['amount']); ?>" step="0.01" min="0" required>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="payment_method_id">Payment Method <span class="text-danger">*</span></label>
                                        <select class="form-select" id="payment_method_id" name="payment_method_id" required>
                                            <option value="">Select Method</option>
                                            <?php foreach ($payment_methods as $method): ?>
                                                <option value="<?php echo $method['payment_method_id'] ?? 0; ?>" 
                                                        <?php echo $form_data['payment_method_id'] == ($method['payment_method_id'] ?? 0) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($method['method_name'] ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="reference_number">Reference Number (Optional)</label>
                                <input type="text" class="form-control" id="reference_number" name="reference_number" 
                                       value="<?php echo escape_html($form_data['reference_number']); ?>"
                                       placeholder="Transaction ID, Check #, etc.">
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="payment_date">Payment Date & Time</label>
                                <input type="datetime-local" class="form-control" id="payment_date" name="payment_date" 
                                       value="<?php echo date('Y-m-d\TH:i', strtotime($form_data['payment_date'])); ?>">
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="notes">Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"><?php echo escape_html($form_data['notes']); ?></textarea>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-save me-1"></i> Record Payment
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
    
    <?php if (!$selected_invoice): ?>
    // Load invoices when guest is selected
    $('#guest_id').on('change', function() {
        const guestId = $(this).val();
        const $invoiceSelect = $('#invoice_id');
        
        if (guestId) {
            $.get('/HMSPOS/api/get-guest-invoices.php', { guest_id: guestId }, function(response) {
                $invoiceSelect.empty().append('<option value="">No Invoice (Direct Payment)</option>');
                
                if (response.data && response.data.length > 0) {
                    response.data.forEach(function(invoice) {
                        const balance = (invoice.total_amount || 0) - (invoice.paid_amount || 0);
                        if (balance > 0) {
                            $invoiceSelect.append(
                                $('<option>', {
                                    value: invoice.invoice_id,
                                    text: invoice.invoice_number + ' - Balance: ' + formatCurrency(balance)
                                }).data('balance', balance)
                            );
                        }
                    });
                }
                
                // Refresh Select2
                if ($.fn.select2) {
                    $invoiceSelect.trigger('change.select2');
                }
            }).fail(function() {
                console.error('Failed to load invoices');
            });
        } else {
            $invoiceSelect.empty().append('<option value="">No Invoice (Direct Payment)</option>');
        }
    });
    
    // Set amount when invoice is selected
    $('#invoice_id').on('change', function() {
        const selected = $(this).find(':selected');
        const balance = selected.data('balance');
        
        if (balance) {
            $('#amount').val(balance.toFixed(2));
        }
    });
    
    // Trigger change if guest is pre-selected
    if ($('#guest_id').val()) {
        $('#guest_id').trigger('change');
    }
    <?php endif; ?>
    
    function formatCurrency(amount) {
        return '<?php echo CURRENCY_SYMBOL; ?>' + amount.toFixed(2);
    }
});

// Form validation
$('#paymentForm').on('submit', function(e) {
    const amount = parseFloat($('#amount').val()) || 0;
    
    if (amount <= 0) {
        e.preventDefault();
        alert('Please enter a valid amount');
        return false;
    }
    
    return confirm('Record this payment?');
});
</script>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>