<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Start 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 authentication and permission
require_auth();
require_permission('reservations.checkout');

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

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

// 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 with folio summary
$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,
        rt.type_name, rt.type_code,
        rm.room_number, rm.floor,
        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,
        (SELECT COUNT(*) FROM folio_charges 
         WHERE reservation_id = r.reservation_id AND charge_type != 'payment' AND is_voided = 0) as charge_count
    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 = ? AND r.booking_status = 'checked_in'
", [$reservation_id]);

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

// Calculate current balance
$balance = $reservation['total_charges'] - $reservation['total_payments'];

// Get folio charges for display
$folio_charges = db_fetch_all("
    SELECT fc.*, u.first_name, u.last_name
    FROM folio_charges fc
    LEFT JOIN users u ON fc.posted_by = u.user_id
    WHERE fc.reservation_id = ? AND fc.is_voided = 0
    ORDER BY fc.posted_at
", [$reservation_id]);

// Get payment methods for quick payment
$payment_methods = db_fetch_all("SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY sort_order");

// 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 Process</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">Process</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <!-- Main Column -->
            <div class="col-md-8">
                <!-- Check-out Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-out-alt mr-1"></i>
                            Check-out Details
                        </h3>
                    </div>
                    
                    <form action="complete.php" method="POST" id="checkoutForm">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                        
                        <div class="card-body">
                            <!-- Guest Summary -->
                            <div class="callout callout-info">
                                <h5>Guest Information</h5>
                                <div class="row">
                                    <div class="col-sm-6">
                                        <strong>Name:</strong> <?php echo escape_html($reservation['first_name'] . ' ' . $reservation['last_name']); ?><br>
                                        <strong>Room:</strong> <?php echo $reservation['room_number']; ?><br>
                                        <strong>Check-in:</strong> <?php echo format_date($reservation['check_in_date']); ?>
                                    </div>
                                    <div class="col-sm-6">
                                        <strong>Booking Code:</strong> <?php echo $reservation['booking_code']; ?><br>
                                        <strong>Check-out:</strong> <?php echo format_date($reservation['check_out_date']); ?><br>
                                        <strong>Nights:</strong> <?php echo $reservation['nights']; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Folio Summary -->
                            <div class="card card-outline card-primary">
                                <div class="card-header">
                                    <h3 class="card-title">Folio Summary</h3>
                                    <div class="card-tools">
                                        <a href="../folio/view.php?reservation_id=<?php echo $reservation_id; ?>" target="_blank" class="btn btn-sm btn-primary">
                                            <i class="fas fa-external-link-alt"></i> Full Folio
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body p-0">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Description</th>
                                                <th class="text-right">Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $subtotal = 0;
                                            foreach ($folio_charges as $charge): 
                                                $subtotal += $charge['amount'];
                                            ?>
                                            <tr class="<?php echo $charge['charge_type'] == 'payment' ? 'table-success' : ''; ?>">
                                                <td><?php echo format_date($charge['posted_at'], 'M d, H:i'); ?></td>
                                                <td>
                                                    <?php echo escape_html($charge['description']); ?>
                                                    <br>
                                                    <small class="text-muted">By: <?php echo $charge['first_name']; ?></small>
                                                </td>
                                                <td class="text-right">
                                                    <?php if ($charge['charge_type'] == 'payment'): ?>
                                                        <span class="text-success">-<?php echo format_currency($charge['amount']); ?></span>
                                                    <?php else: ?>
                                                        <span><?php echo format_currency($charge['amount']); ?></span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <th colspan="2" class="text-right">Total Charges:</th>
                                                <th class="text-right"><?php echo format_currency($reservation['total_charges']); ?></th>
                                            </tr>
                                            <tr>
                                                <th colspan="2" class="text-right">Payments:</th>
                                                <th class="text-right text-success">- <?php echo format_currency($reservation['total_payments']); ?></th>
                                            </tr>
                                            <tr class="<?php echo $balance > 0 ? 'table-danger' : 'table-success'; ?>">
                                                <th colspan="2" class="text-right">Balance Due:</th>
                                                <th class="text-right">
                                                    <strong><?php echo format_currency($balance); ?></strong>
                                                </th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>

                            <!-- Quick Payment (if balance > 0) -->
                            <?php if ($balance > 0): ?>
                            <div class="card card-outline card-success">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="fas fa-credit-card mr-1"></i>
                                        Quick Payment
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="payment_amount">Payment Amount</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                                                    </div>
                                                    <input type="number" class="form-control" id="payment_amount" 
                                                           value="<?php echo $balance; ?>" step="0.01" min="0" max="<?php echo $balance; ?>">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="payment_method">Payment Method</label>
                                                <select class="form-control" id="payment_method">
                                                    <?php foreach ($payment_methods as $method): ?>
                                                        <option value="<?php echo $method['payment_method_id']; ?>">
                                                            <?php echo $method['method_name']; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-success" onclick="processPayment()">
                                        <i class="fas fa-check-circle"></i> Process Payment
                                    </button>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Check-out Options -->
                            <div class="card card-outline card-secondary">
                                <div class="card-header">
                                    <h3 class="card-title">Check-out Options</h3>
                                </div>
                                <div class="card-body">
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="email_receipt" name="email_receipt" checked>
                                            <label class="custom-control-label" for="email_receipt">
                                                Email receipt to guest
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="print_invoice" name="print_invoice" checked>
                                            <label class="custom-control-label" for="print_invoice">
                                                Print final invoice
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="update_guest_history" name="update_guest_history" checked>
                                            <label class="custom-control-label" for="update_guest_history">
                                                Update guest history
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="feedback">Guest Feedback (Optional)</label>
                                        <textarea class="form-control" id="feedback" name="feedback" rows="2" 
                                                  placeholder="Any comments about their stay?"></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Balance Alert -->
                            <?php if ($balance > 0): ?>
                                <div class="alert alert-danger">
                                    <i class="fas fa-exclamation-triangle mr-2"></i>
                                    <strong>Outstanding Balance: <?php echo format_currency($balance); ?></strong>
                                    <br>
                                    Please collect payment before completing check-out.
                                </div>
                            <?php else: ?>
                                <div class="alert alert-success">
                                    <i class="fas fa-check-circle mr-2"></i>
                                    <strong>Balance Paid in Full</strong>
                                    <br>
                                    Ready to complete check-out.
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning" <?php echo $balance > 0 ? 'disabled' : ''; ?> id="checkoutBtn">
                                <i class="fas fa-sign-out-alt mr-1"></i> Complete Check-out
                            </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">
                <!-- Room Information -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-door-open mr-1"></i>
                            Room Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Room Number:</th>
                                <td><span class="badge badge-info badge-lg"><?php echo $reservation['room_number']; ?></span></td>
                            </tr>
                            <tr>
                                <th>Floor:</th>
                                <td><?php echo $reservation['floor']; ?></td>
                            </tr>
                            <tr>
                                <th>Room Type:</th>
                                <td><?php echo $reservation['type_name']; ?></td>
                            </tr>
                        </table>
                        
                        <hr>
                        
                        <h6>Housekeeping Status</h6>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-success" onclick="setHKStatus('clean')">Clean</button>
                            <button type="button" class="btn btn-outline-warning" onclick="setHKStatus('dirty')">Dirty</button>
                            <button type="button" class="btn btn-outline-info" onclick="setHKStatus('inspected')">Inspected</button>
                        </div>
                    </div>
                </div>

                <!-- 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 escape_html($reservation['first_name'] . ' ' . $reservation['last_name']); ?></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td><?php echo $reservation['email'] ?: 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td><?php echo $reservation['phone'] ?: 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Address:</th>
                                <td>
                                    <?php 
                                    $address_parts = array_filter([
                                        $reservation['address'],
                                        $reservation['city'],
                                        $reservation['country']
                                    ]);
                                    echo $address_parts ? implode(', ', $address_parts) : 'Not provided';
                                    ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Quick Stats -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar mr-1"></i>
                            Stay Statistics
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-info elevation-1">
                                <i class="fas fa-clock"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Length of Stay</span>
                                <span class="info-box-number"><?php echo $reservation['nights']; ?> nights</span>
                            </div>
                        </div>
                        
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-success elevation-1">
                                <i class="fas fa-wallet"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Average per Night</span>
                                <span class="info-box-number">
                                    <?php 
                                    $avg = $reservation['nights'] > 0 ? $reservation['total_charges'] / $reservation['nights'] : 0;
                                    echo format_currency($avg);
                                    ?>
                                </span>
                            </div>
                        </div>
                        
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-warning elevation-1">
                                <i class="fas fa-receipt"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Total Transactions</span>
                                <span class="info-box-number"><?php echo $reservation['charge_count']; ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success">
                <h5 class="modal-title">Process Payment</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="paymentForm">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label>Amount</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                            </div>
                            <input type="number" class="form-control" name="amount" id="modal_amount" 
                                   value="<?php echo $balance; ?>" step="0.01" readonly>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Payment Method</label>
                        <select class="form-control" name="payment_method_id" id="modal_method" required>
                            <?php foreach ($payment_methods as $method): ?>
                                <option value="<?php echo $method['payment_method_id']; ?>">
                                    <?php echo $method['method_name']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Reference (Optional)</label>
                        <input type="text" class="form-control" name="reference" placeholder="Transaction ID / Check #">
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Process Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Enable/disable checkout button based on balance
    function updateCheckoutButton() {
        const balance = <?php echo $balance; ?>;
        const checkoutBtn = $('#checkoutBtn');
        
        if (balance <= 0) {
            checkoutBtn.prop('disabled', false);
        } else {
            checkoutBtn.prop('disabled', true);
        }
    }
    
    // Process payment
    window.processPayment = function() {
        const amount = $('#payment_amount').val();
        const method = $('#payment_method').val();
        
        if (amount <= 0) {
            alert('Please enter a valid amount');
            return;
        }
        
        $('#modal_amount').val(amount);
        $('#modal_method').val(method);
        $('#paymentModal').modal('show');
    };
    
    // Submit payment
    $('#paymentForm').on('submit', function(e) {
        e.preventDefault();
        
        $.post('<?php echo base_url('api/process-payment.php'); ?>', $(this).serialize(), function(response) {
            if (response.status === 'success') {
                $('#paymentModal').modal('hide');
                location.reload();
            } else {
                alert('Payment failed: ' + response.message);
            }
        }).fail(function() {
            alert('Failed to process payment');
        });
    });
    
    // Set housekeeping status
    window.setHKStatus = function(status) {
        $.post('<?php echo base_url('api/update-room-status.php'); ?>', {
            room_id: <?php echo $reservation['room_id']; ?>,
            housekeeping_status: status,
            csrf_token: '<?php echo csrf_token(); ?>'
        }, function(response) {
            if (response.status === 'success') {
                alert('Housekeeping status updated');
            } else {
                alert('Failed to update status');
            }
        });
    };
});

// Confirm check-out with outstanding balance
$('#checkoutForm').on('submit', function(e) {
    const balance = <?php echo $balance; ?>;
    
    if (balance > 0) {
        e.preventDefault();
        alert('Please collect outstanding balance before check-out');
        return false;
    }
    
    return confirm('Complete check-out for this guest?');
});
</script>

<style>
.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;
}
.badge-lg {
    font-size: 1rem;
    padding: 0.4rem 0.8rem;
}
</style>

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