<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Price Rules Management - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/rooms/rates/price-rules.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If init.php doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/init.php')) {
    // Manual calculation: /HMSPOS/rooms/rates/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/init.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define audit constants if not defined
if (!defined('AUDIT_CREATE')) {
    define('AUDIT_CREATE', 'create');
}
if (!defined('AUDIT_UPDATE')) {
    define('AUDIT_UPDATE', 'update');
}
if (!defined('AUDIT_DELETE')) {
    define('AUDIT_DELETE', 'delete');
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        if (is_array($data)) {
            return array_map('sanitize_input', $data);
        }
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

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

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('rates.manage');
// }

// Set page title
$page_title = 'Price Rules Management';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $error = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'create':
                $rule_name = $_POST['rule_name'] ?? '';
                $room_type_id = !empty($_POST['room_type_id']) ? (int)$_POST['room_type_id'] : null;
                $day_of_week = $_POST['day_of_week'] ?? 'all';
                $min_occupancy = (int)($_POST['min_occupancy'] ?? 0);
                $adjustment_type = $_POST['adjustment_type'] ?? 'percentage';
                $adjustment_value = (float)($_POST['adjustment_value'] ?? 0);
                $priority = (int)($_POST['priority'] ?? 0);
                $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
                $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
                
                if (empty($rule_name)) {
                    $error = 'Rule name is required';
                } elseif ($adjustment_value <= 0) {
                    $error = 'Adjustment value must be greater than 0';
                } elseif ($adjustment_type == 'percentage' && $adjustment_value > 100) {
                    $error = 'Percentage adjustment cannot exceed 100%';
                } elseif ($start_date && $end_date && $start_date > $end_date) {
                    $error = 'Start date must be before end date';
                } else {
                    try {
                        $insert_data = [
                            'rule_name' => $rule_name,
                            'room_type_id' => $room_type_id,
                            'day_of_week' => $day_of_week,
                            'min_occupancy' => $min_occupancy,
                            'adjustment_type' => $adjustment_type,
                            'adjustment_value' => $adjustment_value,
                            'priority' => $priority,
                            'start_date' => $start_date,
                            'end_date' => $end_date,
                            'is_active' => 1
                        ];
                        
                        if (function_exists('db_insert')) {
                            db_insert('price_rules', $insert_data);
                        } else {
                            // Fallback direct insert
                            $pdo = get_db_connection();
                            $sql = "INSERT INTO price_rules (rule_name, room_type_id, day_of_week, min_occupancy, 
                                    adjustment_type, adjustment_value, priority, start_date, end_date, is_active) 
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)";
                            $stmt = $pdo->prepare($sql);
                            $stmt->execute([
                                $rule_name,
                                $room_type_id,
                                $day_of_week,
                                $min_occupancy,
                                $adjustment_type,
                                $adjustment_value,
                                $priority,
                                $start_date,
                                $end_date
                            ]);
                        }
                        
                        $message = 'Price rule created successfully';
                        if (function_exists('audit_log')) {
                            audit_log($user_id, 'create', 'price_rules', null, null, $_POST);
                        }
                        
                    } catch (Exception $e) {
                        $error = 'Failed to create price rule: ' . $e->getMessage();
                        if (function_exists('log_message')) {
                            log_message("Price rule creation failed: " . $e->getMessage(), 'ERROR');
                        }
                    }
                }
                break;
                
            case 'edit':
                $rule_id = (int)($_POST['rule_id'] ?? 0);
                $rule_name = $_POST['rule_name'] ?? '';
                $room_type_id = !empty($_POST['room_type_id']) ? (int)$_POST['room_type_id'] : null;
                $day_of_week = $_POST['day_of_week'] ?? 'all';
                $min_occupancy = (int)($_POST['min_occupancy'] ?? 0);
                $adjustment_type = $_POST['adjustment_type'] ?? 'percentage';
                $adjustment_value = (float)($_POST['adjustment_value'] ?? 0);
                $priority = (int)($_POST['priority'] ?? 0);
                $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
                $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!$rule_id) {
                    $error = 'Invalid rule ID';
                } elseif (empty($rule_name)) {
                    $error = 'Rule name is required';
                } elseif ($adjustment_value <= 0) {
                    $error = 'Adjustment value must be greater than 0';
                } elseif ($adjustment_type == 'percentage' && $adjustment_value > 100) {
                    $error = 'Percentage adjustment cannot exceed 100%';
                } elseif ($start_date && $end_date && $start_date > $end_date) {
                    $error = 'Start date must be before end date';
                } else {
                    try {
                        $old = db_fetch_one("SELECT * FROM price_rules WHERE rule_id = ?", [$rule_id]);
                        
                        $update_data = [
                            'rule_name' => $rule_name,
                            'room_type_id' => $room_type_id,
                            'day_of_week' => $day_of_week,
                            'min_occupancy' => $min_occupancy,
                            'adjustment_type' => $adjustment_type,
                            'adjustment_value' => $adjustment_value,
                            'priority' => $priority,
                            'start_date' => $start_date,
                            'end_date' => $end_date,
                            'is_active' => $is_active
                        ];
                        
                        if (function_exists('db_update')) {
                            db_update('price_rules', $update_data, 'rule_id = ?', [$rule_id]);
                        } else {
                            // Fallback direct update
                            $pdo = get_db_connection();
                            $sql = "UPDATE price_rules SET 
                                    rule_name = ?, room_type_id = ?, day_of_week = ?, 
                                    min_occupancy = ?, adjustment_type = ?, adjustment_value = ?, 
                                    priority = ?, start_date = ?, end_date = ?, is_active = ?
                                    WHERE rule_id = ?";
                            $stmt = $pdo->prepare($sql);
                            $stmt->execute([
                                $rule_name,
                                $room_type_id,
                                $day_of_week,
                                $min_occupancy,
                                $adjustment_type,
                                $adjustment_value,
                                $priority,
                                $start_date,
                                $end_date,
                                $is_active,
                                $rule_id
                            ]);
                        }
                        
                        $message = 'Price rule updated successfully';
                        if (function_exists('audit_log')) {
                            audit_log($user_id, 'update', 'price_rules', $rule_id, $old, $_POST);
                        }
                        
                    } catch (Exception $e) {
                        $error = 'Failed to update price rule: ' . $e->getMessage();
                        if (function_exists('log_message')) {
                            log_message("Price rule update failed: " . $e->getMessage(), 'ERROR');
                        }
                    }
                }
                break;
                
            case 'delete':
                $rule_id = (int)($_POST['rule_id'] ?? 0);
                
                if (!$rule_id) {
                    $error = 'Invalid rule ID';
                } else {
                    try {
                        if (function_exists('db_delete')) {
                            db_delete('price_rules', 'rule_id = ?', [$rule_id]);
                        } else {
                            // Fallback direct delete
                            $pdo = get_db_connection();
                            $pdo->prepare("DELETE FROM price_rules WHERE rule_id = ?")->execute([$rule_id]);
                        }
                        
                        $message = 'Price rule deleted successfully';
                        if (function_exists('audit_log')) {
                            audit_log($user_id, 'delete', 'price_rules', $rule_id);
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to delete price rule: ' . $e->getMessage();
                        if (function_exists('log_message')) {
                            log_message("Price rule deletion failed: " . $e->getMessage(), 'ERROR');
                        }
                    }
                }
                break;
        }
    }
}

// Get all price rules
$price_rules = [];
try {
    $price_rules = db_fetch_all("
        SELECT pr.*, rt.type_name
        FROM price_rules pr
        LEFT JOIN room_types rt ON pr.room_type_id = rt.room_type_id
        ORDER BY pr.priority DESC, pr.rule_name
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching price rules: " . $e->getMessage());
}

// Get room types for dropdown
$room_types = [];
try {
    $room_types = db_fetch_all("SELECT room_type_id, type_name FROM room_types ORDER BY type_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
}

// Get rule to edit
$edit_rule = null;
if (isset($_GET['edit'])) {
    try {
        $edit_rule = db_fetch_one("SELECT * FROM price_rules WHERE rule_id = ?", [(int)$_GET['edit']]);
    } catch (Exception $e) {
        error_log("Error fetching rule for edit: " . $e->getMessage());
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Price Rules Management</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Price Rules Management</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?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">Price Rules Management</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/rooms/dashboard.php">Rooms</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Rates</a></li>
                    <li class="breadcrumb-item active">Price Rules</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if (!empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Price Rules List -->
            <div class="col-md-<?php echo $edit_rule ? '7' : '12'; ?>">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-cogs me-1"></i>
                            Price Rules
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#createRuleModal">
                                <i class="fas fa-plus"></i> New Rule
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($price_rules)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-cogs fa-3x mb-3"></i>
                                <p>No price rules defined</p>
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createRuleModal">
                                    Create First Rule
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Priority</th>
                                            <th>Rule Name</th>
                                            <th>Room Type</th>
                                            <th>Day of Week</th>
                                            <th>Min Occ</th>
                                            <th>Adjustment</th>
                                            <th>Date Range</th>
                                            <th>Status</th>
                                            <th width="120">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($price_rules as $rule): ?>
                                        <tr>
                                            <td>
                                                <span class="badge bg-secondary"><?php echo $rule['priority'] ?? 0; ?></span>
                                            </td>
                                            <td>
                                                <strong><?php echo escape_html($rule['rule_name'] ?? ''); ?></strong>
                                            </td>
                                            <td>
                                                <?php echo !empty($rule['type_name']) ? escape_html($rule['type_name']) : '<span class="text-muted">All Types</span>'; ?>
                                            </td>
                                            <td>
                                                <?php 
                                                if (($rule['day_of_week'] ?? '') == 'all') {
                                                    echo 'All Days';
                                                } else {
                                                    echo ucfirst($rule['day_of_week'] ?? '');
                                                }
                                                ?>
                                            </td>
                                            <td class="text-center">
                                                <?php echo !empty($rule['min_occupancy']) ? $rule['min_occupancy'] : '-'; ?>
                                            </td>
                                            <td>
                                                <?php if (($rule['adjustment_type'] ?? '') == 'percentage'): ?>
                                                    <span class="badge bg-info"><?php echo $rule['adjustment_value'] ?? 0; ?>%</span>
                                                <?php else: ?>
                                                    <span class="badge bg-success"><?php echo format_currency($rule['adjustment_value'] ?? 0); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if (!empty($rule['start_date']) || !empty($rule['end_date'])): ?>
                                                    <?php echo !empty($rule['start_date']) ? format_date($rule['start_date']) : '∞'; ?>
                                                    <br>
                                                    <small>to</small>
                                                    <br>
                                                    <?php echo !empty($rule['end_date']) ? format_date($rule['end_date']) : '∞'; ?>
                                                <?php else: ?>
                                                    <span class="text-muted">Always</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo !empty($rule['is_active']) ? 'success' : 'secondary'; ?>">
                                                    <?php echo !empty($rule['is_active']) ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="?edit=<?php echo $rule['rule_id'] ?? 0; ?>" class="btn btn-sm btn-warning">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    
                                                    <button type="button" class="btn btn-sm btn-danger" 
                                                            onclick="deleteRule(<?php echo $rule['rule_id'] ?? 0; ?>, '<?php echo escape_html($rule['rule_name'] ?? ''); ?>')">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Edit Form -->
            <?php if ($edit_rule): ?>
            <div class="col-md-5">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit me-1"></i>
                            Edit Price Rule: <?php echo escape_html($edit_rule['rule_name'] ?? ''); ?>
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="rule_id" value="<?php echo $edit_rule['rule_id'] ?? 0; ?>">
                        
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="edit_rule_name">Rule Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_rule_name" name="rule_name" 
                                       value="<?php echo escape_html($edit_rule['rule_name'] ?? ''); ?>" required>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_room_type_id">Room Type</label>
                                        <select class="form-select" id="edit_room_type_id" name="room_type_id">
                                            <option value="">All Room Types</option>
                                            <?php foreach ($room_types as $type): ?>
                                                <option value="<?php echo $type['room_type_id'] ?? 0; ?>" 
                                                        <?php echo ($edit_rule['room_type_id'] ?? 0) == ($type['room_type_id'] ?? 0) ? 'selected' : ''; ?>>
                                                    <?php echo escape_html($type['type_name'] ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_day_of_week">Day of Week</label>
                                        <select class="form-select" id="edit_day_of_week" name="day_of_week">
                                            <option value="all" <?php echo ($edit_rule['day_of_week'] ?? '') == 'all' ? 'selected' : ''; ?>>All Days</option>
                                            <option value="monday" <?php echo ($edit_rule['day_of_week'] ?? '') == 'monday' ? 'selected' : ''; ?>>Monday</option>
                                            <option value="tuesday" <?php echo ($edit_rule['day_of_week'] ?? '') == 'tuesday' ? 'selected' : ''; ?>>Tuesday</option>
                                            <option value="wednesday" <?php echo ($edit_rule['day_of_week'] ?? '') == 'wednesday' ? 'selected' : ''; ?>>Wednesday</option>
                                            <option value="thursday" <?php echo ($edit_rule['day_of_week'] ?? '') == 'thursday' ? 'selected' : ''; ?>>Thursday</option>
                                            <option value="friday" <?php echo ($edit_rule['day_of_week'] ?? '') == 'friday' ? 'selected' : ''; ?>>Friday</option>
                                            <option value="saturday" <?php echo ($edit_rule['day_of_week'] ?? '') == 'saturday' ? 'selected' : ''; ?>>Saturday</option>
                                            <option value="sunday" <?php echo ($edit_rule['day_of_week'] ?? '') == 'sunday' ? 'selected' : ''; ?>>Sunday</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_min_occupancy">Min Occupancy</label>
                                        <input type="number" class="form-control" id="edit_min_occupancy" name="min_occupancy" 
                                               value="<?php echo $edit_rule['min_occupancy'] ?? 0; ?>" min="0">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_priority">Priority</label>
                                        <input type="number" class="form-control" id="edit_priority" name="priority" 
                                               value="<?php echo $edit_rule['priority'] ?? 0; ?>" min="0">
                                        <small class="text-muted">Higher priority rules apply first</small>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="edit_adjustment_type">Adjustment Type</label>
                                        <select class="form-select" id="edit_adjustment_type" name="adjustment_type">
                                            <option value="percentage" <?php echo ($edit_rule['adjustment_type'] ?? '') == 'percentage' ? 'selected' : ''; ?>>Percentage</option>
                                            <option value="fixed" <?php echo ($edit_rule['adjustment_type'] ?? '') == 'fixed' ? 'selected' : ''; ?>>Fixed Amount</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-8">
                                    <div class="mb-3">
                                        <label for="edit_adjustment_value">Adjustment Value <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="edit_adjustment_value" name="adjustment_value" 
                                               value="<?php echo $edit_rule['adjustment_value'] ?? 0; ?>" step="0.01" min="0" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_start_date">Start Date</label>
                                        <input type="date" class="form-control" id="edit_start_date" name="start_date" 
                                               value="<?php echo $edit_rule['start_date'] ?? ''; ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="edit_end_date">End Date</label>
                                        <input type="date" class="form-control" id="edit_end_date" name="end_date" 
                                               value="<?php echo $edit_rule['end_date'] ?? ''; ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input type="checkbox" class="form-check-input" id="edit_is_active" name="is_active"
                                           <?php echo !empty($edit_rule['is_active']) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="edit_is_active">Active</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save me-1"></i> Update Rule
                            </button>
                            <a href="?" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Create Rule Modal -->
<div class="modal fade" id="createRuleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title">Create Price Rule</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            
            <form method="POST">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php else: ?>
                    <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                <?php endif; ?>
                <input type="hidden" name="action" value="create">
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="rule_name">Rule Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="rule_name" name="rule_name" 
                               placeholder="e.g., Weekend Premium, Early Bird Discount" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="room_type_id">Room Type</label>
                                <select class="form-select" id="room_type_id" name="room_type_id">
                                    <option value="">All Room Types</option>
                                    <?php foreach ($room_types as $type): ?>
                                        <option value="<?php echo $type['room_type_id'] ?? 0; ?>">
                                            <?php echo escape_html($type['type_name'] ?? ''); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="day_of_week">Day of Week</label>
                                <select class="form-select" id="day_of_week" name="day_of_week">
                                    <option value="all">All Days</option>
                                    <option value="monday">Monday</option>
                                    <option value="tuesday">Tuesday</option>
                                    <option value="wednesday">Wednesday</option>
                                    <option value="thursday">Thursday</option>
                                    <option value="friday">Friday</option>
                                    <option value="saturday">Saturday</option>
                                    <option value="sunday">Sunday</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="min_occupancy">Min Occupancy</label>
                                <input type="number" class="form-control" id="min_occupancy" name="min_occupancy" value="0" min="0">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="priority">Priority</label>
                                <input type="number" class="form-control" id="priority" name="priority" value="0" min="0">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="adjustment_type">Adjustment Type</label>
                                <select class="form-select" id="adjustment_type" name="adjustment_type">
                                    <option value="percentage">Percentage</option>
                                    <option value="fixed">Fixed Amount</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label for="adjustment_value">Adjustment Value <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="adjustment_value" name="adjustment_value" 
                                       step="0.01" min="0" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="start_date">Start Date</label>
                                <input type="date" class="form-control" id="start_date" name="start_date">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="end_date">End Date</label>
                                <input type="date" class="form-control" id="end_date" name="end_date">
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>How it works:</strong> Rules are applied in priority order. Higher priority numbers are applied first.
                        Rules without date ranges apply year-round.
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Rule</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Rule Modal -->
<div class="modal fade" id="deleteRuleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Price Rule</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete price rule <strong id="deleteRuleName"></strong>?</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteRuleForm">
                    <?php if (function_exists('csrf_field')): ?>
                        <?php echo csrf_field(); ?>
                    <?php else: ?>
                        <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                    <?php endif; ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="rule_id" id="deleteRuleId">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function deleteRule(ruleId, ruleName) {
    document.getElementById('deleteRuleId').value = ruleId;
    document.getElementById('deleteRuleName').textContent = ruleName;
    
    const modal = new bootstrap.Modal(document.getElementById('deleteRuleModal'));
    modal.show();
}

// Date validation
$('#start_date, #end_date, #edit_start_date, #edit_end_date').on('change', function() {
    const isEdit = $(this).attr('id').startsWith('edit_');
    const startField = isEdit ? '#edit_start_date' : '#start_date';
    const endField = isEdit ? '#edit_end_date' : '#end_date';
    
    const start = $(startField).val();
    const end = $(endField).val();
    
    if (start && end && start > end) {
        alert('Start date must be before end date');
        if ($(this).is(startField)) {
            $(this).val('');
        } else {
            $(this).val('');
        }
    }
});

// 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';
    const label = $(this).attr('id') === 'adjustment_type' ? 
                  $('label[for="adjustment_value"]') : 
                  $('label[for="edit_adjustment_value"]');
    
    if (type === 'percentage') {
        $(valueField).attr('step', '0.1').attr('max', '100');
        label.text('Adjustment Value (%)');
    } else {
        $(valueField).attr('step', '0.01').removeAttr('max');
        label.text('Adjustment Value (<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?>)');
    }
});
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>