<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Complete Check-out Process
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 3) . '/config/config.php';
require_once dirname(__DIR__, 3) . '/config/constants.php';
require_once dirname(__DIR__, 3) . '/config/database.php';
require_once dirname(__DIR__, 3) . '/config/helpers.php';
require_once dirname(__DIR__, 3) . '/config/auth.php';
require_once dirname(__DIR__, 3) . '/config/csrf.php';
require_once dirname(__DIR__, 3) . '/config/mailer.php';

// Require authentication and permission
require_auth();
require_permission('reservations.checkout');

// Set page title
$page_title = 'Check-out Complete';

// Get current user
$current_user = current_user();

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    process_checkout();
    exit;
}

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

if (!$reservation_id) {
    set_flash_message('danger', 'Invalid reservation ID');
    redirect('index.php');
}

// Get reservation data
$reservation = db_fetch_one("
    SELECT 
        r.*,
        g.guest_id, g.first_name, g.last_name, g.email,
        rt.type_name,
        rm.room_number,
        DATEDIFF(r.check_out_date, r.check_in_date) as nights,
        (SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
         WHERE reservation_id = r.reservation_id AND charge_type != 'payment' AND is_voided = 0) as total_charges,
        (SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
         WHERE reservation_id = r.reservation_id AND charge_type = 'payment' AND is_voided = 0) as total_payments
    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]);

if (!$reservation) {
    set_flash_message('danger', 'Reservation not found');
    redirect('index.php');
}

$balance = $reservation['total_charges'] - $reservation['total_payments'];

// Include header
require_once dirname(__DIR__, 3) . '/views/partials/header.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-out Complete</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('reservations/dashboard.php'); ?>">Reservations</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Check-out</a></li>
                    <li class="breadcrumb-item active">Complete</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Success Message -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-check-circle mr-1"></i>
                            Check-out Successful
                        </h3>
                    </div>
                    
                    <div class="card-body text-center">
                        <i class="fas fa-check-circle fa-5x text-success mb-4"></i>
                        
                        <h3>Thank You for Staying with Us!</h3>
                        
                        <p class="lead">
                            <?php echo escape_html($reservation['first_name'] . ' ' . $reservation['last_name']); ?> has been checked out successfully.
                        </p>
                        
                        <div class="card card-outline card-success mt-4">
                            <div class="card-header">
                                <h4 class="card-title">Check-out Summary</h4>
                            </div>
                            <div class="card-body">
                                <table class="table table-bordered">
                                    <tr>
                                        <th style="width: 200px;">Booking Code:</th>
                                        <td><strong><?php echo $reservation['booking_code']; ?></strong></td>
                                    </tr>
                                    <tr>
                                        <th>Guest Name:</th>
                                        <td><?php echo escape_html($reservation['first_name'] . ' ' . $reservation['last_name']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Room:</th>
                                        <td>
                                            <span class="badge badge-info badge-lg">Room <?php echo $reservation['room_number']; ?></span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Check-in Date:</th>
                                        <td><?php echo format_date($reservation['check_in_date']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Check-out Date:</th>
                                        <td><?php echo format_date($reservation['check_out_date']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Length of Stay:</th>
                                        <td><?php echo $reservation['nights']; ?> nights</td>
                                    </tr>
                                    <tr>
                                        <th>Total Charges:</th>
                                        <td><?php echo format_currency($reservation['total_charges']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Payments Received:</th>
                                        <td class="text-success"><?php echo format_currency($reservation['total_payments']); ?></td>
                                    </tr>
                                    <tr class="<?php echo $balance > 0 ? 'table-danger' : 'table-success'; ?>">
                                        <th>Final Balance:</th>
                                        <td>
                                            <strong><?php echo format_currency($balance); ?></strong>
                                            <?php if ($balance > 0): ?>
                                                <br><small class="text-danger">Please collect payment</small>
                                            <?php elseif ($balance < 0): ?>
                                                <br><small class="text-warning">Credit balance - refund due</small>
                                            <?php else: ?>
                                                <br><small>Settled in full</small>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Checked out by:</th>
                                        <td><?php echo escape_html($current_user['first_name'] . ' ' . $current_user['last_name']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Time:</th>
                                        <td><?php echo date(DATETIME_FORMAT); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="mt-4">
                            <a href="../folio/view.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-primary btn-lg mr-2">
                                <i class="fas fa-file-invoice mr-1"></i> View Final Invoice
                            </a>
                            
                            <a href="../documents/invoice-pdf.php?id=<?php echo $reservation_id; ?>" target="_blank" class="btn btn-info btn-lg mr-2">
                                <i class="fas fa-file-pdf mr-1"></i> Download Invoice
                            </a>
                            
                            <a href="index.php" class="btn btn-success btn-lg">
                                <i class="fas fa-sign-out-alt mr-1"></i> Next Check-out
                            </a>
                        </div>

                        <!-- Feedback Section -->
                        <div class="mt-5">
                            <h5>Guest Feedback</h5>
                            <div class="row">
                                <div class="col-md-6 offset-md-3">
                                    <div class="rating">
                                        <span class="star" data-rating="1">☆</span>
                                        <span class="star" data-rating="2">☆</span>
                                        <span class="star" data-rating="3">☆</span>
                                        <span class="star" data-rating="4">☆</span>
                                        <span class="star" data-rating="5">☆</span>
                                    </div>
                                    <div class="form-group mt-3">
                                        <textarea class="form-control" rows="2" placeholder="Leave feedback about the stay..."></textarea>
                                    </div>
                                    <button class="btn btn-sm btn-primary" onclick="submitFeedback()">
                                        Submit Feedback
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Email Receipt -->
                        <?php if (isset($_GET['email']) && $_GET['email'] == 1): ?>
                        <div class="alert alert-info mt-4">
                            <i class="fas fa-envelope mr-2"></i>
                            Receipt has been sent to <?php echo $reservation['email']; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
function submitFeedback() {
    alert('Thank you for your feedback!');
}

// Star rating
$('.star').hover(function() {
    const rating = $(this).data('rating');
    $('.star').each(function() {
        if ($(this).data('rating') <= rating) {
            $(this).text('★').addClass('text-warning');
        } else {
            $(this).text('☆').removeClass('text-warning');
        }
    });
}, function() {
    $('.star').text('☆').removeClass('text-warning');
});

$('.star').click(function() {
    const rating = $(this).data('rating');
    alert('Thank you for rating your stay ' + rating + ' stars!');
});

// Auto-print invoice if requested
<?php if (isset($_GET['print']) && $_GET['print'] == 1): ?>
$(document).ready(function() {
    window.open('../documents/invoice-pdf.php?id=<?php echo $reservation_id; ?>', '_blank');
});
<?php endif; ?>
</script>

<style>
.badge-lg {
    font-size: 1.1rem;
    padding: 0.5rem 1rem;
}
.rating {
    font-size: 2rem;
    cursor: pointer;
}
.star {
    margin: 0 2px;
    transition: color 0.2s;
}
.star.text-warning {
    color: #ffc107;
}
</style>

<?php
/**
 * Process check-out form submission
 */
function process_checkout() {
    global $current_user;
    
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        set_flash_message('danger', 'Invalid security token');
        redirect('index.php');
    }
    
    $reservation_id = (int)($_POST['reservation_id'] ?? 0);
    $email_receipt = isset($_POST['email_receipt']);
    $print_invoice = isset($_POST['print_invoice']);
    $feedback = sanitize_input($_POST['feedback'] ?? '');
    
    if (!$reservation_id) {
        set_flash_message('danger', 'Invalid reservation ID');
        redirect('index.php');
    }
    
    // Get reservation
    $reservation = db_fetch_one("SELECT * FROM reservations WHERE reservation_id = ?", [$reservation_id]);
    
    if (!$reservation) {
        set_flash_message('danger', 'Reservation not found');
        redirect('index.php');
    }
    
    try {
        begin_transaction();
        
        // Update reservation status
        db_update('reservations', [
            'booking_status' => 'checked_out',
            'actual_checkout_time' => date('H:i:s')
        ], 'reservation_id = ?', [$reservation_id]);
        
        // Update room status
        if ($reservation['room_id']) {
            db_update('rooms', [
                'status' => 'available',
                'housekeeping_status' => 'dirty'
            ], 'room_id = ?', [$reservation['room_id']]);
            
            // Create housekeeping task
            $task_code = 'HK-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
            
            db_insert('hk_tasks', [
                'task_code' => $task_code,
                'room_id' => $reservation['room_id'],
                'task_type' => 'cleaning',
                'priority' => 'high',
                'status' => 'pending',
                'notes' => 'Post-checkout cleaning required',
                'created_by' => $current_user['user_id']
            ]);
        }
        
        // Create guest activity record
        db_insert('guest_activity', [
            'guest_id' => $reservation['guest_id'],
            'activity_type' => 'checkout',
            'description' => "Guest checked out from room " . get_room_number($reservation['room_id']),
            'reference_id' => $reservation_id,
            'reference_type' => 'reservation',
            'created_by' => $current_user['user_id']
        ]);
        
        // Save feedback if provided
        if (!empty($feedback)) {
            db_insert('guest_activity', [
                'guest_id' => $reservation['guest_id'],
                'activity_type' => 'feedback',
                'description' => "Guest feedback: $feedback",
                'reference_id' => $reservation_id,
                'reference_type' => 'reservation',
                'created_by' => $current_user['user_id']
            ]);
        }
        
        // Send email receipt
        if ($email_receipt && $reservation['email']) {
            send_checkout_receipt($reservation_id);
        }
        
        // Audit log
        audit_log($current_user['user_id'], AUDIT_CHECKOUT, 'reservations', $reservation_id, 
                 ['booking_status' => 'checked_in'], 
                 ['booking_status' => 'checked_out']);
        
        commit_transaction();
        
        // Redirect to completion page
        $redirect = 'complete.php?id=' . $reservation_id;
        if ($print_invoice) {
            $redirect .= '&print=1';
        }
        if ($email_receipt) {
            $redirect .= '&email=1';
        }
        
        set_flash_message('success', 'Check-out completed successfully');
        redirect($redirect);
        
    } catch (Exception $e) {
        rollback_transaction();
        set_flash_message('danger', 'Failed to complete check-out: ' . $e->getMessage());
        log_message("Check-out failed: " . $e->getMessage(), 'ERROR');
        redirect('start.php?id=' . $reservation_id);
    }
}

/**
 * Get room number by ID
 */
function get_room_number($room_id) {
    return db_fetch_value("SELECT room_number FROM rooms WHERE room_id = ?", [$room_id]);
}

/**
 * Send check-out receipt email
 */
function send_checkout_receipt($reservation_id) {
    $reservation = db_fetch_one("
        SELECT r.*, g.first_name, g.last_name, g.email
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        WHERE r.reservation_id = ?
    ", [$reservation_id]);
    
    if (!$reservation || !$reservation['email']) {
        return false;
    }
    
    $subject = "Your Check-out Receipt - Ruhondo Beach Resort";
    
    $body = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #28a745; color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; background: #f9f9f9; }
            .footer { margin-top: 20px; font-size: 12px; color: #666; text-align: center; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>Thank You for Staying with Us!</h2>
            </div>
            <div class='content'>
                <p>Dear {$reservation['first_name']} {$reservation['last_name']},</p>
                
                <p>Thank you for choosing Ruhondo Beach Resort. We hope you enjoyed your stay!</p>
                
                <p>Your check-out has been completed successfully. A detailed invoice is attached to this email.</p>
                
                <p>We look forward to welcoming you again soon!</p>
                
                <p>Best regards,<br>Ruhondo Beach Resort Team</p>
            </div>
            <div class='footer'>
                <p>&copy; " . date('Y') . " Ruhondo Beach Resort. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    $alt_body = "Dear {$reservation['first_name']} {$reservation['last_name']},\n\n";
    $alt_body .= "Thank you for choosing Ruhondo Beach Resort. We hope you enjoyed your stay!\n\n";
    $alt_body .= "Your check-out has been completed successfully. A detailed invoice is attached to this email.\n\n";
    $alt_body .= "We look forward to welcoming you again soon!\n\n";
    $alt_body .= "Best regards,\nRuhondo Beach Resort Team";
    
    // In production, you would generate and attach PDF invoice here
    return send_email($reservation['email'], $subject, $body, $alt_body);
}

// Include footer
require_once dirname(__DIR__, 3) . '/views/partials/footer.php';
?>