<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Move Charges Between Reservations - 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, H:i') {
        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 DATETIME_FORMAT if not defined
if (!defined('DATETIME_FORMAT')) {
    define('DATETIME_FORMAT', 'Y-m-d H:i:s');
}

// 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 = 'Move Charges';

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

if (!$source_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 source reservation
$source = [];
if (function_exists('db_fetch_one')) {
    try {
        $source = db_fetch_one("
            SELECT r.*, g.first_name, g.last_name, g.guest_id,
                   rm.room_number
            FROM reservations r
            JOIN guests g ON r.guest_id = g.guest_id
            LEFT JOIN rooms rm ON r.room_id = rm.room_id
            WHERE r.reservation_id = ?
        ", [$source_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching source reservation: " . $e->getMessage());
    }
}

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

// Get all non-payment, non-voided charges from source
$charges = [];
if (function_exists('db_fetch_all')) {
    try {
        $charges = db_fetch_all("
            SELECT fc.*, u.first_name, u.last_name
            FROM folio_charges fc
            LEFT JOIN users u ON fc.posted_by = u.user_id
            WHERE fc.reservation_id = ? 
            AND fc.charge_type != 'payment' 
            AND (fc.is_voided IS NULL OR fc.is_voided = 0)
            ORDER BY fc.posted_at
        ", [$source_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching charges: " . $e->getMessage());
    }
}

// Calculate total amount that can be moved
$total_move = 0;
foreach ($charges as $charge) {
    $total_move += $charge['amount'] ?? 0;
}

// Get active reservations for the same guest or other guests
$target_reservations = [];
if (function_exists('db_fetch_all')) {
    try {
        $target_reservations = db_fetch_all("
            SELECT r.*, g.first_name, g.last_name, g.guest_id,
                   rm.room_number
            FROM reservations r
            JOIN guests g ON r.guest_id = g.guest_id
            LEFT JOIN rooms rm ON r.room_id = rm.room_id
            WHERE r.reservation_id != ?
            AND r.booking_status IN ('confirmed', 'checked_in')
            ORDER BY r.check_in_date
        ", [$source_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching target reservations: " . $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 {
        $target_id = isset($_POST['target_id']) ? (int)$_POST['target_id'] : 0;
        $selected_charges = $_POST['charges'] ?? [];
        $move_type = $_POST['move_type'] ?? 'transfer';
        $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        
        if (!$target_id) {
            $errors[] = 'Please select a target reservation';
        }
        
        if (empty($selected_charges)) {
            $errors[] = 'Please select at least one charge to move';
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $total_moved = 0;
                $charge_ids = [];
                
                foreach ($selected_charges as $charge_id) {
                    // Get original charge
                    $charge = null;
                    if (function_exists('db_fetch_one')) {
                        $charge = db_fetch_one("SELECT * FROM folio_charges WHERE charge_id = ?", [$charge_id]);
                    }
                    
                    if (!$charge) continue;
                    
                    if ($move_type == 'transfer') {
                        // Move: void original and create new
                        
                        // Void original charge
                        if (function_exists('db_update')) {
                            db_update('folio_charges', [
                                'is_voided' => 1,
                                'void_reason' => "Moved to reservation #$target_id" . ($notes ? ": $notes" : ""),
                                'voided_by' => $user_id,
                                'voided_at' => date(DATETIME_FORMAT)
                            ], 'charge_id = ?', [$charge_id]);
                        }
                        
                        // Create new charge in target
                        $new_charge_data = [
                            'reservation_id' => $target_id,
                            'transaction_code' => function_exists('generate_transaction_code') ? generate_transaction_code() : 'TXN' . date('Ymd') . rand(1000, 9999),
                            'charge_type' => $charge['charge_type'],
                            'description' => $charge['description'] . " (transferred from #$source_id)",
                            'quantity' => $charge['quantity'] ?? 1,
                            'unit_price' => $charge['unit_price'] ?? $charge['amount'],
                            'amount' => $charge['amount'],
                            'product_id' => $charge['product_id'],
                            'pos_outlet_id' => $charge['pos_outlet_id'],
                            'posted_by' => $user_id,
                            'notes' => "Original charge #$charge_id",
                            'posted_at' => date(DATETIME_FORMAT)
                        ];
                        
                        if (function_exists('db_insert')) {
                            db_insert('folio_charges', $new_charge_data);
                        }
                        
                        $total_moved += $charge['amount'];
                        $charge_ids[] = $charge_id;
                        
                    } else {
                        // Copy: create duplicate without voiding original
                        $new_charge_data = [
                            'reservation_id' => $target_id,
                            'transaction_code' => function_exists('generate_transaction_code') ? generate_transaction_code() : 'TXN' . date('Ymd') . rand(1000, 9999),
                            'charge_type' => $charge['charge_type'],
                            'description' => $charge['description'] . " (copy)",
                            'quantity' => $charge['quantity'] ?? 1,
                            'unit_price' => $charge['unit_price'] ?? $charge['amount'],
                            'amount' => $charge['amount'],
                            'product_id' => $charge['product_id'],
                            'pos_outlet_id' => $charge['pos_outlet_id'],
                            'posted_by' => $user_id,
                            'notes' => "Copied from reservation #$source_id, charge #$charge_id" . ($notes ? ": $notes" : ""),
                            'posted_at' => date(DATETIME_FORMAT)
                        ];
                        
                        if (function_exists('db_insert')) {
                            db_insert('folio_charges', $new_charge_data);
                        }
                        
                        $total_moved += $charge['amount'];
                        $charge_ids[] = $charge_id;
                    }
                }
                
                // Create activity records
                if (function_exists('db_insert')) {
                    db_insert('guest_activity', [
                        'guest_id' => $source['guest_id'] ?? 0,
                        'activity_type' => 'charge_moved',
                        'description' => "Charges moved to reservation #$target_id: " . implode(', ', $charge_ids) . ($notes ? " ($notes)" : ""),
                        'reference_id' => $source_id,
                        'reference_type' => 'reservation',
                        'created_by' => $user_id,
                        'created_at' => date(DATETIME_FORMAT)
                    ]);
                    
                    // Get target guest info
                    $target = null;
                    if (function_exists('db_fetch_one')) {
                        $target = db_fetch_one("SELECT guest_id FROM reservations WHERE reservation_id = ?", [$target_id]);
                    }
                    
                    if ($target) {
                        db_insert('guest_activity', [
                            'guest_id' => $target['guest_id'] ?? 0,
                            'activity_type' => 'charge_received',
                            'description' => "Charges received from reservation #$source_id: " . implode(', ', $charge_ids) . ($notes ? " ($notes)" : ""),
                            'reference_id' => $target_id,
                            'reference_type' => 'reservation',
                            'created_by' => $user_id,
                            'created_at' => date(DATETIME_FORMAT)
                        ]);
                    }
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'move_charges', 'folio_charges', null, 
                             ['source' => $source_id, 'target' => $target_id, 'charges' => $charge_ids],
                             ['action' => $move_type, 'total' => $total_moved]);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', count($charge_ids) . ' charge(s) moved successfully. Total: ' . format_currency($total_moved));
                }
                
                if (function_exists('redirect')) {
                    redirect('view.php?reservation_id=' . $source_id);
                } else {
                    header('Location: view.php?reservation_id=' . $source_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to move charges: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Move charges 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>Move Charges</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-3 { margin-top: 1rem; }
            .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="#">Move Charges</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">Move Charges</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 $source_id; ?>">Reservation</a></li>
                    <li class="breadcrumb-item"><a href="view.php?reservation_id=<?php echo $source_id; ?>">Folio</a></li>
                    <li class="breadcrumb-item active">Move Charges</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">
            <!-- Source Reservation Info -->
            <div class="col-md-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-share-square me-1"></i>
                            Source Reservation
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <strong>Booking Code:</strong><br>
                                <?php echo htmlspecialchars($source['booking_code'] ?? 'N/A'); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Guest:</strong><br>
                                <?php echo escape_html(($source['first_name'] ?? '') . ' ' . ($source['last_name'] ?? '')); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Room:</strong><br>
                                <?php echo $source['room_number'] ?: 'Not assigned'; ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Total to Move:</strong><br>
                                <span class="badge bg-warning badge-lg"><?php echo format_currency($total_move); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Move Charges Form -->
        <form method="POST" id="moveForm">
            <?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="row">
                <!-- Charges List -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-list me-1"></i>
                                Select Charges to Move
                            </h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-sm btn-info" onclick="selectAll()">
                                    <i class="fas fa-check-double"></i> Select All
                                </button>
                                <button type="button" class="btn btn-sm btn-secondary" onclick="deselectAll()">
                                    <i class="fas fa-times"></i> Deselect All
                                </button>
                            </div>
                        </div>
                        
                        <div class="card-body p-0">
                            <?php if (empty($charges)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-receipt fa-3x mb-3"></i>
                                    <p>No charges available to move</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th width="30">
                                                    <input type="checkbox" id="selectAllCheckbox">
                                                </th>
                                                <th>Date</th>
                                                <th>Description</th>
                                                <th class="text-end">Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($charges as $charge): ?>
                                            <tr>
                                                <td>
                                                    <input type="checkbox" name="charges[]" value="<?php echo $charge['charge_id'] ?? 0; ?>" 
                                                           class="charge-checkbox">
                                                </td>
                                                <td><?php echo isset($charge['posted_at']) ? date('M d, H:i', strtotime($charge['posted_at'])) : 'N/A'; ?></td>
                                                <td>
                                                    <?php echo escape_html($charge['description'] ?? ''); ?>
                                                    <br>
                                                    <small class="text-muted"><?php echo ucfirst($charge['charge_type'] ?? ''); ?></small>
                                                </td>
                                                <td class="text-end"><?php echo format_currency($charge['amount'] ?? 0); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr class="table-info">
                                                <th colspan="3" class="text-end">Total Selected:</th>
                                                <th class="text-end" id="selectedTotal"><?php echo format_currency(0); ?></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Target Selection -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-download me-1"></i>
                                Target Reservation
                            </h3>
                        </div>
                        
                        <div class="card-body">
                            <div class="form-group mb-3">
                                <label for="target_id">Select Target Reservation <span class="text-danger">*</span></label>
                                <select class="form-select select2" id="target_id" name="target_id" required>
                                    <option value="">Choose a reservation</option>
                                    <?php foreach ($target_reservations as $target): ?>
                                        <option value="<?php echo $target['reservation_id'] ?? 0; ?>">
                                            <?php echo htmlspecialchars($target['booking_code'] ?? ''); ?> - 
                                            <?php echo escape_html(($target['first_name'] ?? '') . ' ' . ($target['last_name'] ?? '')); ?> 
                                            (Room <?php echo $target['room_number'] ?: 'N/A'; ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="form-group mb-3">
                                <label for="move_type">Move Type</label>
                                <select class="form-select" id="move_type" name="move_type">
                                    <option value="transfer">Transfer (remove from source)</option>
                                    <option value="copy">Copy (keep in source)</option>
                                </select>
                                <small class="text-muted">
                                    Transfer moves the charges and voids them in source. Copy duplicates them.
                                </small>
                            </div>

                            <div class="form-group mb-3">
                                <label for="notes">Notes (Optional)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                            </div>

                            <!-- Quick Summary -->
                            <div class="info-box bg-light">
                                <span class="info-box-icon bg-info elevation-1">
                                    <i class="fas fa-calculator"></i>
                                </span>
                                <div class="info-box-content">
                                    <span class="info-box-text">Charges Selected</span>
                                    <span class="info-box-number" id="selectedCount">0</span>
                                </div>
                            </div>

                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <strong>Note:</strong> Moving charges will update both reservations' balances. 
                                This action is logged for audit purposes.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary" <?php echo empty($charges) ? 'disabled' : ''; ?>>
                                <i class="fas fa-arrows-alt me-1"></i> Move Selected Charges
                            </button>
                            <a href="view.php?reservation_id=<?php echo $source_id; ?>" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <!-- Information Card -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            About Moving Charges
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <h6><i class="fas fa-check-circle text-success me-2"></i>When to Transfer</h6>
                                <p class="text-muted small">
                                    Use Transfer when a charge was posted to the wrong reservation.
                                    The original charge will be voided and recreated in the target.
                                </p>
                            </div>
                            <div class="col-md-4">
                                <h6><i class="fas fa-copy text-info me-2"></i>When to Copy</h6>
                                <p class="text-muted small">
                                    Use Copy when a charge should be split between reservations
                                    or when creating a duplicate for another guest.
                                </p>
                            </div>
                            <div class="col-md-4">
                                <h6><i class="fas fa-history text-warning me-2"></i>Audit Trail</h6>
                                <p class="text-muted small">
                                    All moves are logged with user, timestamp, and reason.
                                    Original charges that are transferred are marked as void with reference.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
    
    // Select All checkbox
    $('#selectAllCheckbox').on('change', function() {
        $('.charge-checkbox').prop('checked', $(this).prop('checked'));
        updateSelectedTotals();
    });
    
    // Individual checkboxes
    $('.charge-checkbox').on('change', function() {
        updateSelectAll();
        updateSelectedTotals();
    });
    
    function updateSelectAll() {
        const total = $('.charge-checkbox').length;
        const checked = $('.charge-checkbox:checked').length;
        $('#selectAllCheckbox').prop('checked', total > 0 && checked === total);
    }
    
    function updateSelectedTotals() {
        const checked = $('.charge-checkbox:checked');
        const count = checked.length;
        let total = 0;
        
        checked.each(function() {
            const row = $(this).closest('tr');
            const amountText = row.find('td:last').text();
            const amount = parseFloat(amountText.replace(/[^0-9.-]+/g, '')) || 0;
            total += amount;
        });
        
        $('#selectedCount').text(count);
        $('#selectedTotal').text(formatCurrency(total));
    }
    
    function formatCurrency(amount) {
        return '<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?> ' + amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    }
    
    // Initial update
    updateSelectedTotals();
});

window.selectAll = function() {
    $('.charge-checkbox').prop('checked', true);
    $('#selectAllCheckbox').prop('checked', true);
    updateSelectedTotals();
};

window.deselectAll = function() {
    $('.charge-checkbox').prop('checked', false);
    $('#selectAllCheckbox').prop('checked', false);
    updateSelectedTotals();
};

// Form validation
$('#moveForm').on('submit', function(e) {
    const selected = $('.charge-checkbox:checked').length;
    const target = $('#target_id').val();
    
    if (selected === 0) {
        e.preventDefault();
        alert('Please select at least one charge to move');
        return false;
    }
    
    if (!target) {
        e.preventDefault();
        alert('Please select a target reservation');
        return false;
    }
    
    const moveType = $('#move_type').val();
    const confirmMsg = moveType === 'transfer' 
        ? 'This will permanently move the selected charges to the target reservation. Continue?'
        : 'This will create copies of the selected charges in the target reservation. Continue?';
    
    return confirm(confirmMsg);
});
</script>

<style>
.badge-lg {
    font-size: 1.1rem;
    padding: 0.5rem 1rem;
}
.info-box {
    box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2);
    border-radius: 0.25rem;
    background: #fff;
    display: flex;
    margin-bottom: 20px;
    min-height: 80px;
}
.info-box-icon {
    border-radius: 0.25rem 0 0 0.25rem;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 70px;
    font-size: 1.875rem;
    text-align: center;
}
.info-box-content {
    padding: 10px;
    flex: 1;
}
.bg-light { background-color: #f8f9fa !important; }
</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>';
}
?>