<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Start Check-in Process - COMPLETE INTEGRATED VERSION
 * 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)
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    $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';
}

// 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);
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        }
    }
}

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

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

// Set page title
$page_title = 'Check-in Process';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    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;
}

// Handle walk-in check-in
if (isset($_POST['walkin'])) {
    handle_walkin_checkin();
    exit;
}

// Handle direct payment from check-in
if (isset($_POST['process_payment'])) {
    process_checkin_payment();
    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,
                g.address, g.city, g.country, g.id_type, g.id_number, g.id_expiry,
                g.nationality,
                rt.type_name, rt.type_code, rt.base_price,
                rm.room_id, rm.room_number, rm.floor,
                DATEDIFF(r.check_out_date, r.check_in_date) as nights,
                (r.total_amount - r.paid_amount) as balance
            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 checked in
if (($reservation['booking_status'] ?? '') == 'checked_in') {
    if (function_exists('set_flash_message')) {
        set_flash_message('warning', 'Guest is already checked in');
    }
    if (function_exists('redirect')) {
        redirect('complete.php?id=' . $reservation_id);
    } else {
        header('Location: complete.php?id=' . $reservation_id);
        exit;
    }
}

if (($reservation['booking_status'] ?? '') == 'cancelled') {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Cannot check in a cancelled reservation');
    }
    if (function_exists('redirect')) {
        redirect('../reservations/view.php?id=' . $reservation_id);
    } else {
        header('Location: ../reservations/view.php?id=' . $reservation_id);
        exit;
    }
}

if (($reservation['booking_status'] ?? '') == 'checked_out') {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Guest has already checked out');
    }
    if (function_exists('redirect')) {
        redirect('../reservations/view.php?id=' . $reservation_id);
    } else {
        header('Location: ../reservations/view.php?id=' . $reservation_id);
        exit;
    }
}

// Check if there's an invoice for this reservation
$invoice = [];
if (function_exists('db_fetch_one')) {
    try {
        $invoice = db_fetch_one("
            SELECT invoice_id, invoice_number, total_amount, paid_amount, status
            FROM invoices 
            WHERE reservation_id = ? AND status != 'cancelled'
            ORDER BY created_at DESC LIMIT 1
        ", [$reservation_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching invoice: " . $e->getMessage());
    }
}

// If no invoice exists, create one automatically
if (empty($invoice) && !empty($reservation)) {
    try {
        if (function_exists('begin_transaction')) {
            begin_transaction();
        }
        
        // Generate invoice number
        $invoice_number = 'INV-' . date('Ymd') . '-' . str_pad($reservation_id, 6, '0', STR_PAD_LEFT);
        
        // Calculate due date (usually check-in date or current date)
        $due_date = $reservation['check_in_date'] ?? date('Y-m-d');
        
        // Create invoice
        if (function_exists('db_insert')) {
            $invoice_id = db_insert('invoices', [
                'invoice_number' => $invoice_number,
                'guest_id' => $reservation['guest_id'],
                'reservation_id' => $reservation_id,
                'invoice_date' => date('Y-m-d'),
                'due_date' => $due_date,
                'total_amount' => $reservation['total_amount'] ?? 0,
                'paid_amount' => $reservation['paid_amount'] ?? 0,
                'status' => ($reservation['balance'] ?? 0) > 0 ? 'unpaid' : 'paid',
                'notes' => 'Auto-generated from check-in process',
                'created_by' => $user_id,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            if ($invoice_id) {
                // Create invoice items
                if (function_exists('db_insert')) {
                    db_insert('invoice_items', [
                        'invoice_id' => $invoice_id,
                        'description' => 'Room Charge - ' . ($reservation['type_name'] ?? 'Room') . ' (' . ($reservation['nights'] ?? 1) . ' nights)',
                        'quantity' => $reservation['nights'] ?? 1,
                        'unit_price' => ($reservation['base_price'] ?? 0),
                        'total_price' => $reservation['total_amount'] ?? 0,
                        'item_type' => 'room_charge',
                        'reference_id' => $reservation_id
                    ]);
                }
                
                // Get the newly created invoice
                $invoice = db_fetch_one("
                    SELECT invoice_id, invoice_number, total_amount, paid_amount, status
                    FROM invoices 
                    WHERE invoice_id = ?
                ", [$invoice_id]) ?: [];
            }
        }
        
        if (function_exists('commit_transaction')) {
            commit_transaction();
        }
        
    } catch (Exception $e) {
        if (function_exists('rollback_transaction')) {
            rollback_transaction();
        }
        error_log("Error auto-creating invoice: " . $e->getMessage());
    }
}

// Get available rooms if not assigned
$available_rooms = [];
if (empty($reservation['room_id']) && function_exists('get_room_availability')) {
    try {
        $available_rooms = get_room_availability(
            $reservation['check_in_date'] ?? date('Y-m-d'),
            $reservation['check_out_date'] ?? date('Y-m-d', strtotime('+1 day')),
            $reservation['room_type_id'] ?? 0
        ) ?: [];
    } catch (Exception $e) {
        error_log("Error getting room availability: " . $e->getMessage());
    }
}

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

// Get ID document types
$id_types = [
    'passport' => 'Passport',
    'national_id' => 'National ID',
    'drivers_license' => 'Driver\'s License',
    'other' => 'Other'
];

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Check-in Process</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; }
            .callout {
                border-radius: 0.25rem;
                box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
                padding: 15px;
                margin-bottom: 20px;
            }
            .callout-info {
                border-left: 5px solid #17a2b8;
                background-color: #e3f2fd;
            }
            .callout-success {
                border-left: 5px solid #28a745;
                background-color: #d4edda;
            }
            .callout-warning {
                border-left: 5px solid #ffc107;
                background-color: #fff3cd;
            }
            .mr-1 { margin-right: 0.25rem; }
            .mr-2 { margin-right: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-4 { margin-top: 1.5rem; }
            .table-sm td, .table-sm th { padding: 0.5rem; }
            .payment-tabs { margin-bottom: 20px; }
            .payment-tab { cursor: pointer; }
            .payment-section { display: none; }
            .payment-section.active { display: block; }
        </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="#">Check-in Process</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">Check-in Process</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">Check-in</a></li>
                    <li class="breadcrumb-item active">Process</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8">
                <!-- Check-in Form -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-in-alt mr-1"></i>
                            Check-in Details
                        </h3>
                    </div>
                    
                    <form action="complete.php" method="POST" id="checkinForm" enctype="multipart/form-data">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        
                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                        
                        <div class="card-body">
                            <!-- Reservation Summary -->
                            <div class="callout callout-info">
                                <h5>Reservation Summary</h5>
                                <div class="row">
                                    <div class="col-sm-6">
                                        <strong>Booking Code:</strong> <?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?><br>
                                        <strong>Guest:</strong> <?php echo htmlspecialchars(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?><br>
                                        <strong>Room Type:</strong> <?php echo htmlspecialchars($reservation['type_name'] ?? 'N/A'); ?>
                                    </div>
                                    <div class="col-sm-6">
                                        <strong>Check-in:</strong> <?php echo isset($reservation['check_in_date']) ? date('M d, Y', strtotime($reservation['check_in_date'])) : 'N/A'; ?><br>
                                        <strong>Check-out:</strong> <?php echo isset($reservation['check_out_date']) ? date('M d, Y', strtotime($reservation['check_out_date'])) : 'N/A'; ?><br>
                                        <strong>Nights:</strong> <?php echo $reservation['nights'] ?? 0; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Room Assignment -->
                            <div class="form-group mb-3">
                                <label for="room_id">Assign Room</label>
                                <?php if (!empty($reservation['room_id'])): ?>
                                    <input type="hidden" name="room_id" value="<?php echo $reservation['room_id']; ?>">
                                    <div class="alert alert-info">
                                        <i class="fas fa-door-open mr-2"></i>
                                        Room <?php echo htmlspecialchars($reservation['room_number'] ?? ''); ?> (Floor <?php echo htmlspecialchars($reservation['floor'] ?? ''); ?>) will be assigned.
                                    </div>
                                <?php else: ?>
                                    <select class="form-select" id="room_id" name="room_id" required>
                                        <option value="">Select a room</option>
                                        <?php foreach ($available_rooms as $room): ?>
                                            <option value="<?php echo $room['room_id'] ?? ''; ?>">
                                                Room <?php echo htmlspecialchars($room['room_number'] ?? ''); ?> - <?php echo htmlspecialchars($room['type_name'] ?? ''); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (empty($available_rooms)): ?>
                                        <div class="text-danger mt-2">
                                            <i class="fas fa-exclamation-circle"></i>
                                            No rooms available for these dates. Please adjust dates or room type.
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>

                            <!-- ID Verification -->
                            <h5 class="mt-4 mb-3">ID Verification</h5>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="id_type">ID Type</label>
                                        <select class="form-select" id="id_type" name="id_type">
                                            <option value="">Select ID Type</option>
                                            <?php foreach ($id_types as $value => $label): ?>
                                                <option value="<?php echo $value; ?>" <?php echo ($reservation['id_type'] ?? '') == $value ? 'selected' : ''; ?>>
                                                    <?php echo $label; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="id_number">ID Number</label>
                                        <input type="text" class="form-control" id="id_number" name="id_number" 
                                               value="<?php echo htmlspecialchars($reservation['id_number'] ?? ''); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="id_expiry">ID Expiry</label>
                                        <input type="date" class="form-control" id="id_expiry" name="id_expiry" 
                                               value="<?php echo $reservation['id_expiry'] ?? ''; ?>">
                                    </div>
                                </div>
                            </div>

                            <!-- ID Document Upload -->
                            <div class="form-group mb-3">
                                <label for="id_document">Upload ID Document</label>
                                <input type="file" class="form-control" id="id_document" name="id_document" 
                                       accept=".jpg,.jpeg,.png,.pdf">
                                <small class="text-muted">Upload a copy of the guest's ID (optional)</small>
                            </div>

                            <!-- Address Information -->
                            <h5 class="mt-4 mb-3">Address Information</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="address">Address</label>
                                        <input type="text" class="form-control" id="address" name="address" 
                                               value="<?php echo htmlspecialchars($reservation['address'] ?? ''); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="city">City</label>
                                        <input type="text" class="form-control" id="city" name="city" 
                                               value="<?php echo htmlspecialchars($reservation['city'] ?? ''); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="country">Country</label>
                                        <input type="text" class="form-control" id="country" name="country" 
                                               value="<?php echo htmlspecialchars($reservation['country'] ?? ''); ?>">
                                    </div>
                                </div>
                            </div>

                            <!-- Registration Card -->
                            <div class="form-group mt-4 mb-3">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="print_registration" name="print_registration" checked>
                                    <label class="form-check-label" for="print_registration">
                                        Print registration card after check-in
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success" <?php echo empty($available_rooms) && empty($reservation['room_id']) ? 'disabled' : ''; ?>>
                                <i class="fas fa-check-circle mr-1"></i> Complete Check-in
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="col-md-4">
                <!-- Guest Information -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user mr-1"></i>
                            Guest Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Name:</th>
                                <td><?php echo htmlspecialchars(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td><?php echo htmlspecialchars($reservation['email'] ?? 'Not provided'); ?></td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td><?php echo htmlspecialchars($reservation['phone'] ?? 'Not provided'); ?></td>
                            </tr>
                            <tr>
                                <th>Nationality:</th>
                                <td><?php echo htmlspecialchars($reservation['nationality'] ?? 'Not provided'); ?></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Invoice Summary -->
                <?php if (!empty($invoice)): ?>
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-file-invoice mr-1"></i>
                            Invoice Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Invoice #:</th>
                                <td><?php echo htmlspecialchars($invoice['invoice_number'] ?? 'N/A'); ?></td>
                            </tr>
                            <tr>
                                <th>Status:</th>
                                <td>
                                    <?php
                                    $status = $invoice['status'] ?? 'unpaid';
                                    $badge_class = 'secondary';
                                    if ($status == 'paid') $badge_class = 'success';
                                    elseif ($status == 'partial') $badge_class = 'warning';
                                    elseif ($status == 'unpaid') $badge_class = 'danger';
                                    ?>
                                    <span class="badge bg-<?php echo $badge_class; ?>"><?php echo ucfirst($status); ?></span>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Payment Summary -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-dollar-sign mr-1"></i>
                            Payment Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Total Amount:</th>
                                <td class="text-end">RWF <?php echo number_format($reservation['total_amount'] ?? 0); ?></td>
                            </tr>
                            <tr>
                                <th>Paid Amount:</th>
                                <td class="text-end text-success">RWF <?php echo number_format($reservation['paid_amount'] ?? 0); ?></td>
                            </tr>
                            <tr class="table-<?php echo !empty($reservation['balance']) && $reservation['balance'] > 0 ? 'danger' : 'success'; ?>">
                                <th>Balance Due:</th>
                                <td class="text-end">
                                    <strong>RWF <?php echo number_format($reservation['balance'] ?? 0); ?></strong>
                                </td>
                            </tr>
                        </table>
                        
                        <?php if (!empty($reservation['balance']) && $reservation['balance'] > 0): ?>
                            <!-- Payment Tabs -->
                            <div class="payment-tabs">
                                <ul class="nav nav-tabs" id="paymentTabs" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link active" id="quick-payment-tab" data-bs-toggle="tab" data-bs-target="#quick-payment" type="button" role="tab">
                                            <i class="fas fa-bolt"></i> Quick Payment
                                        </button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="full-billing-tab" data-bs-toggle="tab" data-bs-target="#full-billing" type="button" role="tab">
                                            <i class="fas fa-credit-card"></i> Full Billing
                                        </button>
                                    </li>
                                </ul>
                                
                                <div class="tab-content mt-3">
                                    <!-- Quick Payment Tab -->
                                    <div class="tab-pane fade show active" id="quick-payment" role="tabpanel">
                                        <form method="POST" id="quickPaymentForm">
                                            <?php if (function_exists('csrf_field')): ?>
                                                <?php echo csrf_field(); ?>
                                            <?php else: ?>
                                                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                                            <?php endif; ?>
                                            
                                            <input type="hidden" name="process_payment" value="1">
                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                            <input type="hidden" name="guest_id" value="<?php echo $reservation['guest_id']; ?>">
                                            <input type="hidden" name="invoice_id" value="<?php echo $invoice['invoice_id'] ?? 0; ?>">
                                            
                                            <div class="form-group mb-3">
                                                <label>Amount to Pay</label>
                                                <div class="input-group">
                                                    <span class="input-group-text">RWF</span>
                                                    <input type="number" class="form-control" name="payment_amount" 
                                                           value="<?php echo $reservation['balance']; ?>" step="100" min="0" max="<?php echo $reservation['balance']; ?>" required>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group mb-3">
                                                <label>Payment Method</label>
                                                <select class="form-select" name="payment_method_id" required>
                                                    <option value="">Select Method</option>
                                                    <?php foreach ($payment_methods as $method): ?>
                                                        <option value="<?php echo $method['payment_method_id']; ?>">
                                                            <?php echo htmlspecialchars($method['method_name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group mb-3">
                                                <label>Reference (Optional)</label>
                                                <input type="text" class="form-control" name="reference_number" 
                                                       placeholder="Transaction ID / Check #">
                                            </div>
                                            
                                            <button type="submit" class="btn btn-success w-100">
                                                <i class="fas fa-check-circle"></i> Process Payment
                                            </button>
                                        </form>
                                    </div>
                                    
                                    <!-- Full Billing Tab -->
                                    <div class="tab-pane fade" id="full-billing" role="tabpanel">
                                        <?php if (!empty($invoice)): ?>
                                            <a href="/HMSPOS/admin/billing/payments/add.php?invoice_id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-primary w-100 mb-2">
                                                <i class="fas fa-credit-card"></i> Go to Billing System
                                            </a>
                                            <a href="/HMSPOS/admin/billing/invoices/view.php?id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-info w-100">
                                                <i class="fas fa-file-invoice"></i> View Full Invoice
                                            </a>
                                        <?php else: ?>
                                            <a href="/HMSPOS/admin/billing/invoices/create.php?reservation_id=<?php echo $reservation_id; ?>&guest_id=<?php echo $reservation['guest_id']; ?>" class="btn btn-warning w-100">
                                                <i class="fas fa-file-invoice"></i> Create Invoice
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Payment History (if any) -->
                            <?php
                            $payments = [];
                            if (function_exists('db_fetch_all') && !empty($invoice)) {
                                try {
                                    $payments = db_fetch_all("
                                        SELECT p.*, pm.method_name
                                        FROM payments p
                                        LEFT JOIN payment_methods pm ON p.payment_method_id = pm.payment_method_id
                                        WHERE p.invoice_id = ?
                                        ORDER BY p.payment_date DESC
                                    ", [$invoice['invoice_id']]) ?: [];
                                } catch (Exception $e) {
                                    error_log("Error fetching payments: " . $e->getMessage());
                                }
                            }
                            ?>
                            
                            <?php if (!empty($payments)): ?>
                            <div class="mt-3">
                                <h6 class="text-muted">Recent Payments</h6>
                                <div class="list-group small">
                                    <?php foreach (array_slice($payments, 0, 3) as $payment): ?>
                                        <div class="list-group-item d-flex justify-content-between align-items-center p-2">
                                            <div>
                                                <small><?php echo date('M d, H:i', strtotime($payment['payment_date'])); ?></small><br>
                                                <small class="text-muted"><?php echo htmlspecialchars($payment['method_name'] ?? 'N/A'); ?></small>
                                            </div>
                                            <span class="text-success fw-bold">RWF <?php echo number_format($payment['amount']); ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                        <?php else: ?>
                            <div class="alert alert-success mb-0">
                                <i class="fas fa-check-circle"></i> No balance due
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Check-in Checklist -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clipboard-check mr-1"></i>
                            Check-in Checklist
                        </h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-<?php echo !empty($reservation['room_id']) ? 'check-circle text-success' : 'times-circle text-danger'; ?> me-2"></i>
                                Room assigned
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-<?php echo !empty($reservation['id_number']) ? 'check-circle text-success' : 'circle text-muted'; ?> me-2"></i>
                                ID verified
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-<?php echo empty($reservation['balance']) || $reservation['balance'] == 0 ? 'check-circle text-success' : 'exclamation-triangle text-warning'; ?> me-2"></i>
                                Payment collected
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-circle text-muted me-2"></i>
                                Registration card signed
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-circle text-muted me-2"></i>
                                Keys issued
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize Select2 if available
    if ($.fn.select2 && $('#room_id').is('select')) {
        $('#room_id').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
    
    // File input label update
    $('.custom-file-input').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').addClass("selected").html(fileName);
    });
    
    // Quick payment form validation
    $('#quickPaymentForm').on('submit', function(e) {
        const amount = parseFloat($('input[name="payment_amount"]').val()) || 0;
        const maxAmount = parseFloat($('input[name="payment_amount"]').attr('max')) || 0;
        
        if (amount <= 0) {
            e.preventDefault();
            alert('Please enter a valid amount greater than 0');
            return false;
        }
        
        if (amount > maxAmount) {
            e.preventDefault();
            alert('Payment amount cannot exceed the balance due');
            return false;
        }
        
        if (!$('select[name="payment_method_id"]').val()) {
            e.preventDefault();
            alert('Please select a payment method');
            return false;
        }
        
        return confirm('Process payment of RWF ' + amount.toFixed(2) + '?');
    });
});
</script>

<?php
/**
 * Handle walk-in check-in
 */
function handle_walkin_checkin() {
    global $current_user, $user_id;
    
    // CSRF verification
    if (function_exists('verify_csrf_token')) {
        if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', 'Invalid security token');
            }
            if (function_exists('redirect')) {
                redirect('index.php');
            } else {
                header('Location: index.php');
                exit;
            }
        }
    }
    
    $first_name = isset($_POST['first_name']) ? htmlspecialchars(trim($_POST['first_name'])) : '';
    $last_name = isset($_POST['last_name']) ? htmlspecialchars(trim($_POST['last_name'])) : '';
    $email = isset($_POST['email']) ? htmlspecialchars(trim($_POST['email'])) : '';
    $phone = isset($_POST['phone']) ? htmlspecialchars(trim($_POST['phone'])) : '';
    $room_type_id = isset($_POST['room_type_id']) ? (int)$_POST['room_type_id'] : 0;
    $nights = isset($_POST['nights']) ? (int)$_POST['nights'] : 1;
    $adults = isset($_POST['adults']) ? (int)$_POST['adults'] : 2;
    $children = isset($_POST['children']) ? (int)$_POST['children'] : 0;
    
    $errors = [];
    
    if (empty($first_name)) $errors[] = 'First name is required';
    if (empty($last_name)) $errors[] = 'Last name is required';
    if (!$room_type_id) $errors[] = 'Room type is required';
    if ($nights < 1) $errors[] = 'Nights must be at least 1';
    if ($adults < 1) $errors[] = 'At least 1 adult is required';
    
    if (empty($errors)) {
        try {
            if (function_exists('begin_transaction')) {
                begin_transaction();
            }
            
            // Create guest
            $guest_code = 'G-' . date('Y') . '-' . str_pad((function_exists('db_fetch_value') ? (db_fetch_value("SELECT COUNT(*) FROM guests") + 1) : 1), 4, '0', STR_PAD_LEFT);
            
            $guest_id = null;
            if (function_exists('db_insert')) {
                $guest_id = db_insert('guests', [
                    'guest_code' => $guest_code,
                    'first_name' => $first_name,
                    'last_name' => $last_name,
                    'email' => $email ?: null,
                    'phone' => $phone ?: null
                ]);
            }
            
            if (!$guest_id) {
                throw new Exception('Failed to create guest');
            }
            
            // Calculate dates
            $check_in = date('Y-m-d');
            $check_out = date('Y-m-d', strtotime("+$nights days"));
            
            // Get room type base price
            $room_type = [];
            if (function_exists('db_fetch_one')) {
                $room_type = db_fetch_one("SELECT * FROM room_types WHERE room_type_id = ?", [$room_type_id]) ?: [];
            }
            $total_amount = ($room_type['base_price'] ?? 100) * $nights;
            
            // Find available room
            $available_rooms = [];
            if (function_exists('get_room_availability')) {
                $available_rooms = get_room_availability($check_in, $check_out, $room_type_id) ?: [];
            }
            
            if (empty($available_rooms)) {
                throw new Exception('No rooms available for these dates');
            }
            
            $room_id = $available_rooms[0]['room_id'] ?? 0;
            
            // Create reservation
            $booking_code = function_exists('generate_booking_code') ? generate_booking_code() : 'W' . date('Ymd') . rand(1000, 9999);
            
            $reservation_id = null;
            if (function_exists('db_insert')) {
                $reservation_id = db_insert('reservations', [
                    'booking_code' => $booking_code,
                    'guest_id' => $guest_id,
                    'room_type_id' => $room_type_id,
                    'room_id' => $room_id,
                    'adults' => $adults,
                    'children' => $children,
                    'check_in_date' => $check_in,
                    'check_out_date' => $check_out,
                    'booking_source' => 'walk_in',
                    'booking_status' => 'checked_in',
                    'payment_status' => 'unpaid',
                    'total_amount' => $total_amount,
                    'paid_amount' => 0,
                    'created_by' => $current_user['user_id'] ?? $user_id ?? 0
                ]);
            }
            
            // Update room status
            if (function_exists('db_update') && $room_id) {
                db_update('rooms', ['status' => 'occupied'], 'room_id = ?', [$room_id]);
            }
            
            // Auto-create invoice for walk-in
            if ($reservation_id && function_exists('db_insert')) {
                $invoice_number = 'INV-' . date('Ymd') . '-' . str_pad($reservation_id, 6, '0', STR_PAD_LEFT);
                
                db_insert('invoices', [
                    'invoice_number' => $invoice_number,
                    'guest_id' => $guest_id,
                    'reservation_id' => $reservation_id,
                    'invoice_date' => date('Y-m-d'),
                    'due_date' => $check_in,
                    'total_amount' => $total_amount,
                    'paid_amount' => 0,
                    'status' => 'unpaid',
                    'created_by' => $current_user['user_id'] ?? $user_id ?? 0,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            if (function_exists('commit_transaction')) {
                commit_transaction();
            }
            
            if (function_exists('set_flash_message')) {
                set_flash_message('success', 'Walk-in check-in completed successfully');
            }
            
            if (function_exists('redirect')) {
                redirect('complete.php?id=' . $reservation_id);
            } else {
                header('Location: complete.php?id=' . $reservation_id);
                exit;
            }
            
        } catch (Exception $e) {
            if (function_exists('rollback_transaction')) {
                rollback_transaction();
            }
            error_log("Walk-in check-in error: " . $e->getMessage());
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', 'Failed to process walk-in: ' . $e->getMessage());
            }
            if (function_exists('redirect')) {
                redirect('index.php');
            } else {
                header('Location: index.php');
                exit;
            }
        }
    } else {
        foreach ($errors as $error) {
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', $error);
            }
        }
        if (function_exists('redirect')) {
            redirect('index.php');
        } else {
            header('Location: index.php');
            exit;
        }
    }
}

/**
 * Process payment during check-in
 */
function process_checkin_payment() {
    global $user_id;
    
    // CSRF verification
    if (function_exists('verify_csrf_token')) {
        if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', 'Invalid security token');
            }
            if (function_exists('redirect')) {
                redirect($_SERVER['HTTP_REFERER'] ?? 'index.php');
            } else {
                header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php'));
                exit;
            }
        }
    }
    
    $reservation_id = isset($_POST['reservation_id']) ? (int)$_POST['reservation_id'] : 0;
    $guest_id = isset($_POST['guest_id']) ? (int)$_POST['guest_id'] : 0;
    $invoice_id = isset($_POST['invoice_id']) ? (int)$_POST['invoice_id'] : 0;
    $amount = isset($_POST['payment_amount']) ? (float)$_POST['payment_amount'] : 0;
    $payment_method_id = isset($_POST['payment_method_id']) ? (int)$_POST['payment_method_id'] : 0;
    $reference_number = isset($_POST['reference_number']) ? sanitize_input($_POST['reference_number']) : '';
    
    $errors = [];
    
    if (!$reservation_id) $errors[] = 'Invalid reservation';
    if (!$guest_id) $errors[] = 'Invalid guest';
    if (!$invoice_id) $errors[] = 'No invoice found for this reservation';
    if ($amount <= 0) $errors[] = 'Amount must be greater than 0';
    if (!$payment_method_id) $errors[] = 'Payment method is required';
    
    if (empty($errors)) {
        try {
            if (function_exists('begin_transaction')) {
                begin_transaction();
            }
            
            // Get invoice details
            $invoice = null;
            if (function_exists('db_fetch_one')) {
                $invoice = db_fetch_one("SELECT * FROM invoices WHERE invoice_id = ?", [$invoice_id]);
            }
            
            if (!$invoice) {
                throw new Exception('Invoice not found');
            }
            
            // Check if amount exceeds balance
            $balance = ($invoice['total_amount'] ?? 0) - ($invoice['paid_amount'] ?? 0);
            if ($amount > $balance) {
                throw new Exception('Payment amount exceeds invoice balance');
            }
            
            // Generate payment number
            $payment_number = 'PAY-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
            
            // Create payment
            $payment_id = null;
            if (function_exists('db_insert')) {
                $payment_id = db_insert('payments', [
                    'payment_number' => $payment_number,
                    'invoice_id' => $invoice_id,
                    'guest_id' => $guest_id,
                    'payment_method_id' => $payment_method_id,
                    'amount' => $amount,
                    'payment_date' => date('Y-m-d H:i:s'),
                    'reference_number' => $reference_number ?: null,
                    'received_by' => $user_id,
                    'status' => 'completed',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            if (!$payment_id) {
                throw new Exception('Failed to record payment');
            }
            
            // Update invoice
            $new_paid = ($invoice['paid_amount'] ?? 0) + $amount;
            $new_status = $new_paid >= ($invoice['total_amount'] ?? 0) ? 'paid' : 'partial';
            
            if (function_exists('db_update')) {
                db_update('invoices', [
                    'paid_amount' => $new_paid,
                    'status' => $new_status
                ], 'invoice_id = ?', [$invoice_id]);
            }
            
            // Update reservation paid amount
            if (function_exists('db_fetch_one')) {
                $reservation = db_fetch_one("SELECT paid_amount FROM reservations WHERE reservation_id = ?", [$reservation_id]);
                $new_reservation_paid = ($reservation['paid_amount'] ?? 0) + $amount;
                
                db_update('reservations', [
                    'paid_amount' => $new_reservation_paid,
                    'payment_status' => $new_reservation_paid >= ($invoice['total_amount'] ?? 0) ? 'paid' : 'partial'
                ], 'reservation_id = ?', [$reservation_id]);
            }
            
            // Create guest activity
            if (function_exists('db_insert')) {
                db_insert('guest_activity', [
                    'guest_id' => $guest_id,
                    'activity_type' => 'payment',
                    'description' => "Payment received during check-in: " . format_currency($amount) . " for invoice #" . ($invoice['invoice_number'] ?? ''),
                    'reference_id' => $payment_id,
                    'reference_type' => 'payment',
                    'created_by' => $user_id,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            if (function_exists('commit_transaction')) {
                commit_transaction();
            }
            
            if (function_exists('set_flash_message')) {
                set_flash_message('success', 'Payment of ' . format_currency($amount) . ' recorded successfully');
            }
            
            // Redirect back to check-in page
            if (function_exists('redirect')) {
                redirect('start.php?id=' . $reservation_id);
            } else {
                header('Location: start.php?id=' . $reservation_id);
                exit;
            }
            
        } catch (Exception $e) {
            if (function_exists('rollback_transaction')) {
                rollback_transaction();
            }
            error_log("Payment processing error: " . $e->getMessage());
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', 'Failed to process payment: ' . $e->getMessage());
            }
            if (function_exists('redirect')) {
                redirect($_SERVER['HTTP_REFERER'] ?? 'start.php?id=' . $reservation_id);
            } else {
                header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'start.php?id=' . $reservation_id));
                exit;
            }
        }
    } else {
        foreach ($errors as $error) {
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', $error);
            }
        }
        if (function_exists('redirect')) {
            redirect($_SERVER['HTTP_REFERER'] ?? 'start.php?id=' . $reservation_id);
        } else {
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'start.php?id=' . $reservation_id));
            exit;
        }
    }
}

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