<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Rate Plans Management
 * 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('rates.manage');

// Set page title
$page_title = 'Rate Plans Management';

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

// Get filter parameters
$room_type_id = isset($_GET['room_type_id']) ? (int)$_GET['room_type_id'] : null;
$season_id = isset($_GET['season_id']) ? (int)$_GET['season_id'] : null;
$status = $_GET['status'] ?? '';

// Handle form submissions
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'create':
                $plan_code = strtoupper(sanitize_input($_POST['plan_code'] ?? ''));
                $plan_name = sanitize_input($_POST['plan_name'] ?? '');
                $description = sanitize_input($_POST['description'] ?? '');
                $room_type_id = (int)($_POST['room_type_id'] ?? 0);
                $season_id = !empty($_POST['season_id']) ? (int)$_POST['season_id'] : null;
                $base_rate = (float)($_POST['base_rate'] ?? 0);
                $adjustment_type = sanitize_input($_POST['adjustment_type'] ?? 'fixed');
                $adjustment_value = (float)($_POST['adjustment_value'] ?? 0);
                $min_nights = (int)($_POST['min_nights'] ?? 1);
                $max_nights = !empty($_POST['max_nights']) ? (int)$_POST['max_nights'] : null;
                $is_refundable = isset($_POST['is_refundable']) ? 1 : 0;
                $cancellation_hours = (int)($_POST['cancellation_hours'] ?? 24);
                
                if (empty($plan_code)) {
                    $error = 'Plan code is required';
                } elseif (empty($plan_name)) {
                    $error = 'Plan name is required';
                } elseif (!$room_type_id) {
                    $error = 'Room type is required';
                } elseif ($base_rate <= 0) {
                    $error = 'Base rate must be greater than 0';
                } elseif ($min_nights < 1) {
                    $error = 'Minimum nights must be at least 1';
                } elseif ($max_nights && $max_nights < $min_nights) {
                    $error = 'Maximum nights must be greater than minimum nights';
                } elseif ($cancellation_hours < 0) {
                    $error = 'Cancellation hours cannot be negative';
                } else {
                    // Check if code exists
                    $exists = db_fetch_value("SELECT COUNT(*) FROM rate_plans WHERE plan_code = ?", [$plan_code]);
                    if ($exists) {
                        $error = 'Plan code already exists';
                    } else {
                        try {
                            db_insert('rate_plans', [
                                'plan_code' => $plan_code,
                                'plan_name' => $plan_name,
                                'description' => $description ?: null,
                                'room_type_id' => $room_type_id,
                                'season_id' => $season_id,
                                'base_rate' => $base_rate,
                                'adjustment_type' => $adjustment_type,
                                'adjustment_value' => $adjustment_value,
                                'min_nights' => $min_nights,
                                'max_nights' => $max_nights,
                                'is_refundable' => $is_refundable,
                                'cancellation_hours' => $cancellation_hours,
                                'is_active' => 1
                            ]);
                            
                            $message = 'Rate plan created successfully';
                            audit_log($current_user['user_id'], AUDIT_CREATE, 'rate_plans', null, null, $_POST);
                            
                        } catch (Exception $e) {
                            $error = 'Failed to create rate plan: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'edit':
                $plan_id = (int)($_POST['plan_id'] ?? 0);
                $plan_code = strtoupper(sanitize_input($_POST['plan_code'] ?? ''));
                $plan_name = sanitize_input($_POST['plan_name'] ?? '');
                $description = sanitize_input($_POST['description'] ?? '');
                $room_type_id = (int)($_POST['room_type_id'] ?? 0);
                $season_id = !empty($_POST['season_id']) ? (int)$_POST['season_id'] : null;
                $base_rate = (float)($_POST['base_rate'] ?? 0);
                $adjustment_type = sanitize_input($_POST['adjustment_type'] ?? 'fixed');
                $adjustment_value = (float)($_POST['adjustment_value'] ?? 0);
                $min_nights = (int)($_POST['min_nights'] ?? 1);
                $max_nights = !empty($_POST['max_nights']) ? (int)$_POST['max_nights'] : null;
                $is_refundable = isset($_POST['is_refundable']) ? 1 : 0;
                $cancellation_hours = (int)($_POST['cancellation_hours'] ?? 24);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!$plan_id) {
                    $error = 'Invalid plan ID';
                } elseif (empty($plan_code)) {
                    $error = 'Plan code is required';
                } elseif (empty($plan_name)) {
                    $error = 'Plan name is required';
                } elseif (!$room_type_id) {
                    $error = 'Room type is required';
                } elseif ($base_rate <= 0) {
                    $error = 'Base rate must be greater than 0';
                } elseif ($min_nights < 1) {
                    $error = 'Minimum nights must be at least 1';
                } elseif ($max_nights && $max_nights < $min_nights) {
                    $error = 'Maximum nights must be greater than minimum nights';
                } elseif ($cancellation_hours < 0) {
                    $error = 'Cancellation hours cannot be negative';
                } else {
                    // Check if code exists for another plan
                    $exists = db_fetch_value("SELECT COUNT(*) FROM rate_plans WHERE plan_code = ? AND rate_plan_id != ?", 
                                            [$plan_code, $plan_id]);
                    if ($exists) {
                        $error = 'Plan code already exists';
                    } else {
                        try {
                            $old = db_fetch_one("SELECT * FROM rate_plans WHERE rate_plan_id = ?", [$plan_id]);
                            
                            db_update('rate_plans', [
                                'plan_code' => $plan_code,
                                'plan_name' => $plan_name,
                                'description' => $description ?: null,
                                'room_type_id' => $room_type_id,
                                'season_id' => $season_id,
                                'base_rate' => $base_rate,
                                'adjustment_type' => $adjustment_type,
                                'adjustment_value' => $adjustment_value,
                                'min_nights' => $min_nights,
                                'max_nights' => $max_nights,
                                'is_refundable' => $is_refundable,
                                'cancellation_hours' => $cancellation_hours,
                                'is_active' => $is_active
                            ], 'rate_plan_id = ?', [$plan_id]);
                            
                            $message = 'Rate plan updated successfully';
                            audit_log($current_user['user_id'], AUDIT_UPDATE, 'rate_plans', $plan_id, $old, $_POST);
                            
                        } catch (Exception $e) {
                            $error = 'Failed to update rate plan: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'delete':
                $plan_id = (int)($_POST['plan_id'] ?? 0);
                
                if (!$plan_id) {
                    $error = 'Invalid plan ID';
                } else {
                    // Check if plan is used in reservations
                    $in_use = db_fetch_value("SELECT COUNT(*) FROM reservations WHERE rate_plan_id = ?", [$plan_id]);
                    
                    if ($in_use > 0) {
                        $error = 'Cannot delete rate plan that has been used in reservations';
                    } else {
                        try {
                            db_delete('rate_plans', 'rate_plan_id = ?', [$plan_id]);
                            $message = 'Rate plan deleted successfully';
                            audit_log($current_user['user_id'], AUDIT_DELETE, 'rate_plans', $plan_id);
                        } catch (Exception $e) {
                            $error = 'Failed to delete rate plan: ' . $e->getMessage();
                        }
                    }
                }
                break;
        }
    }
}

// Get all rate plans with details
$rate_plans = db_fetch_all("
    SELECT rp.*, rt.type_name, s.season_name,
           (SELECT COUNT(*) FROM reservations WHERE rate_plan_id = rp.rate_plan_id) as usage_count
    FROM rate_plans rp
    JOIN room_types rt ON rp.room_type_id = rt.room_type_id
    LEFT JOIN seasons s ON rp.season_id = s.season_id
    WHERE 1=1
    " . ($room_type_id ? " AND rp.room_type_id = $room_type_id" : "") . "
    " . ($season_id ? " AND rp.season_id = $season_id" : "") . "
    " . ($status == 'active' ? " AND rp.is_active = 1" : ($status == 'inactive' ? " AND rp.is_active = 0" : "")) . "
    ORDER BY rt.type_name, rp.base_rate
");

// Get room types for dropdown
$room_types = db_fetch_all("SELECT room_type_id, type_name, type_code FROM room_types ORDER BY type_name");

// Get seasons for dropdown
$seasons = db_fetch_all("SELECT season_id, season_name FROM seasons WHERE is_active = 1 ORDER BY start_date");

// Get plan to edit
$edit_plan = null;
if (isset($_GET['edit'])) {
    $edit_plan = db_fetch_one("SELECT * FROM rate_plans WHERE rate_plan_id = ?", [(int)$_GET['edit']]);
}

// 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">Rate Plans Management</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('rooms/dashboard.php'); ?>">Rooms</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Rates</a></li>
                    <li class="breadcrumb-item active">Rate Plans</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?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; ?>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter mr-1"></i>
                    Filters
                </h3>
            </div>
            <div class="card-body">
                <form method="GET" class="form-inline">
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="room_type_id">
                            <option value="">All Room Types</option>
                            <?php foreach ($room_types as $type): ?>
                                <option value="<?php echo $type['room_type_id']; ?>" 
                                        <?php echo $room_type_id == $type['room_type_id'] ? 'selected' : ''; ?>>
                                    <?php echo escape_html($type['type_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="season_id">
                            <option value="">All Seasons</option>
                            <?php foreach ($seasons as $season): ?>
                                <option value="<?php echo $season['season_id']; ?>" 
                                        <?php echo $season_id == $season['season_id'] ? 'selected' : ''; ?>>
                                    <?php echo escape_html($season['season_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="status">
                            <option value="">All Status</option>
                            <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary mb-2 mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filters
                    </button>
                    
                    <a href="?" class="btn btn-secondary mb-2">
                        <i class="fas fa-times mr-1"></i> Clear
                    </a>
                    
                    <button type="button" class="btn btn-success mb-2 ml-auto" data-toggle="modal" data-target="#createPlanModal">
                        <i class="fas fa-plus"></i> New Rate Plan
                    </button>
                </form>
            </div>
        </div>

        <!-- Rate Plans List -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-tags mr-1"></i>
                            Rate Plans (<?php echo count($rate_plans); ?>)
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($rate_plans)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-tags fa-3x mb-3"></i>
                                <p>No rate plans found</p>
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#createPlanModal">
                                    Create First Rate Plan
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Code</th>
                                            <th>Name</th>
                                            <th>Room Type</th>
                                            <th>Season</th>
                                            <th class="text-right">Base Rate</th>
                                            <th class="text-right">Adjustment</th>
                                            <th>Min Nights</th>
                                            <th>Refundable</th>
                                            <th>Usage</th>
                                            <th>Status</th>
                                            <th width="120">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($rate_plans as $plan): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape_html($plan['plan_code']); ?></strong>
                                            </td>
                                            <td>
                                                <?php echo escape_html($plan['plan_name']); ?>
                                                <?php if ($plan['description']): ?>
                                                    <br>
                                                    <small class="text-muted"><?php echo escape_html(truncate_text($plan['description'], 30)); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo escape_html($plan['type_name']); ?></td>
                                            <td>
                                                <?php echo $plan['season_name'] ?: '<span class="text-muted">All Year</span>'; ?>
                                            </td>
                                            <td class="text-right"><?php echo format_currency($plan['base_rate']); ?></td>
                                            <td class="text-right">
                                                <?php if ($plan['adjustment_type'] == 'percentage'): ?>
                                                    <?php echo $plan['adjustment_value']; ?>%
                                                <?php else: ?>
                                                    <?php echo format_currency($plan['adjustment_value']); ?>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <?php echo $plan['min_nights']; ?>
                                                <?php if ($plan['max_nights']): ?>
                                                    - <?php echo $plan['max_nights']; ?>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($plan['is_refundable']): ?>
                                                    <span class="badge badge-success">Yes</span>
                                                    <br>
                                                    <small><?php echo $plan['cancellation_hours']; ?>h</small>
                                                <?php else: ?>
                                                    <span class="badge badge-danger">No</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge badge-info"><?php echo $plan['usage_count']; ?></span>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php echo $plan['is_active'] ? 'success' : 'secondary'; ?>">
                                                    <?php echo $plan['is_active'] ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="?edit=<?php echo $plan['rate_plan_id']; ?>" class="btn btn-sm btn-warning">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    
                                                    <?php if ($plan['usage_count'] == 0): ?>
                                                        <button type="button" class="btn btn-sm btn-danger" 
                                                                onclick="deletePlan(<?php echo $plan['rate_plan_id']; ?>, '<?php echo escape_html($plan['plan_name']); ?>')">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Edit Form -->
        <?php if ($edit_plan): ?>
        <div class="row">
            <div class="col-12">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit mr-1"></i>
                            Edit Rate Plan: <?php echo escape_html($edit_plan['plan_code']); ?>
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="plan_id" value="<?php echo $edit_plan['rate_plan_id']; ?>">
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="edit_plan_code">Plan Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="edit_plan_code" name="plan_code" 
                                               value="<?php echo escape_html($edit_plan['plan_code']); ?>" 
                                               maxlength="20" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="edit_plan_name">Plan Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="edit_plan_name" name="plan_name" 
                                               value="<?php echo escape_html($edit_plan['plan_name']); ?>" 
                                               maxlength="50" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_description">Description</label>
                                <textarea class="form-control" id="edit_description" name="description" rows="2"><?php echo escape_html($edit_plan['description']); ?></textarea>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="edit_room_type_id">Room Type <span class="text-danger">*</span></label>
                                        <select class="form-control" id="edit_room_type_id" name="room_type_id" required>
                                            <option value="">Select Room Type</option>
                                            <?php foreach ($room_types as $type): ?>
                                                <option value="<?php echo $type['room_type_id']; ?>" 
                                                        <?php echo $edit_plan['room_type_id'] == $type['room_type_id'] ? 'selected' : ''; ?>>
                                                    <?php echo escape_html($type['type_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="edit_season_id">Season</label>
                                        <select class="form-control" id="edit_season_id" name="season_id">
                                            <option value="">All Year</option>
                                            <?php foreach ($seasons as $season): ?>
                                                <option value="<?php echo $season['season_id']; ?>" 
                                                        <?php echo $edit_plan['season_id'] == $season['season_id'] ? 'selected' : ''; ?>>
                                                    <?php echo escape_html($season['season_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="edit_base_rate">Base Rate <span class="text-danger">*</span></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="edit_base_rate" name="base_rate" 
                                                   value="<?php echo $edit_plan['base_rate']; ?>" step="0.01" min="0" required>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="edit_adjustment_type">Adjustment Type</label>
                                        <select class="form-control" id="edit_adjustment_type" name="adjustment_type">
                                            <option value="fixed" <?php echo $edit_plan['adjustment_type'] == 'fixed' ? 'selected' : ''; ?>>Fixed Amount</option>
                                            <option value="percentage" <?php echo $edit_plan['adjustment_type'] == 'percentage' ? 'selected' : ''; ?>>Percentage</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="edit_adjustment_value">Adjustment Value</label>
                                        <input type="number" class="form-control" id="edit_adjustment_value" name="adjustment_value" 
                                               value="<?php echo $edit_plan['adjustment_value']; ?>" step="0.01" min="0">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="edit_min_nights">Minimum Nights</label>
                                        <input type="number" class="form-control" id="edit_min_nights" name="min_nights" 
                                               value="<?php echo $edit_plan['min_nights']; ?>" min="1" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="edit_max_nights">Maximum Nights</label>
                                        <input type="number" class="form-control" id="edit_max_nights" name="max_nights" 
                                               value="<?php echo $edit_plan['max_nights']; ?>" min="1">
                                        <small class="text-muted">Leave empty for no maximum</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="edit_cancellation_hours">Cancellation Hours</label>
                                        <input type="number" class="form-control" id="edit_cancellation_hours" name="cancellation_hours" 
                                               value="<?php echo $edit_plan['cancellation_hours']; ?>" min="0">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="edit_is_refundable" name="is_refundable"
                                                   <?php echo $edit_plan['is_refundable'] ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="edit_is_refundable">Refundable</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="edit_is_active" name="is_active"
                                                   <?php echo $edit_plan['is_active'] ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="edit_is_active">Active</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save mr-1"></i> Update Rate Plan
                            </button>
                            <a href="?" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Create Plan Modal -->
<div class="modal fade" id="createPlanModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title">Create New Rate Plan</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            
            <form method="POST">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="create">
                
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="plan_code">Plan Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="plan_code" name="plan_code" 
                                       maxlength="20" required placeholder="e.g., STD-BB, DEL-HB">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="plan_name">Plan Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="plan_name" name="plan_name" 
                                       maxlength="50" required placeholder="e.g., Standard Bed & Breakfast">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="room_type_id">Room Type <span class="text-danger">*</span></label>
                                <select class="form-control" id="room_type_id" name="room_type_id" required>
                                    <option value="">Select Room Type</option>
                                    <?php foreach ($room_types as $type): ?>
                                        <option value="<?php echo $type['room_type_id']; ?>">
                                            <?php echo escape_html($type['type_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="season_id">Season</label>
                                <select class="form-control" id="season_id" name="season_id">
                                    <option value="">All Year</option>
                                    <?php foreach ($seasons as $season): ?>
                                        <option value="<?php echo $season['season_id']; ?>">
                                            <?php echo escape_html($season['season_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="base_rate">Base Rate <span class="text-danger">*</span></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="base_rate" name="base_rate" 
                                           step="0.01" min="0" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="adjustment_type">Adjustment Type</label>
                                <select class="form-control" id="adjustment_type" name="adjustment_type">
                                    <option value="fixed">Fixed Amount</option>
                                    <option value="percentage">Percentage</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="adjustment_value">Adjustment Value</label>
                                <input type="number" class="form-control" id="adjustment_value" name="adjustment_value" 
                                       step="0.01" min="0" value="0">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="min_nights">Minimum Nights</label>
                                <input type="number" class="form-control" id="min_nights" name="min_nights" 
                                       value="1" min="1" required>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="max_nights">Maximum Nights</label>
                                <input type="number" class="form-control" id="max_nights" name="max_nights" 
                                       min="1" placeholder="No max">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="cancellation_hours">Cancellation Hours</label>
                                <input type="number" class="form-control" id="cancellation_hours" name="cancellation_hours" 
                                       value="24" min="0">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="is_refundable" name="is_refundable" checked>
                            <label class="custom-control-label" for="is_refundable">Refundable</label>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Rate Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Plan Modal -->
<div class="modal fade" id="deletePlanModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Rate Plan</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete rate plan <strong id="deletePlanName"></strong>?</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deletePlanForm">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="plan_id" id="deletePlanId">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function deletePlan(planId, planName) {
    $('#deletePlanId').val(planId);
    $('#deletePlanName').text(planName);
    $('#deletePlanModal').modal('show');
}

// Auto-capitalize plan code
$('#plan_code, #edit_plan_code').on('input', function() {
    this.value = this.value.toUpperCase();
});

// Toggle adjustment fields based on type
$('#adjustment_type, #edit_adjustment_type').on('change', function() {
    const type = $(this).val();
    const valueField = $(this).attr('id') === 'adjustment_type' ? '#adjustment_value' : '#edit_adjustment_value';
    
    if (type === 'percentage') {
        $(valueField).attr('step', '0.1').attr('max', '100');
    } else {
        $(valueField).attr('step', '0.01').removeAttr('max');
    }
});
</script>

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