<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Add Charge to Folio - 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/folio/
$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/folio/ -> /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 has_permission function if it doesn't exist
if (!function_exists('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// 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 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 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, $new_values) {
        // 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 generate_transaction_code function if it doesn't exist
if (!function_exists('generate_transaction_code')) {
    function generate_transaction_code() {
        return 'TXN' . date('Ymd') . rand(1000, 9999);
    }
}

// Define create_notification function if it doesn't exist
if (!function_exists('create_notification')) {
    function create_notification($user_id, $type, $title, $message, $link) {
        if (function_exists('db_insert')) {
            try {
                db_insert('notifications', [
                    'user_id' => $user_id,
                    'type' => $type,
                    'title' => $title,
                    'message' => $message,
                    'link' => $link,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            } catch (Exception $e) {
                error_log("Failed to create notification: " . $e->getMessage());
            }
        }
    }
}

// Define NOTIFICATION constants if not defined
if (!defined('NOTIFICATION_SUCCESS')) {
    define('NOTIFICATION_SUCCESS', 'success');
}
if (!defined('NOTIFICATION_INFO')) {
    define('NOTIFICATION_INFO', 'info');
}
if (!defined('AUDIT_CREATE')) {
    define('AUDIT_CREATE', 'create');
}

// Define CURRENCY_SYMBOL if not defined
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('reservations.folio');
}

// Set page title
$page_title = 'Add Folio Charge';

// 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 reservation ID from URL
$reservation_id = isset($_GET['reservation_id']) ? (int)$_GET['reservation_id'] : 0;

if (!$reservation_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid reservation ID');
    }
    if (function_exists('redirect')) {
        redirect('../reservations/index.php');
    } else {
        header('Location: ../reservations/index.php');
        exit;
    }
}

// Get reservation and guest information
$reservation = [];
if (function_exists('db_fetch_one')) {
    try {
        $reservation = db_fetch_one("
            SELECT 
                r.*,
                g.guest_id, g.first_name, g.last_name,
                rt.type_name,
                rm.room_number
            FROM reservations r
            JOIN guests g ON r.guest_id = g.guest_id
            JOIN room_types rt ON r.room_type_id = rt.room_type_id
            LEFT JOIN rooms rm ON r.room_id = rm.room_id
            WHERE r.reservation_id = ?
        ", [$reservation_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching reservation: " . $e->getMessage());
    }
}

if (empty($reservation)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Reservation not found');
    }
    if (function_exists('redirect')) {
        redirect('../reservations/index.php');
    } else {
        header('Location: ../reservations/index.php');
        exit;
    }
}

// Get current balance
$balance = 0;
if (function_exists('db_fetch_value')) {
    try {
        $balance = (float)db_fetch_value("
            SELECT COALESCE(SUM(CASE WHEN charge_type = 'payment' THEN -amount ELSE amount END), 0)
            FROM folio_charges
            WHERE reservation_id = ? AND (is_voided IS NULL OR is_voided = 0)
        ", [$reservation_id]) ?: 0;
    } catch (Exception $e) {
        error_log("Error fetching balance: " . $e->getMessage());
    }
}

// Get POS products for F&B charges
$products = [];
if (function_exists('db_fetch_all')) {
    try {
        $products = db_fetch_all("
            SELECT p.*, c.category_name
            FROM pos_products p
            JOIN pos_categories c ON p.category_id = c.category_id
            WHERE p.is_active = 1
            ORDER BY c.category_name, p.product_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching products: " . $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());
    }
}

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

// Handle form submission
$errors = [];

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 {
        $charge_type = isset($_POST['charge_type']) ? sanitize_input($_POST['charge_type']) : '';
        $description = isset($_POST['description']) ? sanitize_input($_POST['description']) : '';
        $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
        $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;
        $product_id = !empty($_POST['product_id']) ? (int)$_POST['product_id'] : null;
        $outlet_id = !empty($_POST['outlet_id']) ? (int)$_POST['outlet_id'] : null;
        $payment_method_id = !empty($_POST['payment_method_id']) ? (int)$_POST['payment_method_id'] : null;
        $reference = isset($_POST['reference']) ? sanitize_input($_POST['reference']) : '';
        
        // Validate required fields
        if (empty($charge_type)) {
            $errors[] = 'Charge type is required';
        }
        
        if (empty($description)) {
            $errors[] = 'Description is required';
        }
        
        if ($amount <= 0) {
            $errors[] = 'Amount must be greater than 0';
        }
        
        if ($charge_type == 'payment' && !$payment_method_id) {
            $errors[] = 'Payment method is required for payments';
        }
        
        // Add charge
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $transaction_code = function_exists('generate_transaction_code') ? generate_transaction_code() : 'TXN' . date('Ymd') . rand(1000, 9999);
                
                $charge_data = [
                    'reservation_id' => $reservation_id,
                    'transaction_code' => $transaction_code,
                    'charge_type' => $charge_type,
                    'description' => $description,
                    'quantity' => $quantity,
                    'unit_price' => $amount / $quantity,
                    'amount' => $amount,
                    'product_id' => $product_id,
                    'pos_outlet_id' => $outlet_id,
                    'posted_by' => $user_id,
                    'posted_at' => date('Y-m-d H:i:s')
                ];
                
                // If it's a payment, add payment method and reference
                if ($charge_type == 'payment') {
                    $charge_data['payment_method_id'] = $payment_method_id;
                    if ($reference) {
                        $charge_data['reference'] = $reference;
                    }
                }
                
                $charge_id = null;
                if (function_exists('db_insert')) {
                    $charge_id = db_insert('folio_charges', $charge_data);
                }
                
                // Update reservation paid amount if payment
                if ($charge_type == 'payment' && $charge_id) {
                    $new_paid = ($reservation['paid_amount'] ?? 0) + $amount;
                    $payment_status = $new_paid >= ($reservation['total_amount'] ?? 0) ? 'paid' : 'partial';
                    
                    if (function_exists('db_update')) {
                        db_update('reservations', [
                            'paid_amount' => $new_paid,
                            'payment_status' => $payment_status
                        ], 'reservation_id = ?', [$reservation_id]);
                    }
                }
                
                // Create notification
                if (function_exists('create_notification')) {
                    create_notification(
                        $reservation['guest_id'] ?? 0,
                        $charge_type == 'payment' ? NOTIFICATION_SUCCESS : NOTIFICATION_INFO,
                        $charge_type == 'payment' ? 'Payment Received' : 'Charge Added',
                        "$description: " . format_currency($amount),
                        '../folio/view.php?reservation_id=' . $reservation_id
                    );
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, AUDIT_CREATE, 'folio_charges', $charge_id, null, $charge_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', ucfirst($charge_type) . ' added successfully');
                }
                
                if (function_exists('redirect')) {
                    redirect('view.php?reservation_id=' . $reservation_id);
                } else {
                    header('Location: view.php?reservation_id=' . $reservation_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to add charge: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Add charge failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// Determine default charge type from URL
$default_type = $_GET['type'] ?? 'charge';

// 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>Add Folio Charge</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; }
            .badge-lg { font-size: 1.1rem; padding: 0.5rem 1rem; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-4 { margin-top: 1.5rem; }
            .text-end { text-align: right; }
        </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="#">Add Folio Charge</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">Add Folio Charge</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/reservations/dashboard.php">Reservations</a></li>
                    <li class="breadcrumb-item"><a href="../reservations/view.php?id=<?php echo $reservation_id; ?>">Reservation</a></li>
                    <li class="breadcrumb-item"><a href="view.php?reservation_id=<?php echo $reservation_id; ?>">Folio</a></li>
                    <li class="breadcrumb-item active">Add Charge</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">
                <!-- Reservation Summary -->
                <div class="card card-outline card-info">
                    <div class="card-header">
                        <h3 class="card-title">Reservation Summary</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-sm-4">
                                <strong>Guest:</strong><br>
                                <?php echo escape_html(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?>
                            </div>
                            <div class="col-sm-4">
                                <strong>Room:</strong><br>
                                <?php echo $reservation['room_number'] ?: 'Not assigned'; ?>
                            </div>
                            <div class="col-sm-4">
                                <strong>Booking Code:</strong><br>
                                <?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?>
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-sm-4">
                                <strong>Check-in:</strong><br>
                                <?php echo isset($reservation['check_in_date']) ? date('M d, Y', strtotime($reservation['check_in_date'])) : 'N/A'; ?>
                            </div>
                            <div class="col-sm-4">
                                <strong>Check-out:</strong><br>
                                <?php echo isset($reservation['check_out_date']) ? date('M d, Y', strtotime($reservation['check_out_date'])) : 'N/A'; ?>
                            </div>
                            <div class="col-sm-4">
                                <strong>Current Balance:</strong><br>
                                <span class="badge bg-<?php echo $balance > 0 ? 'warning' : ($balance < 0 ? 'info' : 'success'); ?> badge-lg">
                                    <?php echo format_currency($balance); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Add Charge Form -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-plus-circle me-1"></i>
                            Add New Transaction
                        </h3>
                    </div>
                    
                    <form method="POST" id="addChargeForm">
                        <?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; ?>
                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                        
                        <div class="card-body">
                            <!-- Charge Type Selection -->
                            <div class="form-group mb-3">
                                <label for="charge_type">Transaction Type</label>
                                <select class="form-select" id="charge_type" name="charge_type" required>
                                    <optgroup label="Charges">
                                        <option value="room" <?php echo $default_type == 'room' ? 'selected' : ''; ?>>Room Charge</option>
                                        <option value="fnb" <?php echo $default_type == 'fnb' ? 'selected' : ''; ?>>Food & Beverage</option>
                                        <option value="service" <?php echo $default_type == 'service' ? 'selected' : ''; ?>>Service Charge</option>
                                        <option value="other" <?php echo $default_type == 'other' ? 'selected' : ''; ?>>Other Charge</option>
                                        <option value="adjustment" <?php echo $default_type == 'adjustment' ? 'selected' : ''; ?>>Adjustment</option>
                                    </optgroup>
                                    <optgroup label="Payments">
                                        <option value="payment" <?php echo $default_type == 'payment' ? 'selected' : ''; ?>>Payment</option>
                                    </optgroup>
                                </select>
                            </div>

                            <!-- Product Selection (for F&B) -->
                            <div class="form-group mb-3" id="product_group" style="display: none;">
                                <label for="product_id">Select Product</label>
                                <select class="form-select select2" id="product_id" name="product_id">
                                    <option value="">Manual Entry</option>
                                    <?php foreach ($products as $product): ?>
                                        <option value="<?php echo $product['product_id'] ?? 0; ?>" 
                                                data-price="<?php echo $product['unit_price'] ?? 0; ?>">
                                            <?php echo escape_html($product['product_name'] ?? ''); ?> 
                                            (<?php echo format_currency($product['unit_price'] ?? 0); ?>) - <?php echo $product['category_name'] ?? ''; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <!-- Description -->
                            <div class="form-group mb-3">
                                <label for="description">Description <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="description" name="description" 
                                       placeholder="e.g., Mini Bar, Spa Treatment, Room Service" required>
                            </div>

                            <!-- Quantity and Amount -->
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="quantity">Quantity</label>
                                        <input type="number" class="form-control" id="quantity" name="quantity" value="1" min="1">
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="unit_price">Unit Price</label>
                                        <div class="input-group">
                                            <span class="input-group-text">RWF</span>
                                            <input type="number" class="form-control" id="unit_price" step="0.01" min="0">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="amount">Total Amount <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text">RWF</span>
                                            <input type="number" class="form-control" id="amount" name="amount" 
                                                   step="0.01" min="0" required>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Outlet (for F&B) -->
                            <div class="form-group mb-3" id="outlet_group" style="display: none;">
                                <label for="outlet_id">Outlet</label>
                                <select class="form-select" id="outlet_id" name="outlet_id">
                                    <option value="">Select Outlet</option>
                                    <?php foreach ($outlets as $outlet): ?>
                                        <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>">
                                            <?php echo escape_html($outlet['outlet_name'] ?? ''); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <!-- Payment Method (for payments) -->
                            <div class="form-group mb-3" id="payment_group" style="display: none;">
                                <label for="payment_method_id">Payment Method</label>
                                <select class="form-select" id="payment_method_id" name="payment_method_id">
                                    <option value="">Select Payment Method</option>
                                    <?php foreach ($payment_methods as $method): ?>
                                        <option value="<?php echo $method['payment_method_id'] ?? 0; ?>">
                                            <?php echo escape_html($method['method_name'] ?? ''); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <!-- Reference (for payments) -->
                            <div class="form-group mb-3" id="reference_group" style="display: none;">
                                <label for="reference">Reference Number</label>
                                <input type="text" class="form-control" id="reference" name="reference" 
                                       placeholder="Transaction ID, Check #, etc.">
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i> Add Transaction
                            </button>
                            <a href="view.php?reservation_id=<?php echo $reservation_id; ?>" 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%'
        });
    }
    
    // Handle charge type change
    $('#charge_type').on('change', function() {
        const type = $(this).val();
        
        // Hide all conditional groups
        $('#product_group, #outlet_group, #payment_group, #reference_group').hide();
        
        // Show relevant groups
        if (type === 'fnb') {
            $('#product_group, #outlet_group').show();
        } else if (type === 'payment') {
            $('#payment_group, #reference_group').show();
        }
        
        // Update description placeholder
        updateDescriptionPlaceholder(type);
    });
    
    // Trigger initial change
    $('#charge_type').trigger('change');
    
    // Handle product selection
    $('#product_id').on('change', function() {
        const selected = $(this).find(':selected');
        const price = selected.data('price');
        
        if (price) {
            $('#unit_price').val(price);
            calculateTotal();
            $('#description').val(selected.text().split(' (')[0]);
        }
    });
    
    // Calculate total on quantity or unit price change
    $('#quantity, #unit_price').on('input', calculateTotal);
    
    function calculateTotal() {
        const qty = parseFloat($('#quantity').val()) || 1;
        const price = parseFloat($('#unit_price').val()) || 0;
        const total = qty * price;
        $('#amount').val(total.toFixed(2));
    }
    
    function updateDescriptionPlaceholder(type) {
        let placeholder = '';
        switch(type) {
            case 'room':
                placeholder = 'e.g., Room Service, Mini Bar';
                break;
            case 'fnb':
                placeholder = 'e.g., Restaurant, Bar';
                break;
            case 'service':
                placeholder = 'e.g., Spa, Laundry, Activities';
                break;
            case 'payment':
                placeholder = 'e.g., Cash Payment, Card Payment';
                break;
            case 'adjustment':
                placeholder = 'e.g., Discount, Correction';
                break;
            default:
                placeholder = 'Description of charge';
        }
        $('#description').attr('placeholder', placeholder);
    }
});

// Form validation
$('#addChargeForm').on('submit', function(e) {
    const type = $('#charge_type').val();
    const amount = parseFloat($('#amount').val());
    const description = $('#description').val();
    
    if (!description) {
        e.preventDefault();
        alert('Please enter a description');
        return false;
    }
    
    if (amount <= 0) {
        e.preventDefault();
        alert('Amount must be greater than 0');
        return false;
    }
    
    if (type === 'payment') {
        const method = $('#payment_method_id').val();
        if (!method) {
            e.preventDefault();
            alert('Please select a payment method');
            return false;
        }
    }
    
    return true;
});
</script>

<style>
.badge-lg {
    font-size: 1.1rem;
    padding: 0.5rem 1rem;
}
</style>

<?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>';
}
?>