<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Cancel Reservation
 * 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.cancel');

// Set page title
$page_title = 'Cancel Reservation';

// 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
$reservation = db_fetch_one("
    SELECT r.*, 
           g.first_name, g.last_name, g.email,
           rt.type_name,
           rm.room_number
    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');
}

// Check if reservation can be cancelled
if (in_array($reservation['booking_status'], ['checked_out', 'cancelled', 'no_show'])) {
    set_flash_message('danger', 'This reservation cannot be cancelled');
    redirect('view.php?id=' . $reservation_id);
}

// Check if guest is checked in
if ($reservation['booking_status'] == 'checked_in') {
    set_flash_message('danger', 'Guest is already checked in. Please check out first.');
    redirect('view.php?id=' . $reservation_id);
}

// Handle cancellation
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $cancel_reason = sanitize_input($_POST['cancel_reason'] ?? '');
        $refund_policy = $_POST['refund_policy'] ?? '';
        $send_notification = isset($_POST['send_notification']);
        
        if (empty($cancel_reason)) {
            $error = 'Please provide a reason for cancellation';
        } else {
            try {
                begin_transaction();
                
                // Update reservation status
                $old_status = $reservation['booking_status'];
                db_update('reservations', [
                    'booking_status' => 'cancelled',
                    'cancel_reason' => $cancel_reason,
                    'cancelled_at' => date(DATETIME_FORMAT),
                    'cancelled_by' => $current_user['user_id']
                ], 'reservation_id = ?', [$reservation_id]);
                
                // Free up the room if assigned
                if ($reservation['room_id']) {
                    db_update('rooms', [
                        'status' => 'available'
                    ], 'room_id = ?', [$reservation['room_id']]);
                }
                
                // Create guest activity record
                db_insert('guest_activity', [
                    'guest_id' => $reservation['guest_id'],
                    'activity_type' => 'cancellation',
                    'description' => "Reservation cancelled: {$reservation['booking_code']} - Reason: $cancel_reason",
                    'reference_id' => $reservation_id,
                    'reference_type' => 'reservation',
                    'created_by' => $current_user['user_id']
                ]);
                
                // Send cancellation email
                if ($send_notification && $reservation['email']) {
                    $subject = "Reservation Cancelled - {$reservation['booking_code']}";
                    
                    $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: #dc3545; color: white; padding: 20px; text-align: center; }
                            .content { padding: 20px; background: #f9f9f9; }
                            .details { background: white; padding: 15px; border-radius: 5px; margin: 15px 0; }
                            .footer { margin-top: 20px; font-size: 12px; color: #666; text-align: center; }
                        </style>
                    </head>
                    <body>
                        <div class='container'>
                            <div class='header'>
                                <h2>Reservation Cancelled</h2>
                            </div>
                            <div class='content'>
                                <p>Dear {$reservation['first_name']} {$reservation['last_name']},</p>
                                
                                <p>Your reservation at <strong>Ruhondo Beach Resort</strong> has been cancelled.</p>
                                
                                <div class='details'>
                                    <h3>Booking Details:</h3>
                                    <p><strong>Booking Code:</strong> {$reservation['booking_code']}</p>
                                    <p><strong>Check-in:</strong> " . format_date($reservation['check_in_date']) . "</p>
                                    <p><strong>Check-out:</strong> " . format_date($reservation['check_out_date']) . "</p>
                                    <p><strong>Room Type:</strong> {$reservation['type_name']}</p>
                                    <p><strong>Reason:</strong> $cancel_reason</p>
                                </div>
                                
                                <p><strong>Refund Policy:</strong> $refund_policy</p>
                                
                                <p>If you have any questions, please contact us.</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 .= "Your reservation at Ruhondo Beach Resort has been cancelled.\n\n";
                    $alt_body .= "Booking Code: {$reservation['booking_code']}\n";
                    $alt_body .= "Check-in: " . format_date($reservation['check_in_date']) . "\n";
                    $alt_body .= "Check-out: " . format_date($reservation['check_out_date']) . "\n";
                    $alt_body .= "Reason: $cancel_reason\n\n";
                    $alt_body .= "Refund Policy: $refund_policy\n\n";
                    $alt_body .= "If you have any questions, please contact us.\n\n";
                    $alt_body .= "Best regards,\nRuhondo Beach Resort Team";
                    
                    send_email($reservation['email'], $subject, $body, $alt_body);
                }
                
                // Audit log
                audit_log($current_user['user_id'], AUDIT_CANCEL, 'reservations', $reservation_id, 
                         ['booking_status' => $old_status], 
                         ['booking_status' => 'cancelled', 'reason' => $cancel_reason]);
                
                commit_transaction();
                
                set_flash_message('success', 'Reservation cancelled successfully');
                redirect('view.php?id=' . $reservation_id);
                
            } catch (Exception $e) {
                rollback_transaction();
                $error = 'Failed to cancel reservation: ' . $e->getMessage();
                log_message("Cancellation failed: " . $e->getMessage(), 'ERROR');
            }
        }
    }
}

// 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">Cancel Reservation: <?php echo $reservation['booking_code']; ?></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">Reservations</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $reservation_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Cancel</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Error Messages -->
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo $error; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Cancellation Form -->
                <div class="card card-danger">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exclamation-triangle mr-1"></i>
                            Cancel Reservation
                        </h3>
                    </div>
                    
                    <form method="POST" id="cancelForm">
                        <?php echo csrf_field(); ?>
                        
                        <div class="card-body">
                            <!-- Warning Alert -->
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle mr-2"></i>
                                <strong>Warning:</strong> Cancelling a reservation will free up the room and cannot be undone.
                                Please ensure you have the guest's consent before proceeding.
                            </div>

                            <!-- Reservation Summary -->
                            <div class="card card-outline card-secondary mb-4">
                                <div class="card-header">
                                    <h3 class="card-title">Reservation Summary</h3>
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm">
                                        <tr>
                                            <th style="width: 120px;">Guest:</th>
                                            <td><?php echo escape_html($reservation['first_name'] . ' ' . $reservation['last_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Booking Code:</th>
                                            <td><strong><?php echo $reservation['booking_code']; ?></strong></td>
                                        </tr>
                                        <tr>
                                            <th>Dates:</th>
                                            <td><?php echo format_date($reservation['check_in_date']); ?> to <?php echo format_date($reservation['check_out_date']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Room Type:</th>
                                            <td><?php echo $reservation['type_name']; ?></td>
                                        </tr>
                                        <?php if ($reservation['room_number']): ?>
                                        <tr>
                                            <th>Assigned Room:</th>
                                            <td>Room <?php echo $reservation['room_number']; ?></td>
                                        </tr>
                                        <?php endif; ?>
                                        <tr>
                                            <th>Total Amount:</th>
                                            <td><?php echo format_currency($reservation['total_amount']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Paid Amount:</th>
                                            <td><?php echo format_currency($reservation['paid_amount']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Current Status:</th>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $reservation['booking_status'] == 'confirmed' ? 'success' : 
                                                        ($reservation['booking_status'] == 'checked_in' ? 'info' : 
                                                        ($reservation['booking_status'] == 'pending' ? 'warning' : 'secondary'));
                                                ?>">
                                                    <?php echo ucfirst($reservation['booking_status']); ?>
                                                </span>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>

                            <!-- Cancellation Form -->
                            <div class="form-group">
                                <label for="cancel_reason">Reason for Cancellation <span class="text-danger">*</span></label>
                                <select class="form-control" id="cancel_reason" name="cancel_reason" required>
                                    <option value="">Select a reason</option>
                                    <option value="Guest request">Guest request</option>
                                    <option value="Change of plans">Change of plans</option>
                                    <option value="No-show">No-show</option>
                                    <option value="Payment issue">Payment issue</option>
                                    <option value="Duplicate booking">Duplicate booking</option>
                                    <option value="Hotel unable to accommodate">Hotel unable to accommodate</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>

                            <div class="form-group" id="other_reason_group" style="display: none;">
                                <label for="other_reason">Please specify</label>
                                <input type="text" class="form-control" id="other_reason">
                            </div>

                            <div class="form-group">
                                <label for="refund_policy">Refund Policy</label>
                                <select class="form-control" id="refund_policy" name="refund_policy">
                                    <option value="Full refund">Full refund</option>
                                    <option value="Partial refund (cancellation fee applied)">Partial refund (cancellation fee applied)</option>
                                    <option value="No refund">No refund</option>
                                    <option value="Credit for future stay">Credit for future stay</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="send_notification" name="send_notification" checked>
                                    <label class="custom-control-label" for="send_notification">
                                        Send cancellation notification to guest
                                    </label>
                                </div>
                            </div>

                            <?php if ($reservation['paid_amount'] > 0): ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>Note:</strong> This guest has made a payment of <?php echo format_currency($reservation['paid_amount']); ?>.
                                Please process any refunds separately through the billing module.
                            </div>
                            <?php endif; ?>

                            <?php if ($reservation['booking_status'] == 'checked_in'): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle mr-2"></i>
                                <strong>Warning:</strong> This guest is currently checked in. Please check them out first.
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-danger" id="submitBtn">
                                <i class="fas fa-times-circle mr-1"></i> Confirm Cancellation
                            </button>
                            <a href="view.php?id=<?php echo $reservation_id; ?>" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Go Back
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Cancellation Policy -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle mr-1"></i>
                            Cancellation Policy
                        </h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-clock text-info mr-2"></i>
                                <strong>48+ hours before check-in:</strong> Full refund
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-clock text-warning mr-2"></i>
                                <strong>24-48 hours before check-in:</strong> 50% refund
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-clock text-danger mr-2"></i>
                                <strong>Less than 24 hours:</strong> No refund
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-ban text-danger mr-2"></i>
                                <strong>No-show:</strong> Full charge
                            </li>
                        </ul>
                        
                        <hr>
                        
                        <p class="text-muted mb-0">
                            <i class="fas fa-calculator mr-1"></i>
                            Days until check-in: 
                            <?php 
                            $days_until = (strtotime($reservation['check_in_date']) - time()) / 86400;
                            echo round($days_until, 1);
                            ?>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Show/hide other reason field
    $('#cancel_reason').on('change', function() {
        if ($(this).val() === 'Other') {
            $('#other_reason_group').show();
            $('#other_reason').prop('required', true);
        } else {
            $('#other_reason_group').hide();
            $('#other_reason').prop('required', false);
        }
    });
    
    // Form validation
    $('#cancelForm').on('submit', function(e) {
        const reason = $('#cancel_reason').val();
        let finalReason = reason;
        
        if (reason === 'Other') {
            finalReason = $('#other_reason').val();
            if (!finalReason) {
                e.preventDefault();
                alert('Please specify the reason for cancellation');
                return false;
            }
        }
        
        // Confirm cancellation
        if (!confirm('Are you absolutely sure you want to cancel this reservation? This action cannot be undone.')) {
            e.preventDefault();
            return false;
        }
        
        // Set the final reason
        if (reason === 'Other') {
            $('<input>').attr({
                type: 'hidden',
                name: 'cancel_reason',
                value: finalReason
            }).appendTo('#cancelForm');
        }
        
        return true;
    });
    
    // Warn if guest has paid
    <?php if ($reservation['paid_amount'] > 0): ?>
    $('#submitBtn').on('click', function(e) {
        if (!confirm('This guest has made a payment. Have you processed the refund?')) {
            e.preventDefault();
        }
    });
    <?php endif; ?>
});
</script>

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