<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create New Reservation - ULTIMATE FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct path using a reliable method
// Current file: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/reservations/reservations/create.php
// We need: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/

// Method 1: Go up 3 levels from current file's directory
$base_path = dirname(__DIR__, 3); // This should work in PHP 7.0+

// Method 2: Manual calculation as fallback
if (!file_exists($base_path . '/config/init.php')) {
    // Try manual calculation
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: Absolute path as last resort
if (!file_exists($base_path . '/config/init.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Debug - remove after confirming
error_log("Create Reservation - Base path: " . $base_path);
error_log("Create Reservation - Init file: " . $base_path . '/config/init.php');

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// 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 audit constants if not defined
if (!defined('AUDIT_CREATE')) define('AUDIT_CREATE', 'create');

// Define booking sources if not defined
if (!defined('BOOKING_SOURCES')) {
    define('BOOKING_SOURCES', serialize([
        'direct' => 'Direct',
        'website' => 'Website',
        'phone' => 'Phone',
        'email' => 'Email',
        'walk_in' => 'Walk-in',
        'agent' => 'Travel Agent',
        'ota' => 'Online Travel Agency'
    ]));
}

// Define helper functions if they don't exist
if (!function_exists('generate_booking_code')) {
    function generate_booking_code() {
        return 'BK-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('generate_transaction_code')) {
    function generate_transaction_code() {
        return 'TXN-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('calculate_nights')) {
    function calculate_nights($check_in, $check_out) {
        $start = new DateTime($check_in);
        $end = new DateTime($check_out);
        return $end->diff($start)->days;
    }
}

if (!function_exists('check_room_availability')) {
    function check_room_availability($room_id, $check_in, $check_out) {
        try {
            $count = db_fetch_value("
                SELECT COUNT(*) FROM reservations 
                WHERE room_id = ? 
                AND booking_status IN ('confirmed', 'checked_in')
                AND check_in_date < ? 
                AND check_out_date > ?
            ", [$room_id, $check_out, $check_in]);
            
            return $count == 0;
        } catch (Exception $e) {
            error_log("Error checking room availability: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_booking_confirmation')) {
    function send_booking_confirmation($reservation, $guest) {
        // Placeholder - implement actual email sending later
        error_log("Booking confirmation would be sent to: " . ($guest['email'] ?? 'no email'));
        return true;
    }
}

// Set page title
$page_title = 'New Reservation';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

// Get room types for dropdown
$room_types = [];
try {
    $room_types = db_fetch_all("SELECT * FROM room_types ORDER BY type_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
}

// Get rate plans
$rate_plans = [];
try {
    $rate_plans = db_fetch_all("
        SELECT rp.*, rt.type_name 
        FROM rate_plans rp
        JOIN room_types rt ON rp.room_type_id = rt.room_type_id
        WHERE rp.is_active = 1
        ORDER BY rt.type_name, rp.base_rate
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching rate plans: " . $e->getMessage());
}

// Initialize form data
$form_data = [
    'guest_id' => isset($_GET['guest_id']) ? (int)$_GET['guest_id'] : 0,
    'room_type_id' => isset($_GET['room_type_id']) ? (int)$_GET['room_type_id'] : 0,
    'room_id' => isset($_GET['room_id']) ? (int)$_GET['room_id'] : 0,
    'rate_plan_id' => 0,
    'check_in_date' => $_GET['check_in'] ?? date('Y-m-d'),
    'check_out_date' => $_GET['check_out'] ?? date('Y-m-d', strtotime('+1 day')),
    'adults' => 2,
    'children' => 0,
    'booking_source' => 'direct',
    'special_requests' => '',
    'total_amount' => 0,
    'paid_amount' => 0
];

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $errors[] = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        // Get form data
        $form_data['guest_id'] = (int)($_POST['guest_id'] ?? 0);
        $form_data['room_type_id'] = (int)($_POST['room_type_id'] ?? 0);
        $form_data['room_id'] = !empty($_POST['room_id']) ? (int)$_POST['room_id'] : null;
        $form_data['rate_plan_id'] = !empty($_POST['rate_plan_id']) ? (int)$_POST['rate_plan_id'] : null;
        $form_data['check_in_date'] = $_POST['check_in_date'] ?? '';
        $form_data['check_out_date'] = $_POST['check_out_date'] ?? '';
        $form_data['adults'] = (int)($_POST['adults'] ?? 2);
        $form_data['children'] = (int)($_POST['children'] ?? 0);
        $form_data['booking_source'] = $_POST['booking_source'] ?? 'direct';
        $form_data['special_requests'] = $_POST['special_requests'] ?? '';
        $form_data['total_amount'] = (float)($_POST['total_amount'] ?? 0);
        $form_data['paid_amount'] = (float)($_POST['paid_amount'] ?? 0);
        
        $send_confirmation = isset($_POST['send_confirmation']);
        
        // Validate required fields
        if (!$form_data['guest_id']) {
            $errors[] = 'Please select a guest';
        }
        
        if (!$form_data['room_type_id']) {
            $errors[] = 'Please select a room type';
        }
        
        if (empty($form_data['check_in_date'])) {
            $errors[] = 'Check-in date is required';
        }
        
        if (empty($form_data['check_out_date'])) {
            $errors[] = 'Check-out date is required';
        }
        
        if ($form_data['check_in_date'] >= $form_data['check_out_date']) {
            $errors[] = 'Check-out date must be after check-in date';
        }
        
        if ($form_data['adults'] < 1) {
            $errors[] = 'At least 1 adult is required';
        }
        
        if ($form_data['total_amount'] <= 0) {
            $errors[] = 'Total amount must be greater than 0';
        }
        
        // Check room availability if room selected
        if ($form_data['room_id']) {
            $available = check_room_availability(
                $form_data['room_id'],
                $form_data['check_in_date'],
                $form_data['check_out_date']
            );
            
            if (!$available) {
                $errors[] = 'Selected room is not available for these dates';
            }
        }
        
        // Create reservation
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Generate booking code
                $booking_code = generate_booking_code();
                
                // Calculate nights
                $nights = calculate_nights($form_data['check_in_date'], $form_data['check_out_date']);
                
                // Insert reservation
                $reservation_data = [
                    'booking_code' => $booking_code,
                    'guest_id' => $form_data['guest_id'],
                    'room_type_id' => $form_data['room_type_id'],
                    'room_id' => $form_data['room_id'],
                    'rate_plan_id' => $form_data['rate_plan_id'],
                    'adults' => $form_data['adults'],
                    'children' => $form_data['children'],
                    'check_in_date' => $form_data['check_in_date'],
                    'check_out_date' => $form_data['check_out_date'],
                    'booking_source' => $form_data['booking_source'],
                    'booking_status' => 'confirmed',
                    'payment_status' => $form_data['paid_amount'] >= $form_data['total_amount'] ? 'paid' : ($form_data['paid_amount'] > 0 ? 'partial' : 'unpaid'),
                    'total_amount' => $form_data['total_amount'],
                    'paid_amount' => $form_data['paid_amount'],
                    'special_requests' => $form_data['special_requests'] ?: null,
                    'created_by' => $user_id
                ];
                
                if (function_exists('db_insert')) {
                    $reservation_id = db_insert('reservations', $reservation_data);
                } else {
                    // Fallback direct insert
                    $pdo = get_db_connection();
                    $sql = "INSERT INTO reservations (booking_code, guest_id, room_type_id, room_id, rate_plan_id, 
                            adults, children, check_in_date, check_out_date, booking_source, booking_status, 
                            payment_status, total_amount, paid_amount, special_requests, created_by) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        $booking_code,
                        $form_data['guest_id'],
                        $form_data['room_type_id'],
                        $form_data['room_id'],
                        $form_data['rate_plan_id'],
                        $form_data['adults'],
                        $form_data['children'],
                        $form_data['check_in_date'],
                        $form_data['check_out_date'],
                        $form_data['booking_source'],
                        'confirmed',
                        $form_data['paid_amount'] >= $form_data['total_amount'] ? 'paid' : ($form_data['paid_amount'] > 0 ? 'partial' : 'unpaid'),
                        $form_data['total_amount'],
                        $form_data['paid_amount'],
                        $form_data['special_requests'] ?: null,
                        $user_id
                    ]);
                    $reservation_id = $pdo->lastInsertId();
                }
                
                // Create folio charge for room if paid
                if ($form_data['paid_amount'] > 0) {
                    $transaction_code = generate_transaction_code();
                    
                    $charge_data = [
                        'reservation_id' => $reservation_id,
                        'transaction_code' => $transaction_code,
                        'charge_type' => 'payment',
                        'description' => 'Advance payment/deposit',
                        'amount' => $form_data['paid_amount'],
                        'posted_by' => $user_id,
                        'posted_at' => date('Y-m-d H:i:s')
                    ];
                    
                    if (function_exists('db_insert')) {
                        db_insert('folio_charges', $charge_data);
                    }
                }
                
                // Send confirmation email
                if ($send_confirmation) {
                    $guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$form_data['guest_id']]);
                    send_booking_confirmation(['booking_code' => $booking_code], $guest);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'create', 'reservations', $reservation_id, null, $form_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Reservation created successfully');
                }
                
                // Redirect
                if (function_exists('redirect')) {
                    redirect('reservations/view.php?id=' . $reservation_id);
                } else {
                    header('Location: view.php?id=' . $reservation_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to create reservation: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Reservation creation failed: " . $e->getMessage(), 'ERROR');
                } else {
                    error_log("Reservation creation failed: " . $e->getMessage());
                }
            }
        }
    }
}

// Get guest if pre-selected
$selected_guest = null;
if ($form_data['guest_id']) {
    try {
        $selected_guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$form_data['guest_id']]);
    } catch (Exception $e) {
        error_log("Error fetching guest: " . $e->getMessage());
    }
}

// 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>New Reservation</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <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://cdn.jsdelivr.net/npm/bootstrap-datepicker@1.9.0/dist/css/bootstrap-datepicker3.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>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap-datepicker@1.9.0/dist/js/bootstrap-datepicker.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.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-1 { margin-left: 0.25rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .btn-group .btn { margin-right: 2px; }
            .btn-group .btn:last-child { margin-right: 0; }
        </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="#">Ruhondo Beach Resort</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="<?php echo $base_path; ?>/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">New Reservation</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo $base_path; ?>/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo $base_path; ?>/reservations/dashboard.php">Reservations</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Reservations</a></li>
                    <li class="breadcrumb-item active">Create</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; ?>

        <!-- Create Form -->
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-plus-circle me-1"></i>
                    Reservation Details
                </h3>
            </div>
            
            <form method="POST" id="reservationForm">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php else: ?>
                    <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                <?php endif; ?>
                
                <div class="card-body">
                    <!-- Guest Selection -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group mb-3">
                                <label for="guest_id">Guest <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <select class="form-control" id="guest_id" name="guest_id" required style="width: 100%;">
                                        <option value="">Select Guest</option>
                                        <?php if ($selected_guest): ?>
                                            <option value="<?php echo $selected_guest['guest_id']; ?>" selected>
                                                <?php echo htmlspecialchars(($selected_guest['first_name'] ?? '') . ' ' . ($selected_guest['last_name'] ?? '') . ' (' . ($selected_guest['email'] ?? '') . ')'); ?>
                                            </option>
                                        <?php endif; ?>
                                    </select>
                                    <button type="button" class="btn btn-info" onclick="openGuestModal()">
                                        <i class="fas fa-user-plus"></i> New Guest
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Dates -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="check_in_date">Check-in Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control datepicker" id="check_in_date" name="check_in_date" 
                                       value="<?php echo htmlspecialchars($form_data['check_in_date']); ?>" required>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="check_out_date">Check-out Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control datepicker" id="check_out_date" name="check_out_date" 
                                       value="<?php echo htmlspecialchars($form_data['check_out_date']); ?>" required>
                            </div>
                        </div>
                    </div>

                    <!-- Room Selection -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="room_type_id">Room Type <span class="text-danger">*</span></label>
                                <select class="form-control" id="room_type_id" name="room_type_id" required>
                                    <option value="">Select Room Type</option>
                                    <?php foreach ($room_types as $type): ?>
                                        <option value="<?php echo $type['room_type_id'] ?? 0; ?>" 
                                                data-price="<?php echo $type['base_price'] ?? 0; ?>"
                                                <?php echo $form_data['room_type_id'] == ($type['room_type_id'] ?? 0) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($type['type_name'] ?? ''); ?> 
                                            (<?php echo function_exists('format_currency') ? format_currency($type['base_price'] ?? 0) : 'RWF ' . number_format($type['base_price'] ?? 0); ?>/night)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="room_id">Specific Room (Optional)</label>
                                <select class="form-control" id="room_id" name="room_id">
                                    <option value="">Auto-assign</option>
                                </select>
                                <small class="text-muted">Leave empty for automatic assignment</small>
                            </div>
                        </div>
                    </div>

                    <!-- Rate Plan -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="rate_plan_id">Rate Plan</label>
                                <select class="form-control" id="rate_plan_id" name="rate_plan_id">
                                    <option value="">Standard Rate</option>
                                    <?php foreach ($rate_plans as $plan): ?>
                                        <option value="<?php echo $plan['rate_plan_id'] ?? 0; ?>" 
                                                data-rate="<?php echo $plan['base_rate'] ?? 0; ?>"
                                                data-adjustment="<?php echo $plan['adjustment_value'] ?? 0; ?>"
                                                data-type="<?php echo $plan['adjustment_type'] ?? 'fixed'; ?>">
                                            <?php echo htmlspecialchars($plan['plan_name'] ?? ''); ?> 
                                            (<?php echo function_exists('format_currency') ? format_currency($plan['base_rate'] ?? 0) : 'RWF ' . number_format($plan['base_rate'] ?? 0); ?>/night)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Guests -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="adults">Adults <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="adults" name="adults" 
                                       value="<?php echo $form_data['adults']; ?>" min="1" max="10" required>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="children">Children</label>
                                <input type="number" class="form-control" id="children" name="children" 
                                       value="<?php echo $form_data['children']; ?>" min="0" max="10">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="booking_source">Booking Source</label>
                                <select class="form-control" id="booking_source" name="booking_source">
                                    <?php 
                                    $sources = [
                                        'direct' => 'Direct',
                                        'website' => 'Website',
                                        'phone' => 'Phone',
                                        'email' => 'Email',
                                        'walk_in' => 'Walk-in',
                                        'agent' => 'Travel Agent',
                                        'ota' => 'Online Travel Agency'
                                    ];
                                    foreach ($sources as $value => $label):
                                    ?>
                                        <option value="<?php echo $value; ?>" <?php echo $form_data['booking_source'] == $value ? 'selected' : ''; ?>>
                                            <?php echo $label; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Pricing -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label>Nights</label>
                                <input type="text" class="form-control" id="nights_display" readonly>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="total_amount">Total Amount <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                    <input type="number" class="form-control" id="total_amount" name="total_amount" 
                                           value="<?php echo $form_data['total_amount']; ?>" step="0.01" min="0" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="paid_amount">Deposit / Advance Payment</label>
                                <div class="input-group">
                                    <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                    <input type="number" class="form-control" id="paid_amount" name="paid_amount" 
                                           value="<?php echo $form_data['paid_amount']; ?>" step="0.01" min="0">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Special Requests -->
                    <div class="form-group mb-3">
                        <label for="special_requests">Special Requests</label>
                        <textarea class="form-control" id="special_requests" name="special_requests" rows="3"><?php echo htmlspecialchars($form_data['special_requests']); ?></textarea>
                    </div>

                    <!-- Options -->
                    <div class="form-group mb-3">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="send_confirmation" name="send_confirmation" checked>
                            <label class="form-check-label" for="send_confirmation">
                                Send confirmation email to guest
                            </label>
                        </div>
                    </div>
                </div>
                
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i> Create Reservation
                    </button>
                    <a href="index.php" class="btn btn-secondary">
                        <i class="fas fa-times me-1"></i> Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
</section>

<!-- Quick Guest Modal -->
<div class="modal fade" id="guestModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Quick Add Guest</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="quickGuestForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label>First Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="first_name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label>Last Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="last_name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label>Email</label>
                        <input type="email" class="form-control" name="email" id="guest_email">
                    </div>
                    
                    <div class="mb-3">
                        <label>Phone</label>
                        <input type="tel" class="form-control" name="phone" id="guest_phone">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-info">Save Guest</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize Select2 for guest dropdown
    $('#guest_id').select2({
        theme: 'bootstrap-5',
        width: '100%',
        placeholder: 'Search for a guest...',
        minimumInputLength: 2,
        ajax: {
            url: '<?php echo $base_path; ?>/api/search-guests.php',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return { 
                    q: params.term,
                    _t: new Date().getTime() // Prevent caching
                };
            },
            processResults: function(data) {
                if (data && data.status === 'success' && data.data) {
                    return {
                        results: data.data.map(function(guest) {
                            return {
                                id: guest.guest_id,
                                text: (guest.first_name || '') + ' ' + (guest.last_name || '') + ' (' + (guest.email || 'no email') + ')'
                            };
                        })
                    };
                }
                return { results: [] };
            },
            error: function(xhr, status, error) {
                console.error('Select2 AJAX error:', error);
                return { results: [] };
            }
        }
    });
    
    // Initialize datepickers
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayHighlight: true,
        startDate: '<?php echo date('Y-m-d'); ?>'
    }).on('changeDate', function() {
        calculateNights();
        $('#room_type_id').trigger('change');
    });
    
    // Calculate nights
    function calculateNights() {
        const checkIn = $('#check_in_date').val();
        const checkOut = $('#check_out_date').val();
        
        if (checkIn && checkOut) {
            const start = moment(checkIn);
            const end = moment(checkOut);
            const nights = end.diff(start, 'days');
            
            if (nights > 0) {
                $('#nights_display').val(nights + ' night' + (nights > 1 ? 's' : ''));
                updateTotal();
            } else {
                $('#nights_display').val('Invalid dates');
            }
        }
    }
    
    // Update total amount based on rate
    function updateTotal() {
        const roomType = $('#room_type_id option:selected');
        const ratePlan = $('#rate_plan_id option:selected');
        const checkIn = $('#check_in_date').val();
        const checkOut = $('#check_out_date').val();
        
        if (roomType.val() && checkIn && checkOut) {
            const nights = moment(checkOut).diff(moment(checkIn), 'days');
            
            if (ratePlan.val()) {
                // Use rate plan
                const baseRate = parseFloat(ratePlan.data('rate')) || 0;
                const adjustment = parseFloat(ratePlan.data('adjustment')) || 0;
                const adjType = ratePlan.data('type');
                
                let rate = baseRate;
                if (adjType === 'percentage') {
                    rate = baseRate * (1 + adjustment / 100);
                } else {
                    rate = baseRate + adjustment;
                }
                
                $('#total_amount').val((rate * nights).toFixed(2));
            } else {
                // Use base price
                const basePrice = parseFloat(roomType.data('price')) || 0;
                $('#total_amount').val((basePrice * nights).toFixed(2));
            }
        }
    }
    
    // Load available rooms when room type changes
    $('#room_type_id').on('change', function() {
        const roomTypeId = $(this).val();
        const checkIn = $('#check_in_date').val();
        const checkOut = $('#check_out_date').val();
        
        if (roomTypeId && checkIn && checkOut) {
            $.ajax({
                url: '<?php echo $base_path; ?>/api/availability.php',
                method: 'GET',
                data: {
                    room_type_id: roomTypeId,
                    check_in: checkIn,
                    check_out: checkOut,
                    _t: new Date().getTime()
                },
                dataType: 'json',
                success: function(response) {
                    const $roomSelect = $('#room_id');
                    $roomSelect.empty().append('<option value="">Auto-assign</option>');
                    
                    if (response && response.data && response.data.length > 0) {
                        response.data.forEach(function(room) {
                            $roomSelect.append(
                                $('<option>', {
                                    value: room.room_id,
                                    text: 'Room ' + (room.room_number || '')
                                })
                            );
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Failed to load available rooms:', error);
                }
            });
        }
        
        updateTotal();
    });
    
    // Update on rate plan change
    $('#rate_plan_id').on('change', updateTotal);
    
    // Initial calculations
    calculateNights();
    
    // Quick guest form
    $('#quickGuestForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = $(this).serialize();
        
        $.ajax({
            url: '<?php echo $base_path; ?>/api/quick-add-guest.php',
            method: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response && response.status === 'success') {
                    // Add to select2
                    const newOption = new Option(
                        (response.data.first_name || '') + ' ' + (response.data.last_name || '') + ' (' + (response.data.email || '') + ')',
                        response.data.guest_id,
                        true,
                        true
                    );
                    $('#guest_id').append(newOption).trigger('change');
                    
                    // Close modal and reset form
                    $('#guestModal').modal('hide');
                    $('#quickGuestForm')[0].reset();
                    
                    // Show success message
                    alert('Guest added successfully');
                } else {
                    alert(response.message || 'Failed to add guest');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
                alert('Failed to add guest. Please check console for details.');
            }
        });
    });
    
    // Clear form when modal is closed
    $('#guestModal').on('hidden.bs.modal', function() {
        $('#quickGuestForm')[0].reset();
    });
});

function openGuestModal() {
    const modal = new bootstrap.Modal(document.getElementById('guestModal'));
    modal.show();
}
</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>';
}
?>