<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Pricing Rules Manager';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('pr_table_exists')) {
    function pr_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pr_column_exists')) {
    function pr_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
              AND column_name = :column_name
        ");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pr_flash')) {
    function pr_flash(string $type, string $message): void {
        $_SESSION['pricing_rules_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('pr_get_flash')) {
    function pr_get_flash(): array {
        $items = $_SESSION['pricing_rules_flash'] ?? [];
        unset($_SESSION['pricing_rules_flash']);
        return $items;
    }
}
if (!function_exists('pr_bool')) {
    function pr_bool($value): int {
        return in_array((string)$value, ['1', 'yes', 'true', 'on'], true) ? 1 : 0;
    }
}

$errors = [];

try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS pricing_rules (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            rule_name VARCHAR(150) NOT NULL,
            rule_type ENUM('season','weekend','event','occupancy','pickup','manual') NOT NULL DEFAULT 'season',
            property_id INT UNSIGNED NULL,
            room_type_id INT UNSIGNED NULL,
            agent_id INT UNSIGNED NULL,
            valid_from DATE NOT NULL,
            valid_to DATE NOT NULL,
            days_of_week VARCHAR(30) NULL,
            adjustment_type ENUM('percent','fixed') NOT NULL DEFAULT 'percent',
            adjustment_value DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            min_rate DECIMAL(12,2) NULL,
            max_rate DECIMAL(12,2) NULL,
            occupancy_from DECIMAL(5,2) NULL,
            occupancy_to DECIMAL(5,2) NULL,
            pickup_from INT NULL,
            pickup_to INT NULL,
            priority INT NOT NULL DEFAULT 100,
            apply_mode ENUM('suggest_only','auto_apply') NOT NULL DEFAULT 'suggest_only',
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            notes TEXT NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_pricing_rules_dates (valid_from, valid_to),
            INDEX idx_pricing_rules_scope (property_id, room_type_id, agent_id),
            INDEX idx_pricing_rules_active (is_active, rule_type, priority)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (Throwable $e) {
    $errors[] = 'Could not create pricing_rules table: ' . $e->getMessage();
}

$properties = [];
$roomTypes = [];
$agents = [];

try {
    if (pr_table_exists($pdo, 'properties')) {
        $properties = $pdo->query("
            SELECT id, name, code
            FROM properties
            WHERE is_active = 1
            ORDER BY name ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $properties = [];
}

try {
    if (pr_table_exists($pdo, 'room_types')) {
        $roomTypes = $pdo->query("
            SELECT id, title, property_id
            FROM room_types
            ORDER BY title ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $roomTypes = [];
}

try {
    if (pr_table_exists($pdo, 'agents')) {
        $agents = $pdo->query("
            SELECT id, firstname, lastname
            FROM agents
            ORDER BY firstname ASC, lastname ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $agents = [];
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) {
            verify_csrf();
        }

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save_rule') {
            $id = (int)($_POST['id'] ?? 0);
            $ruleName = trim((string)($_POST['rule_name'] ?? ''));
            $ruleType = (string)($_POST['rule_type'] ?? 'season');
            $propertyId = (int)($_POST['property_id'] ?? 0);
            $roomTypeId = (int)($_POST['room_type_id'] ?? 0);
            $agentId = (int)($_POST['agent_id'] ?? 0);
            $validFrom = trim((string)($_POST['valid_from'] ?? ''));
            $validTo = trim((string)($_POST['valid_to'] ?? ''));
            $days = $_POST['days_of_week'] ?? [];
            $adjustmentType = (string)($_POST['adjustment_type'] ?? 'percent');
            $adjustmentValue = (float)($_POST['adjustment_value'] ?? 0);
            $minRate = trim((string)($_POST['min_rate'] ?? ''));
            $maxRate = trim((string)($_POST['max_rate'] ?? ''));
            $occupancyFrom = trim((string)($_POST['occupancy_from'] ?? ''));
            $occupancyTo = trim((string)($_POST['occupancy_to'] ?? ''));
            $pickupFrom = trim((string)($_POST['pickup_from'] ?? ''));
            $pickupTo = trim((string)($_POST['pickup_to'] ?? ''));
            $priority = (int)($_POST['priority'] ?? 100);
            $applyMode = (string)($_POST['apply_mode'] ?? 'suggest_only');
            $isActive = pr_bool($_POST['is_active'] ?? 0);
            $notes = trim((string)($_POST['notes'] ?? ''));

            $allowedRuleTypes = ['season','weekend','event','occupancy','pickup','manual'];
            $allowedAdjustmentTypes = ['percent','fixed'];
            $allowedApplyModes = ['suggest_only','auto_apply'];

            if ($ruleName === '') {
                throw new RuntimeException('Rule name is required.');
            }
            if (!in_array($ruleType, $allowedRuleTypes, true)) {
                throw new RuntimeException('Invalid rule type.');
            }
            if (!in_array($adjustmentType, $allowedAdjustmentTypes, true)) {
                throw new RuntimeException('Invalid adjustment type.');
            }
            if (!in_array($applyMode, $allowedApplyModes, true)) {
                throw new RuntimeException('Invalid apply mode.');
            }
            if (strtotime($validFrom) === false || strtotime($validTo) === false) {
                throw new RuntimeException('Valid from and valid to dates are required.');
            }
            if (strtotime($validFrom) > strtotime($validTo)) {
                throw new RuntimeException('Valid from cannot be after valid to.');
            }

            $cleanDays = [];
            if (is_array($days)) {
                foreach ($days as $d) {
                    $d = (int)$d;
                    if ($d >= 1 && $d <= 7) {
                        $cleanDays[] = (string)$d;
                    }
                }
            }
            $daysOfWeek = $cleanDays ? implode(',', array_unique($cleanDays)) : null;

            $payload = [
                ':rule_name' => $ruleName,
                ':rule_type' => $ruleType,
                ':property_id' => $propertyId > 0 ? $propertyId : null,
                ':room_type_id' => $roomTypeId > 0 ? $roomTypeId : null,
                ':agent_id' => $agentId > 0 ? $agentId : null,
                ':valid_from' => $validFrom,
                ':valid_to' => $validTo,
                ':days_of_week' => $daysOfWeek,
                ':adjustment_type' => $adjustmentType,
                ':adjustment_value' => $adjustmentValue,
                ':min_rate' => $minRate !== '' ? (float)$minRate : null,
                ':max_rate' => $maxRate !== '' ? (float)$maxRate : null,
                ':occupancy_from' => $occupancyFrom !== '' ? (float)$occupancyFrom : null,
                ':occupancy_to' => $occupancyTo !== '' ? (float)$occupancyTo : null,
                ':pickup_from' => $pickupFrom !== '' ? (int)$pickupFrom : null,
                ':pickup_to' => $pickupTo !== '' ? (int)$pickupTo : null,
                ':priority' => $priority,
                ':apply_mode' => $applyMode,
                ':is_active' => $isActive,
                ':notes' => $notes !== '' ? $notes : null,
            ];

            if ($id > 0) {
                $payload[':id'] = $id;
                $stmt = $pdo->prepare("
                    UPDATE pricing_rules
                    SET
                        rule_name = :rule_name,
                        rule_type = :rule_type,
                        property_id = :property_id,
                        room_type_id = :room_type_id,
                        agent_id = :agent_id,
                        valid_from = :valid_from,
                        valid_to = :valid_to,
                        days_of_week = :days_of_week,
                        adjustment_type = :adjustment_type,
                        adjustment_value = :adjustment_value,
                        min_rate = :min_rate,
                        max_rate = :max_rate,
                        occupancy_from = :occupancy_from,
                        occupancy_to = :occupancy_to,
                        pickup_from = :pickup_from,
                        pickup_to = :pickup_to,
                        priority = :priority,
                        apply_mode = :apply_mode,
                        is_active = :is_active,
                        notes = :notes
                    WHERE id = :id
                ");
                $stmt->execute($payload);
                pr_flash('success', 'Pricing rule updated successfully.');
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO pricing_rules
                    (
                        rule_name, rule_type, property_id, room_type_id, agent_id,
                        valid_from, valid_to, days_of_week,
                        adjustment_type, adjustment_value,
                        min_rate, max_rate,
                        occupancy_from, occupancy_to,
                        pickup_from, pickup_to,
                        priority, apply_mode, is_active, notes
                    )
                    VALUES
                    (
                        :rule_name, :rule_type, :property_id, :room_type_id, :agent_id,
                        :valid_from, :valid_to, :days_of_week,
                        :adjustment_type, :adjustment_value,
                        :min_rate, :max_rate,
                        :occupancy_from, :occupancy_to,
                        :pickup_from, :pickup_to,
                        :priority, :apply_mode, :is_active, :notes
                    )
                ");
                $stmt->execute($payload);
                pr_flash('success', 'Pricing rule created successfully.');
            }

            header('Location: pricing_rules.php');
            exit;
        }

        if ($action === 'toggle_rule') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Invalid rule selected.');
            }

            $stmt = $pdo->prepare("
                UPDATE pricing_rules
                SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END
                WHERE id = :id
            ");
            $stmt->execute([':id' => $id]);

            pr_flash('success', 'Pricing rule status updated.');
            header('Location: pricing_rules.php');
            exit;
        }

        if ($action === 'delete_rule') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Invalid rule selected.');
            }

            $stmt = $pdo->prepare("DELETE FROM pricing_rules WHERE id = :id");
            $stmt->execute([':id' => $id]);

            pr_flash('success', 'Pricing rule deleted.');
            header('Location: pricing_rules.php');
            exit;
        }

        if ($action === 'seed_defaults') {
            $today = date('Y-m-d');
            $yearEnd = date('Y-12-31');

            $defaults = [
                ['Low Season Discount', 'season', $today, $yearEnd, 'percent', -10, 200, 'suggest_only', 'Use for soft periods or low occupancy seasons.'],
                ['Weekend Premium', 'weekend', $today, $yearEnd, 'percent', 5, 120, 'suggest_only', 'Friday, Saturday and Sunday premium.', '5,6,7'],
                ['Peak Season Premium', 'season', $today, $yearEnd, 'percent', 20, 80, 'suggest_only', 'General peak season uplift.'],
                ['High Occupancy Premium', 'occupancy', $today, $yearEnd, 'percent', 15, 60, 'suggest_only', 'Applies when occupancy pressure is high.'],
            ];

            $stmt = $pdo->prepare("
                INSERT INTO pricing_rules
                (rule_name, rule_type, valid_from, valid_to, adjustment_type, adjustment_value, priority, apply_mode, is_active, notes, days_of_week, occupancy_from)
                VALUES
                (:rule_name, :rule_type, :valid_from, :valid_to, :adjustment_type, :adjustment_value, :priority, :apply_mode, 1, :notes, :days_of_week, :occupancy_from)
            ");

            foreach ($defaults as $rule) {
                $stmt->execute([
                    ':rule_name' => $rule[0],
                    ':rule_type' => $rule[1],
                    ':valid_from' => $rule[2],
                    ':valid_to' => $rule[3],
                    ':adjustment_type' => $rule[4],
                    ':adjustment_value' => $rule[5],
                    ':priority' => $rule[6],
                    ':apply_mode' => $rule[7],
                    ':notes' => $rule[8],
                    ':days_of_week' => $rule[9] ?? null,
                    ':occupancy_from' => $rule[1] === 'occupancy' ? 80 : null,
                ]);
            }

            pr_flash('success', 'Default pricing rules created.');
            header('Location: pricing_rules.php');
            exit;
        }

    } catch (Throwable $e) {
        pr_flash('danger', $e->getMessage());
        header('Location: pricing_rules.php');
        exit;
    }
}

$editId = (int)($_GET['edit_id'] ?? 0);
$editRule = null;

if ($editId > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM pricing_rules WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $editId]);
        $editRule = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (Throwable $e) {
        $editRule = null;
    }
}

$filterType = trim((string)($_GET['rule_type'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$filterPropertyId = (int)($_GET['property_id'] ?? 0);

$where = "1=1";
$params = [];

if ($filterType !== '') {
    $where .= " AND pr.rule_type = :rule_type ";
    $params[':rule_type'] = $filterType;
}

if ($filterStatus !== '') {
    $where .= " AND pr.is_active = :is_active ";
    $params[':is_active'] = (int)$filterStatus;
}

if ($filterPropertyId > 0) {
    $where .= " AND (pr.property_id = :filter_property_id OR pr.property_id IS NULL) ";
    $params[':filter_property_id'] = $filterPropertyId;
}

$rules = [];
$summary = [
    'total' => 0,
    'active' => 0,
    'inactive' => 0,
    'auto_apply' => 0,
    'suggest_only' => 0,
];

try {
    $stmt = $pdo->prepare("
        SELECT
            pr.*,
            p.name AS property_name,
            p.code AS property_code,
            rt.title AS room_type,
            TRIM(CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,''))) AS agent_name
        FROM pricing_rules pr
        LEFT JOIN properties p ON p.id = pr.property_id
        LEFT JOIN room_types rt ON rt.id = pr.room_type_id
        LEFT JOIN agents a ON a.id = pr.agent_id
        WHERE $where
        ORDER BY pr.is_active DESC, pr.priority ASC, pr.valid_from ASC, pr.rule_name ASC
    ");
    $stmt->execute($params);
    $rules = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rules as $rule) {
        $summary['total']++;
        if ((int)$rule['is_active'] === 1) $summary['active']++;
        else $summary['inactive']++;

        if (($rule['apply_mode'] ?? '') === 'auto_apply') $summary['auto_apply']++;
        else $summary['suggest_only']++;
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load pricing rules: ' . $e->getMessage();
}

$flashes = pr_get_flash();

function pr_checked_days(?string $daysOfWeek, int $day): string {
    $days = array_filter(array_map('trim', explode(',', (string)$daysOfWeek)));
    return in_array((string)$day, $days, true) ? 'checked' : '';
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50">
                <i class="bi bi-sliders"></i> Revenue Management
            </div>
            <div class="hero-title mt-2">Pricing Rules Manager</div>
            <div class="hero-subtitle mt-2">
                Control seasons, events, weekend premiums, occupancy rules, pickup rules and rate boundaries.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="pricing_engine_dashboard.php" class="btn btn-light me-2">
                <i class="bi bi-lightning-charge me-2"></i>Pricing Engine
            </a>
            <form method="post" class="d-inline">
                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                <input type="hidden" name="action" value="seed_defaults">
                <button type="submit" class="btn btn-outline-light" onclick="return confirm('Create default pricing rules?');">
                    <i class="bi bi-magic me-2"></i>Seed Defaults
                </button>
            </form>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-list-check"></i></div>
            <div><div class="metric-label">Total Rules</div><div class="metric-value"><?php echo (int)$summary['total']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-toggle-on"></i></div>
            <div><div class="metric-label">Active</div><div class="metric-value"><?php echo (int)$summary['active']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-lightbulb"></i></div>
            <div><div class="metric-label">Suggest Only</div><div class="metric-value"><?php echo (int)$summary['suggest_only']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-robot"></i></div>
            <div><div class="metric-label">Auto Apply</div><div class="metric-value"><?php echo (int)$summary['auto_apply']; ?></div></div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card sticky-xl-top" style="top: 20px;">
            <div class="card-header">
                <h5 class="mb-0"><?php echo $editRule ? 'Edit Pricing Rule' : 'Create Pricing Rule'; ?></h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_rule">
                    <input type="hidden" name="id" value="<?php echo (int)($editRule['id'] ?? 0); ?>">

                    <div class="mb-3">
                        <label class="form-label">Rule Name</label>
                        <input type="text" name="rule_name" class="form-control" required value="<?php echo h($editRule['rule_name'] ?? ''); ?>" placeholder="Peak Season Premium">
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Rule Type</label>
                            <select name="rule_type" class="form-select">
                                <?php foreach (['season'=>'Season','weekend'=>'Weekend','event'=>'Event / Holiday','occupancy'=>'Occupancy','pickup'=>'Pickup','manual'=>'Manual'] as $value => $label): ?>
                                    <option value="<?php echo h($value); ?>" <?php echo (($editRule['rule_type'] ?? 'season') === $value) ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Priority</label>
                            <input type="number" name="priority" class="form-control" value="<?php echo h($editRule['priority'] ?? 100); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Valid From</label>
                            <input type="date" name="valid_from" class="form-control" required value="<?php echo h($editRule['valid_from'] ?? date('Y-m-d')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Valid To</label>
                            <input type="date" name="valid_to" class="form-control" required value="<?php echo h($editRule['valid_to'] ?? date('Y-m-d', strtotime('+3 months'))); ?>">
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Property</label>
                        <select name="property_id" class="form-select">
                            <option value="0">All properties</option>
                            <?php foreach ($properties as $property): ?>
                                <option value="<?php echo (int)$property['id']; ?>" <?php echo (int)($editRule['property_id'] ?? 0) === (int)$property['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($property['name']); ?> - <?php echo h($property['code']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Room Type</label>
                        <select name="room_type_id" class="form-select">
                            <option value="0">All room types</option>
                            <?php foreach ($roomTypes as $rt): ?>
                                <option value="<?php echo (int)$rt['id']; ?>" <?php echo (int)($editRule['room_type_id'] ?? 0) === (int)$rt['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($rt['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Agent</label>
                        <select name="agent_id" class="form-select">
                            <option value="0">All agents / direct</option>
                            <?php foreach ($agents as $agent): ?>
                                <?php $agentName = trim(($agent['firstname'] ?? '') . ' ' . ($agent['lastname'] ?? '')); ?>
                                <option value="<?php echo (int)$agent['id']; ?>" <?php echo (int)($editRule['agent_id'] ?? 0) === (int)$agent['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($agentName ?: ('Agent #' . (int)$agent['id'])); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mt-3">
                        <label class="form-label d-block">Days of Week</label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php foreach ([1=>'Mon',2=>'Tue',3=>'Wed',4=>'Thu',5=>'Fri',6=>'Sat',7=>'Sun'] as $day => $label): ?>
                                <label class="day-pill">
                                    <input type="checkbox" name="days_of_week[]" value="<?php echo $day; ?>" <?php echo pr_checked_days($editRule['days_of_week'] ?? '', $day); ?>>
                                    <span><?php echo h($label); ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <div class="small text-muted mt-1">Leave blank to apply every day.</div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Adjustment Type</label>
                            <select name="adjustment_type" class="form-select">
                                <option value="percent" <?php echo (($editRule['adjustment_type'] ?? 'percent') === 'percent') ? 'selected' : ''; ?>>Percent %</option>
                                <option value="fixed" <?php echo (($editRule['adjustment_type'] ?? '') === 'fixed') ? 'selected' : ''; ?>>Fixed Amount</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Adjustment Value</label>
                            <input type="number" step="0.01" name="adjustment_value" class="form-control" value="<?php echo h($editRule['adjustment_value'] ?? 0); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Min Rate</label>
                            <input type="number" step="0.01" name="min_rate" class="form-control" value="<?php echo h($editRule['min_rate'] ?? ''); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Max Rate</label>
                            <input type="number" step="0.01" name="max_rate" class="form-control" value="<?php echo h($editRule['max_rate'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Occupancy From %</label>
                            <input type="number" step="0.01" name="occupancy_from" class="form-control" value="<?php echo h($editRule['occupancy_from'] ?? ''); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Occupancy To %</label>
                            <input type="number" step="0.01" name="occupancy_to" class="form-control" value="<?php echo h($editRule['occupancy_to'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Pickup From</label>
                            <input type="number" name="pickup_from" class="form-control" value="<?php echo h($editRule['pickup_from'] ?? ''); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Pickup To</label>
                            <input type="number" name="pickup_to" class="form-control" value="<?php echo h($editRule['pickup_to'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Apply Mode</label>
                            <select name="apply_mode" class="form-select">
                                <option value="suggest_only" <?php echo (($editRule['apply_mode'] ?? 'suggest_only') === 'suggest_only') ? 'selected' : ''; ?>>Suggest Only</option>
                                <option value="auto_apply" <?php echo (($editRule['apply_mode'] ?? '') === 'auto_apply') ? 'selected' : ''; ?>>Auto Apply</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status</label>
                            <select name="is_active" class="form-select">
                                <option value="1" <?php echo (int)($editRule['is_active'] ?? 1) === 1 ? 'selected' : ''; ?>>Active</option>
                                <option value="0" <?php echo (int)($editRule['is_active'] ?? 1) === 0 ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" rows="3" class="form-control" placeholder="Rule explanation or internal notes"><?php echo h($editRule['notes'] ?? ''); ?></textarea>
                    </div>

                    <div class="d-grid gap-2 mt-4">
                        <button class="btn btn-primary">
                            <i class="bi bi-save me-2"></i><?php echo $editRule ? 'Update Rule' : 'Create Rule'; ?>
                        </button>
                        <?php if ($editRule): ?>
                            <a href="pricing_rules.php" class="btn btn-outline-secondary">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label">Rule Type</label>
                        <select name="rule_type" class="form-select">
                            <option value="">All types</option>
                            <?php foreach (['season'=>'Season','weekend'=>'Weekend','event'=>'Event / Holiday','occupancy'=>'Occupancy','pickup'=>'Pickup','manual'=>'Manual'] as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo $filterType === $value ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <option value="1" <?php echo $filterStatus === '1' ? 'selected' : ''; ?>>Active</option>
                            <option value="0" <?php echo $filterStatus === '0' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Property</label>
                        <select name="property_id" class="form-select">
                            <option value="0">All</option>
                            <?php foreach ($properties as $property): ?>
                                <option value="<?php echo (int)$property['id']; ?>" <?php echo $filterPropertyId === (int)$property['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($property['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2 d-grid">
                        <button class="btn btn-primary"><i class="bi bi-funnel me-2"></i>Filter</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0">Pricing Rules</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Rule</th>
                            <th>Scope</th>
                            <th>Dates</th>
                            <th>Adjustment</th>
                            <th>Limits</th>
                            <th>Mode</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$rules): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No pricing rules found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($rules as $rule): ?>
                                <?php
                                $scope = [];
                                $scope[] = $rule['property_name'] ? ($rule['property_name'] . (!empty($rule['property_code']) ? ' - ' . $rule['property_code'] : '')) : 'All Properties';
                                $scope[] = $rule['room_type'] ?: 'All Room Types';
                                $agentName = trim((string)($rule['agent_name'] ?? ''));
                                $scope[] = $agentName !== '' ? $agentName : 'All Agents';

                                $daysText = 'Every day';
                                if (!empty($rule['days_of_week'])) {
                                    $dayMap = ['1'=>'Mon','2'=>'Tue','3'=>'Wed','4'=>'Thu','5'=>'Fri','6'=>'Sat','7'=>'Sun'];
                                    $names = [];
                                    foreach (explode(',', (string)$rule['days_of_week']) as $d) {
                                        $d = trim($d);
                                        if (isset($dayMap[$d])) $names[] = $dayMap[$d];
                                    }
                                    if ($names) $daysText = implode(', ', $names);
                                }

                                $adjSymbol = $rule['adjustment_type'] === 'percent' ? '%' : '';
                                $adjPrefix = (float)$rule['adjustment_value'] >= 0 ? '+' : '';
                                ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($rule['rule_name']); ?></strong>
                                        <div class="small text-muted">
                                            <?php echo h(ucwords(str_replace('_', ' ', $rule['rule_type']))); ?> • Priority <?php echo (int)$rule['priority']; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="data-stack">
                                            <?php foreach ($scope as $item): ?>
                                                <small><?php echo h($item); ?></small>
                                            <?php endforeach; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <strong><?php echo h($rule['valid_from']); ?></strong>
                                        <div class="small text-muted">to <?php echo h($rule['valid_to']); ?></div>
                                        <div class="small text-muted"><?php echo h($daysText); ?></div>
                                    </td>
                                    <td>
                                        <span class="fw-bold <?php echo (float)$rule['adjustment_value'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                            <?php echo h($adjPrefix . money_fmt($rule['adjustment_value']) . $adjSymbol); ?>
                                        </span>
                                        <div class="small text-muted"><?php echo h(ucwords($rule['adjustment_type'])); ?></div>
                                    </td>
                                    <td>
                                        <div class="small">Min: <?php echo $rule['min_rate'] !== null ? money_fmt($rule['min_rate']) : '—'; ?></div>
                                        <div class="small">Max: <?php echo $rule['max_rate'] !== null ? money_fmt($rule['max_rate']) : '—'; ?></div>
                                        <?php if ($rule['occupancy_from'] !== null || $rule['occupancy_to'] !== null): ?>
                                            <div class="small text-muted">Occ: <?php echo h($rule['occupancy_from'] ?? '0'); ?>% - <?php echo h($rule['occupancy_to'] ?? '100'); ?>%</div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo $rule['apply_mode'] === 'auto_apply' ? 'text-bg-danger' : 'text-bg-warning'; ?>">
                                            <?php echo h(ucwords(str_replace('_', ' ', $rule['apply_mode']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo (int)$rule['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>">
                                            <?php echo (int)$rule['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a href="pricing_rules.php?edit_id=<?php echo (int)$rule['id']; ?>" class="btn btn-outline-primary">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="toggle_rule">
                                                <input type="hidden" name="id" value="<?php echo (int)$rule['id']; ?>">
                                                <button type="submit" class="btn btn-outline-secondary">
                                                    <i class="bi bi-toggle-on"></i>
                                                </button>
                                            </form>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Delete this pricing rule?');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_rule">
                                                <input type="hidden" name="id" value="<?php echo (int)$rule['id']; ?>">
                                                <button type="submit" class="btn btn-outline-danger">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="alert alert-info mt-4">
            <strong>Important:</strong> Pricing rules are control settings. Your current pricing engine is still in safe suggestion mode unless you explicitly integrate auto-apply logic into your reservation pricing flow.
        </div>
    </div>
</div>

<style>
.day-pill{
    display:inline-flex;
    align-items:center;
    cursor:pointer;
}
.day-pill input{
    display:none;
}
.day-pill span{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:44px;
    height:34px;
    border-radius:999px;
    border:1px solid rgba(15,23,42,.12);
    background:#fff;
    font-weight:800;
    font-size:12px;
    color:#64748b;
    transition:.18s ease;
}
.day-pill input:checked + span{
    background:#111827;
    color:#fff;
    border-color:#111827;
}
.data-stack{
    display:flex;
    flex-direction:column;
    gap:2px;
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
