<?php
require_once __DIR__ . '/booking_setup_common.php';

bs_ensure_booking_setup_schema($pdo);

function bcr_condition_options(string $selected, array $options): string
{
    $html = '';
    foreach ($options as $value => $label) {
        $sel = ((string)$selected === (string)$value) ? ' selected' : '';
        $html .= '<option value="' . h($value) . '"' . $sel . '>' . h($label) . '</option>';
    }
    return $html;
}

function bcr_lookup_options(PDO $pdo, string $table, ?string $selected): string
{
    $html = '<option value="">Any / Not Applicable</option>';
    foreach (bs_get_lookup_options($pdo, $table, false) as $row) {
        $code = (string)$row['code'];
        $sel = ((string)$selected === $code) ? ' selected' : '';
        $html .= '<option value="' . h($code) . '"' . $sel . '>' . h($row['name'] . ' [' . $code . ']') . '</option>';
    }
    return $html;
}

function bcr_validate_hex(string $value, string $fallback): string
{
    $value = trim($value);
    if (preg_match('/^#[0-9A-Fa-f]{6}$/', $value)) {
        return strtoupper($value);
    }
    return $fallback;
}

try {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
        if (function_exists('verify_csrf')) {
            verify_csrf();
        }
        $action = (string)($_POST['action'] ?? '');
        $id = (int)($_POST['id'] ?? 0);

        if ($action === 'delete') {
            if ($id <= 0) throw new RuntimeException('Invalid rule selected.');
            $stmt = $pdo->prepare("UPDATE booking_color_codes SET is_active = 0, updated_by = :updated_by WHERE id = :id");
            $stmt->execute([':id' => $id, ':updated_by' => bs_current_user_id()]);
            bs_flash('success', 'Color rule disabled.');
            header('Location: booking_color_rules.php'); exit;
        }

        if ($action === 'save') {
            $ruleKey = bs_safe_code((string)($_POST['rule_key'] ?? ''));
            $ruleName = trim((string)($_POST['rule_name'] ?? ''));
            $bookingStatus = trim((string)($_POST['booking_status_code'] ?? ''));
            $paymentDue = trim((string)($_POST['payment_due_code'] ?? ''));
            $paymentStatus = trim((string)($_POST['payment_status_code'] ?? ''));
            $bookingSource = trim((string)($_POST['booking_source_code'] ?? ''));
            $invoicedCondition = (string)($_POST['invoiced_condition'] ?? 'any');
            $balanceCondition = (string)($_POST['balance_condition'] ?? 'any');
            $bgColor = bcr_validate_hex((string)($_POST['bg_color'] ?? ''), '#9CA3AF');
            $textColor = bcr_validate_hex((string)($_POST['text_color'] ?? ''), '#FFFFFF');
            $priorityNo = (int)($_POST['priority_no'] ?? 100);
            $cssClass = trim((string)($_POST['css_class'] ?? ''));
            $description = trim((string)($_POST['description'] ?? ''));
            $isActive = isset($_POST['is_active']) ? 1 : 0;

            if ($ruleKey === '') throw new RuntimeException('Rule key is required.');
            if ($ruleName === '') throw new RuntimeException('Rule name is required.');
            if (!in_array($invoicedCondition, ['any','yes','no'], true)) $invoicedCondition = 'any';
            if (!in_array($balanceCondition, ['any','has_balance','no_balance'], true)) $balanceCondition = 'any';

            if ($id > 0) {
                $stmt = $pdo->prepare("UPDATE booking_color_codes SET
                    rule_key = :rule_key,
                    rule_name = :rule_name,
                    booking_status_code = :booking_status_code,
                    payment_due_code = :payment_due_code,
                    payment_status_code = :payment_status_code,
                    booking_source_code = :booking_source_code,
                    invoiced_condition = :invoiced_condition,
                    balance_condition = :balance_condition,
                    bg_color = :bg_color,
                    text_color = :text_color,
                    priority_no = :priority_no,
                    css_class = :css_class,
                    description = :description,
                    is_active = :is_active,
                    updated_by = :updated_by
                    WHERE id = :id");
                $stmt->execute([
                    ':rule_key' => $ruleKey,
                    ':rule_name' => $ruleName,
                    ':booking_status_code' => $bookingStatus !== '' ? $bookingStatus : null,
                    ':payment_due_code' => $paymentDue !== '' ? $paymentDue : null,
                    ':payment_status_code' => $paymentStatus !== '' ? $paymentStatus : null,
                    ':booking_source_code' => $bookingSource !== '' ? $bookingSource : null,
                    ':invoiced_condition' => $invoicedCondition,
                    ':balance_condition' => $balanceCondition,
                    ':bg_color' => $bgColor,
                    ':text_color' => $textColor,
                    ':priority_no' => $priorityNo,
                    ':css_class' => $cssClass !== '' ? $cssClass : null,
                    ':description' => $description !== '' ? $description : null,
                    ':is_active' => $isActive,
                    ':updated_by' => bs_current_user_id(),
                    ':id' => $id,
                ]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO booking_color_codes
                    (rule_key, rule_name, booking_status_code, payment_due_code, payment_status_code, booking_source_code, invoiced_condition, balance_condition, bg_color, text_color, priority_no, css_class, description, is_active, created_by)
                    VALUES
                    (:rule_key, :rule_name, :booking_status_code, :payment_due_code, :payment_status_code, :booking_source_code, :invoiced_condition, :balance_condition, :bg_color, :text_color, :priority_no, :css_class, :description, :is_active, :created_by)");
                $stmt->execute([
                    ':rule_key' => $ruleKey,
                    ':rule_name' => $ruleName,
                    ':booking_status_code' => $bookingStatus !== '' ? $bookingStatus : null,
                    ':payment_due_code' => $paymentDue !== '' ? $paymentDue : null,
                    ':payment_status_code' => $paymentStatus !== '' ? $paymentStatus : null,
                    ':booking_source_code' => $bookingSource !== '' ? $bookingSource : null,
                    ':invoiced_condition' => $invoicedCondition,
                    ':balance_condition' => $balanceCondition,
                    ':bg_color' => $bgColor,
                    ':text_color' => $textColor,
                    ':priority_no' => $priorityNo,
                    ':css_class' => $cssClass !== '' ? $cssClass : null,
                    ':description' => $description !== '' ? $description : null,
                    ':is_active' => $isActive,
                    ':created_by' => bs_current_user_id(),
                ]);
            }

            bs_flash('success', 'Color rule saved.');
            header('Location: booking_color_rules.php'); exit;
        }
    }
} catch (Throwable $e) {
    bs_flash('danger', $e->getMessage());
}

$editId = (int)($_GET['edit_id'] ?? 0);
$edit = null;
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM booking_color_codes WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $editId]);
    $edit = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$stmt = $pdo->query("SELECT * FROM booking_color_codes ORDER BY is_active DESC, priority_no ASC, rule_name ASC");
$rules = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

bs_render_header('Booking Color Rules');
echo '<div class="setup-wrap">';
bs_render_setup_tabs('color_rules');
bs_render_flashes();

echo '<div class="setup-card"><div class="setup-card-header"><h3>Booking Color Rules</h3><a class="setup-btn setup-btn-light" href="booking_color_rules.php">New Rule</a></div><div class="setup-card-body">';
echo '<form method="post"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="' . h((string)($edit['id'] ?? 0)) . '">';
if (function_exists('csrf_input')) { echo csrf_input(); }
echo '<div class="setup-grid">';
echo '<div class="setup-col-3"><label class="setup-label">Rule Key</label><input class="setup-input" name="rule_key" value="' . h($edit['rule_key'] ?? '') . '" placeholder="e.g. CHASE_PAYMENT" required></div>';
echo '<div class="setup-col-4"><label class="setup-label">Rule Name</label><input class="setup-input" name="rule_name" value="' . h($edit['rule_name'] ?? '') . '" placeholder="e.g. Chase Payment" required></div>';
echo '<div class="setup-col-2"><label class="setup-label">Priority</label><input class="setup-input" type="number" name="priority_no" value="' . h((string)($edit['priority_no'] ?? 100)) . '"></div>';
$checked = !isset($edit['is_active']) || (int)$edit['is_active'] === 1 ? 'checked' : '';
echo '<div class="setup-col-3"><label class="setup-label">Active</label><label><input type="checkbox" name="is_active" value="1" ' . $checked . '> Active rule</label></div>';

echo '<div class="setup-col-3"><label class="setup-label">Booking Status</label><select class="setup-select" name="booking_status_code">' . bcr_lookup_options($pdo, 'booking_statuses', $edit['booking_status_code'] ?? '') . '</select></div>';
echo '<div class="setup-col-3"><label class="setup-label">Payment Due</label><select class="setup-select" name="payment_due_code">' . bcr_lookup_options($pdo, 'booking_payment_due_types', $edit['payment_due_code'] ?? '') . '</select></div>';
echo '<div class="setup-col-3"><label class="setup-label">Payment Status</label><select class="setup-select" name="payment_status_code">' . bcr_lookup_options($pdo, 'booking_payment_statuses', $edit['payment_status_code'] ?? '') . '</select></div>';
echo '<div class="setup-col-3"><label class="setup-label">Booking Source</label><select class="setup-select" name="booking_source_code">' . bcr_lookup_options($pdo, 'booking_sources', $edit['booking_source_code'] ?? '') . '</select></div>';

echo '<div class="setup-col-3"><label class="setup-label">Invoiced Condition</label><select class="setup-select" name="invoiced_condition">' . bcr_condition_options((string)($edit['invoiced_condition'] ?? 'any'), ['any'=>'Any','yes'=>'Yes - must be invoiced','no'=>'No - must not be invoiced']) . '</select></div>';
echo '<div class="setup-col-3"><label class="setup-label">Balance Condition</label><select class="setup-select" name="balance_condition">' . bcr_condition_options((string)($edit['balance_condition'] ?? 'any'), ['any'=>'Any','has_balance'=>'Has Balance','no_balance'=>'No Balance']) . '</select></div>';
echo '<div class="setup-col-2"><label class="setup-label">Background</label><input class="setup-input" type="color" name="bg_color" value="' . h($edit['bg_color'] ?? '#9CA3AF') . '"></div>';
echo '<div class="setup-col-2"><label class="setup-label">Text Color</label><input class="setup-input" type="color" name="text_color" value="' . h($edit['text_color'] ?? '#FFFFFF') . '"></div>';
echo '<div class="setup-col-2"><label class="setup-label">CSS Class</label><input class="setup-input" name="css_class" value="' . h($edit['css_class'] ?? '') . '" placeholder="optional"></div>';
echo '<div class="setup-col-12"><label class="setup-label">Description</label><input class="setup-input" name="description" value="' . h($edit['description'] ?? '') . '"></div>';
echo '<div class="setup-col-12"><button class="setup-btn setup-btn-primary" type="submit">Save Color Rule</button></div>';
echo '</div></form></div></div>';

echo '<div class="setup-card"><div class="setup-card-header"><h3>Rules Priority List</h3></div><div class="setup-card-body"><p style="color:#64748b;margin-top:0">Lower priority number wins. For example, Active Out with balance should be above Confirmed.</p><div class="table-responsive"><table class="setup-table"><thead><tr><th>Preview</th><th>Priority</th><th>Rule</th><th>Conditions</th><th>Status</th><th style="width:160px">Action</th></tr></thead><tbody>';
foreach ($rules as $row) {
    $conditions = [];
    if (!empty($row['booking_status_code'])) $conditions[] = 'Status: ' . $row['booking_status_code'];
    if (!empty($row['payment_due_code'])) $conditions[] = 'Due: ' . $row['payment_due_code'];
    if (!empty($row['payment_status_code'])) $conditions[] = 'Payment: ' . $row['payment_status_code'];
    if (!empty($row['booking_source_code'])) $conditions[] = 'Source: ' . $row['booking_source_code'];
    if (($row['invoiced_condition'] ?? 'any') !== 'any') $conditions[] = 'Invoiced: ' . $row['invoiced_condition'];
    if (($row['balance_condition'] ?? 'any') !== 'any') $conditions[] = 'Balance: ' . str_replace('_', ' ', $row['balance_condition']);
    if (!$conditions) $conditions[] = 'Default / fallback rule';

    echo '<tr>';
    echo '<td><span class="setup-pill" style="background:' . h($row['bg_color']) . ';color:' . h($row['text_color']) . '">' . h($row['rule_name']) . '</span></td>';
    echo '<td><strong>' . h((string)$row['priority_no']) . '</strong></td>';
    echo '<td><strong>' . h($row['rule_key']) . '</strong><br><span style="color:#64748b">' . h($row['description'] ?? '') . '</span></td>';
    echo '<td>' . h(implode(' | ', $conditions)) . '</td>';
    echo '<td>' . ((int)$row['is_active'] === 1 ? '<span class="setup-pill" style="background:#dcfce7;color:#166534">Active</span>' : '<span class="setup-pill" style="background:#fee2e2;color:#991b1b">Disabled</span>') . '</td>';
    echo '<td><a class="setup-btn setup-btn-light" href="booking_color_rules.php?edit_id=' . (int)$row['id'] . '">Edit</a> ';
    echo '<form method="post" style="display:inline" onsubmit="return confirm(\'Disable this rule?\')"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="' . (int)$row['id'] . '">';
    if (function_exists('csrf_input')) { echo csrf_input(); }
    echo '<button class="setup-btn setup-btn-danger" type="submit">Disable</button></form></td>';
    echo '</tr>';
}
if (!$rules) {
    echo '<tr><td colspan="6">No color rules found.</td></tr>';
}
echo '</tbody></table></div></div></div></div>';
bs_render_footer();
