<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Edit Reservation - 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/reservations/
$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/reservations/ -> /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 calculate_nights function if it doesn't exist
if (!function_exists('calculate_nights')) {
    function calculate_nights($check_in, $check_out) {
        $start = strtotime($check_in);
        $end = strtotime($check_out);
        return ceil(($end - $start) / 86400);
    }
}

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

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

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

// 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['id']) ? (int)$_GET['id'] : 0;

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

// Get reservation data
$reservation = [];
if (function_exists('db_fetch_one')) {
    try {
        $reservation = db_fetch_one("
            SELECT r.*, 
                   g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                   rt.type_name, rt.type_code, rt.base_price,
                   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('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Check if reservation can be edited
if (in_array($reservation['booking_status'] ?? '', ['checked_out', 'cancelled', 'no_show'])) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'This reservation cannot be edited');
    }
    if (function_exists('redirect')) {
        redirect('view.php?id=' . $reservation_id);
    } else {
        header('Location: view.php?id=' . $reservation_id);
        exit;
    }
}

// Get room types for dropdown
$room_types = [];
if (function_exists('db_fetch_all')) {
    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 = [];
if (function_exists('db_fetch_all')) {
    try {
        $rate_plans = db_fetch_all("
            SELECT rp.*, rt.type_name, s.season_name 
            FROM rate_plans rp
            JOIN room_types rt ON rp.room_type_id = rt.room_type_id
            LEFT JOIN seasons s ON rp.season_id = s.season_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' => $reservation['guest_id'] ?? 0,
    'room_type_id' => $reservation['room_type_id'] ?? 0,
    'room_id' => $reservation['room_id'] ?? null,
    'rate_plan_id' => $reservation['rate_plan_id'] ?? null,
    'check_in_date' => $reservation['check_in_date'] ?? date('Y-m-d'),
    'check_out_date' => $reservation['check_out_date'] ?? date('Y-m-d', strtotime('+1 day')),
    'adults' => $reservation['adults'] ?? 2,
    'children' => $reservation['children'] ?? 0,
    'booking_source' => $reservation['booking_source'] ?? 'direct',
    'special_requests' => $reservation['special_requests'] ?? '',
    'total_amount' => $reservation['total_amount'] ?? 0,
    'paid_amount' => $reservation['paid_amount'] ?? 0
];

// Get booking sources
$sources = [];
if (defined('BOOKING_SOURCES')) {
    $sources = @unserialize(BOOKING_SOURCES) ?: [];
} else {
    $sources = [
        'direct' => 'Direct',
        'website' => 'Website',
        'phone' => 'Phone',
        'email' => 'Email',
        'walk_in' => 'Walk-in',
        'agent' => 'Travel Agent',
        'ota' => 'OTA'
    ];
}

// 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 {
        // Get form data
        $form_data['guest_id'] = isset($_POST['guest_id']) ? (int)$_POST['guest_id'] : 0;
        $form_data['room_type_id'] = isset($_POST['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'] = isset($_POST['check_in_date']) ? sanitize_input($_POST['check_in_date']) : '';
        $form_data['check_out_date'] = isset($_POST['check_out_date']) ? sanitize_input($_POST['check_out_date']) : '';
        $form_data['adults'] = isset($_POST['adults']) ? (int)$_POST['adults'] : 2;
        $form_data['children'] = isset($_POST['children']) ? (int)$_POST['children'] : 0;
        $form_data['booking_source'] = isset($_POST['booking_source']) ? sanitize_input($_POST['booking_source']) : 'direct';
        $form_data['special_requests'] = isset($_POST['special_requests']) ? sanitize_input($_POST['special_requests']) : '';
        $form_data['total_amount'] = isset($_POST['total_amount']) ? (float)$_POST['total_amount'] : 0;
        $form_data['paid_amount'] = $reservation['paid_amount'] ?? 0; // Don't change from POST
        
        // 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 changed
        if ($form_data['room_id'] && $form_data['room_id'] != ($reservation['room_id'] ?? 0)) {
            $available = check_room_availability(
                $form_data['room_id'],
                $form_data['check_in_date'],
                $form_data['check_out_date'],
                $reservation_id
            );
            
            if (!$available) {
                $errors[] = 'Selected room is not available for these dates';
            }
        }
        
        // Update reservation
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Calculate nights
                $nights = calculate_nights($form_data['check_in_date'], $form_data['check_out_date']);
                
                $update_data = [
                    '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'],
                    '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,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                if (function_exists('db_update')) {
                    db_update('reservations', $update_data, 'reservation_id = ?', [$reservation_id]);
                }
                
                // Create guest activity record
                if (function_exists('db_insert')) {
                    db_insert('guest_activity', [
                        'guest_id' => $form_data['guest_id'],
                        'activity_type' => 'reservation_update',
                        'description' => "Reservation updated: {$reservation['booking_code']}",
                        'reference_id' => $reservation_id,
                        'reference_type' => 'reservation',
                        'created_by' => $user_id,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'update', 'reservations', $reservation_id, $reservation, $update_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Reservation updated successfully');
                }
                
                if (function_exists('redirect')) {
                    redirect('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 update reservation: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Reservation update 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>Edit Reservation</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">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.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://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/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-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-4 { margin-top: 1.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="#">Edit Reservation</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">Edit Reservation: <?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?></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="index.php">Reservations</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $reservation_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Edit</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; ?>

        <!-- Edit Form -->
        <div class="card card-warning">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-edit me-1"></i>
                    Edit Reservation Details
                </h3>
            </div>
            
            <form method="POST" id="editForm">
                <?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">
                    <!-- Guest Selection (read-only) -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group mb-3">
                                <label>Guest</label>
                                <input type="hidden" name="guest_id" value="<?php echo $reservation['guest_id'] ?? 0; ?>">
                                <input type="text" class="form-control" 
                                       value="<?php echo htmlspecialchars(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '') . ' (' . ($reservation['email'] ?? '') . ')'); ?>" 
                                       readonly>
                            </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 $form_data['check_in_date']; ?>" 
                                       min="<?php echo date('Y-m-d'); ?>" 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 $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-select select2" 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'] ?? 0) == ($type['room_type_id'] ?? 0) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($type['type_name'] ?? ''); ?> 
                                            (<?php echo isset($type['base_price']) ? 'RWF ' . number_format($type['base_price']) : 'N/A'; ?>/night)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="room_id">Specific Room</label>
                                <select class="form-select select2" id="room_id" name="room_id">
                                    <option value="">Auto-assign</option>
                                    <?php if (!empty($reservation['room_id'])): ?>
                                        <option value="<?php echo $reservation['room_id']; ?>" selected>
                                            Room <?php echo htmlspecialchars($reservation['room_number'] ?? ''); ?> (Current)
                                        </option>
                                    <?php endif; ?>
                                </select>
                                <small class="text-muted">Change only if necessary</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-select select2" 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'] ?? ''; ?>"
                                                <?php echo ($form_data['rate_plan_id'] ?? 0) == ($plan['rate_plan_id'] ?? 0) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($plan['plan_name'] ?? ''); ?> 
                                            (<?php echo isset($plan['base_rate']) ? 'RWF ' . number_format($plan['base_rate']) : 'N/A'; ?>/night)
                                            <?php if (!empty($plan['season_name'])): ?>- <?php echo htmlspecialchars($plan['season_name']); ?><?php endif; ?>
                                        </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-select" id="booking_source" name="booking_source">
                                    <?php foreach ($sources as $value => $label): ?>
                                        <option value="<?php echo $value; ?>" <?php echo ($form_data['booking_source'] ?? '') == $value ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($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">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>Paid Amount</label>
                                <div class="input-group">
                                    <span class="input-group-text">RWF</span>
                                    <input type="text" class="form-control" value="<?php echo number_format($form_data['paid_amount'] ?? 0, 2); ?>" readonly>
                                </div>
                                <small class="text-muted">Manage payments in folio</small>
                            </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>

                    <!-- Status Info -->
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Current Status:</strong> 
                        <span class="badge bg-<?php 
                            $status = $reservation['booking_status'] ?? '';
                            echo $status == 'confirmed' ? 'success' : 
                                ($status == 'checked_in' ? 'info' : 
                                ($status == 'pending' ? 'warning' : 'secondary'));
                        ?>">
                            <?php echo ucfirst($status); ?>
                        </span>
                        - To change status, use check-in/out or cancel functions.
                    </div>
                </div>
                
                <div class="card-footer">
                    <button type="submit" class="btn btn-warning">
                        <i class="fas fa-save me-1"></i> Update Reservation
                    </button>
                    <a href="view.php?id=<?php echo $reservation_id; ?>" class="btn btn-secondary">
                        <i class="fas fa-times me-1"></i> Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
    
    // Initialize datepickers
    if ($.fn.datepicker) {
        $('.datepicker').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true,
            startDate: '<?php echo date('Y-m-d'); ?>'
        });
    }
    
    // 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 if (adjType === 'fixed') {
                    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();
        const currentRoom = <?php echo $reservation['room_id'] ?: 'null'; ?>;
        
        if (roomTypeId && checkIn && checkOut) {
            $.get('/HMSPOS/api/availability.php', {
                action: 'get_rooms',
                room_type_id: roomTypeId,
                check_in: checkIn,
                check_out: checkOut,
                exclude_reservation: <?php echo $reservation_id; ?>
            }, function(response) {
                const $roomSelect = $('#room_id');
                $roomSelect.empty().append('<option value="">Auto-assign</option>');
                
                // Add current room if it exists
                if (currentRoom) {
                    $roomSelect.append(
                        $('<option>', {
                            value: currentRoom,
                            text: 'Room <?php echo addslashes($reservation['room_number'] ?? ''); ?> (Current)',
                            selected: true
                        })
                    );
                }
                
                // Add available rooms
                if (response.data && response.data.length > 0) {
                    response.data.forEach(function(room) {
                        if (room.room_id !== currentRoom) {
                            $roomSelect.append(
                                $('<option>', {
                                    value: room.room_id,
                                    text: 'Room ' + room.room_number + ' (Available)'
                                })
                            );
                        }
                    });
                }
                
                // Refresh Select2
                if ($.fn.select2) {
                    $roomSelect.trigger('change.select2');
                }
            });
        }
        
        updateTotal();
    });
    
    // Update on date change
    $('#check_in_date, #check_out_date').on('change', function() {
        calculateNights();
        $('#room_type_id').trigger('change');
    });
    
    // Update on rate plan change
    $('#rate_plan_id').on('change', updateTotal);
    
    // Initial calculations
    calculateNights();
    
    // Warn if dates are in the past
    $('#check_in_date').on('change', function() {
        const today = moment().startOf('day');
        const checkIn = moment($(this).val());
        
        if (checkIn.isBefore(today)) {
            if (!confirm('Check-in date is in the past. Are you sure?')) {
                $(this).val('<?php echo $reservation['check_in_date'] ?? ''; ?>');
            }
        }
    });
    
    // Confirm if reducing total amount below paid amount
    $('#total_amount').on('change', function() {
        const total = parseFloat($(this).val()) || 0;
        const paid = <?php echo $reservation['paid_amount'] ?? 0; ?>;
        
        if (total < paid) {
            if (!confirm('Total amount is less than amount already paid. This will create a credit balance. Continue?')) {
                $(this).val(<?php echo $reservation['total_amount'] ?? 0; ?>);
            }
        }
    });
});
</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>';
}
?>