<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest Registration Card - 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/documents/
$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/documents/ -> /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'
];

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 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 format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// Define constants if not defined
if (!defined('DEFAULT_CHECKOUT_TIME')) {
    define('DEFAULT_CHECKOUT_TIME', '11:00');
}

// Get reservation ID from URL
$reservation_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$reservation_id) {
    die('Invalid reservation ID');
}

// Get reservation data with all details
$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.nationality,
                g.id_type, g.id_number, g.id_expiry,
                rt.type_name, rt.type_code,
                rm.room_number, rm.floor,
                u.first_name as created_by_first, u.last_name as created_by_last,
                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
            LEFT JOIN users u ON r.created_by = u.user_id
            WHERE r.reservation_id = ?
        ", [$reservation_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching reservation: " . $e->getMessage());
        die('Error loading reservation data');
    }
}

if (empty($reservation)) {
    die('Reservation not found');
}

// Get resort settings
$resort = [];
if (function_exists('db_fetch_one')) {
    try {
        $resort = db_fetch_one("SELECT * FROM resort_settings LIMIT 1") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching resort settings: " . $e->getMessage());
    }
}

// Set document title
$document_title = 'Registration Card - ' . ($reservation['booking_code'] ?? 'N/A');

// Include header
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($document_title); ?></title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background: white;
            padding: 20px;
        }
        
        .registration-card {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border: 2px solid #333;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            border-bottom: 3px double #333;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        
        .header h1 {
            font-size: 28px;
            font-weight: bold;
            margin: 0;
            text-transform: uppercase;
        }
        
        .header h2 {
            font-size: 18px;
            margin: 5px 0 0;
            color: #666;
        }
        
        .registration-title {
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            text-transform: uppercase;
            border: 2px solid #333;
            padding: 10px;
            margin-bottom: 20px;
            background: #f0f0f0;
        }
        
        .info-section {
            margin-bottom: 20px;
        }
        
        .info-section h3 {
            font-size: 16px;
            font-weight: bold;
            border-bottom: 1px solid #333;
            padding-bottom: 5px;
            margin-bottom: 10px;
            text-transform: uppercase;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 8px;
        }
        
        .info-label {
            width: 150px;
            font-weight: bold;
        }
        
        .info-value {
            flex: 1;
            border-bottom: 1px dotted #999;
            padding-bottom: 3px;
        }
        
        .signature-section {
            margin-top: 40px;
            margin-bottom: 20px;
        }
        
        .signature-line {
            border-bottom: 2px solid #333;
            width: 300px;
            margin-top: 10px;
        }
        
        .footer {
            margin-top: 40px;
            font-size: 12px;
            text-align: center;
            color: #666;
            border-top: 1px solid #ccc;
            padding-top: 10px;
        }
        
        .terms {
            font-size: 11px;
            margin-top: 30px;
            padding: 10px;
            border: 1px solid #ccc;
            background: #f9f9f9;
        }
        
        .badge-paid {
            background: #28a745;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 14px;
            font-weight: bold;
        }
        
        .badge-unpaid {
            background: #dc3545;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 14px;
            font-weight: bold;
        }
        
        @media print {
            body {
                padding: 0;
            }
            .no-print {
                display: none;
            }
            .registration-card {
                border: none;
            }
        }
    </style>
</head>
<body>
    <div class="registration-card">
        <!-- Header -->
        <div class="header">
            <h1><?php echo htmlspecialchars($resort['resort_name'] ?? 'Ruhondo Beach Resort'); ?></h1>
            <h2><?php echo htmlspecialchars($resort['resort_address'] ?? ''); ?></h2>
            <p>
                Tel: <?php echo htmlspecialchars($resort['resort_phone'] ?? '+250 788 888 888'); ?> | 
                Email: <?php echo htmlspecialchars($resort['resort_email'] ?? 'info@ruhondo.com'); ?>
            </p>
        </div>

        <!-- Registration Title -->
        <div class="registration-title">
            Guest Registration Card
        </div>

        <!-- Guest Information -->
        <div class="info-section">
            <h3>Guest Information</h3>
            <div class="info-row">
                <span class="info-label">Full Name:</span>
                <span class="info-value"><?php echo escape_html(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Email:</span>
                <span class="info-value"><?php echo escape_html($reservation['email'] ?: 'N/A'); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Phone:</span>
                <span class="info-value"><?php echo escape_html($reservation['phone'] ?: 'N/A'); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Address:</span>
                <span class="info-value">
                    <?php 
                    $address = array_filter([
                        $reservation['address'] ?? '',
                        $reservation['city'] ?? '',
                        $reservation['country'] ?? ''
                    ]);
                    echo escape_html(implode(', ', $address)) ?: 'N/A';
                    ?>
                </span>
            </div>
            <div class="info-row">
                <span class="info-label">Nationality:</span>
                <span class="info-value"><?php echo escape_html($reservation['nationality'] ?: 'N/A'); ?></span>
            </div>
        </div>

        <!-- Identification -->
        <div class="info-section">
            <h3>Identification</h3>
            <div class="info-row">
                <span class="info-label">ID Type:</span>
                <span class="info-value"><?php echo !empty($reservation['id_type']) ? ucfirst(str_replace('_', ' ', $reservation['id_type'])) : 'Not provided'; ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">ID Number:</span>
                <span class="info-value"><?php echo escape_html($reservation['id_number'] ?: 'Not provided'); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Expiry Date:</span>
                <span class="info-value"><?php echo !empty($reservation['id_expiry']) ? date('M d, Y', strtotime($reservation['id_expiry'])) : 'Not provided'; ?></span>
            </div>
        </div>

        <!-- Reservation Details -->
        <div class="info-section">
            <h3>Reservation Details</h3>
            <div class="info-row">
                <span class="info-label">Booking Code:</span>
                <span class="info-value"><strong><?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?></strong></span>
            </div>
            <div class="info-row">
                <span class="info-label">Room Number:</span>
                <span class="info-value"><?php echo htmlspecialchars($reservation['room_number'] ?: 'Not assigned'); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Room Type:</span>
                <span class="info-value"><?php echo htmlspecialchars($reservation['type_name'] ?? 'N/A'); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Check-in Date:</span>
                <span class="info-value"><?php echo isset($reservation['check_in_date']) ? date('M d, Y', strtotime($reservation['check_in_date'])) : 'N/A'; ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Check-out Date:</span>
                <span class="info-value"><?php echo isset($reservation['check_out_date']) ? date('M d, Y', strtotime($reservation['check_out_date'])) : 'N/A'; ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Number of Nights:</span>
                <span class="info-value"><?php echo $reservation['nights'] ?? 0; ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Number of Guests:</span>
                <span class="info-value">
                    <?php echo $reservation['adults'] ?? 0; ?> Adult(s)
                    <?php if (!empty($reservation['children']) && $reservation['children'] > 0): ?>
                        , <?php echo $reservation['children']; ?> Child(ren)
                    <?php endif; ?>
                </span>
            </div>
        </div>

        <!-- Payment Summary -->
        <div class="info-section">
            <h3>Payment Summary</h3>
            <div class="info-row">
                <span class="info-label">Total Amount:</span>
                <span class="info-value"><?php echo format_currency($reservation['total_amount'] ?? 0); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Paid Amount:</span>
                <span class="info-value"><?php echo format_currency($reservation['paid_amount'] ?? 0); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Balance Due:</span>
                <span class="info-value">
                    <?php echo format_currency($reservation['balance'] ?? 0); ?>
                    <?php if (!empty($reservation['balance']) && $reservation['balance'] > 0): ?>
                        <span class="badge-unpaid">UNPAID</span>
                    <?php else: ?>
                        <span class="badge-paid">PAID</span>
                    <?php endif; ?>
                </span>
            </div>
        </div>

        <!-- Special Requests -->
        <?php if (!empty($reservation['special_requests'])): ?>
        <div class="info-section">
            <h3>Special Requests</h3>
            <p><?php echo nl2br(escape_html($reservation['special_requests'])); ?></p>
        </div>
        <?php endif; ?>

        <!-- Terms and Conditions -->
        <div class="terms">
            <h5>Terms and Conditions</h5>
            <p>By signing this registration card, I agree to the following:</p>
            <ol>
                <li>I agree to pay all charges incurred during my stay.</li>
                <li>I understand that check-out time is <?php echo substr($resort['checkout_time'] ?? DEFAULT_CHECKOUT_TIME, 0, 5); ?>.</li>
                <li>I am responsible for any damage to the room or its contents caused by me or my guests.</li>
                <li>I agree not to smoke in non-smoking rooms and understand that a cleaning fee will be charged if violated.</li>
                <li>The hotel is not responsible for lost or stolen items.</li>
                <li>I consent to the collection and processing of my personal data as per privacy policy.</li>
            </ol>
        </div>

        <!-- Signature -->
        <div class="signature-section">
            <div class="row">
                <div class="col-6">
                    <p>Guest Signature: ______________________________</p>
                </div>
                <div class="col-6">
                    <p>Date: <?php echo date('Y-m-d'); ?></p>
                </div>
            </div>
            <div class="row mt-4">
                <div class="col-6">
                    <p>Received by: <?php echo escape_html(($reservation['created_by_first'] ?? '') . ' ' . ($reservation['created_by_last'] ?? '')); ?></p>
                </div>
                <div class="col-6">
                    <p>Time: <?php echo date('H:i'); ?></p>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <div class="footer">
            <p>This is a computer generated registration card. No signature is required if printed electronically.</p>
            <p><?php echo htmlspecialchars($resort['resort_name'] ?? 'Ruhondo Beach Resort'); ?> - Your Home Away from Home</p>
        </div>
    </div>

    <!-- Print Button (only visible on screen) -->
    <div class="text-center mt-4 no-print">
        <button onclick="window.print()" class="btn btn-primary">
            <i class="fas fa-print"></i> Print Registration Card
        </button>
        <button onclick="window.close()" class="btn btn-secondary">
            <i class="fas fa-times"></i> Close
        </button>
    </div>

    <script>
        // Auto-print if requested
        <?php if (isset($_GET['print']) && $_GET['print'] == 1): ?>
        window.onload = function() {
            setTimeout(function() {
                window.print();
            }, 500);
        }
        <?php endif; ?>
    </script>
</body>
</html>