<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<h1 class="h3 mb-3">Settings</h1>

<ul class="nav nav-tabs mb-3" id="settingsTabs">
    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-hotel">Hotel Information</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-billing">Billing</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-integrations">Integrations</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-widget">Booking Widget</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-ai">AI Features</a></li>
</ul>

<div class="tab-content">
    <div class="tab-pane fade show active" id="tab-hotel">
        <p class="text-muted">Your hotel's name, logo, and brand colors — shown across the app and on generated invoices/reports.</p>

        <form action="<?= site_url('settings/hotel-info') ?>" method="post" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label small fw-semibold">Hotel Name</label>
                            <input type="text" class="form-control" name="hotel_name" value="<?= esc($tenant->hotel_name ?? '') ?>" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small fw-semibold">Primary Color</label>
                            <input type="color" class="form-control form-control-color w-100" name="primary_color" value="<?= esc(safe_hex_color($tenant->primary_color ?? null, '#4f46e5')) ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small fw-semibold">Secondary Color</label>
                            <input type="color" class="form-control form-control-color w-100" name="secondary_color" value="<?= esc(safe_hex_color($tenant->secondary_color ?? null, '#16182b')) ?>">
                        </div>
                    </div>
                    <div class="row align-items-end">
                        <div class="col-md-6 mb-3">
                            <label class="form-label small fw-semibold">Logo <span class="text-muted fw-normal">(JPG, PNG, or WEBP — max 2MB)</span></label>
                            <input type="file" class="form-control" name="logo" accept="image/jpeg,image/png,image/webp">
                        </div>
                        <div class="col-md-6 mb-3">
                            <?php if (! empty($tenant->logo_path)): ?>
                                <div class="text-muted small mb-1">Current logo</div>
                                <img src="<?= site_url('uploads/' . $tenant->logo_path) ?>" alt="Current logo" style="max-height: 60px; max-width: 200px;" class="border rounded p-1">
                            <?php else: ?>
                                <div class="text-muted small">No logo uploaded yet — the hotel name is shown as text everywhere a logo would go.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check2 me-1"></i>Save Hotel Information</button>
                </div>
            </div>
        </form>
    </div>

    <div class="tab-pane fade" id="tab-billing">
        <p class="text-muted">Applies to the New Booking wizard's pricing summary and any other place a total is quoted before a folio exists.</p>
        <form action="<?= site_url('settings') ?>" method="post">
            <?= csrf_field() ?>
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Tax</h2>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Tax Rate</label>
                            <div class="input-group">
                                <input type="number" step="0.01" min="0" max="100" class="form-control" name="billing__tax_rate_percent" value="<?= esc($values['billing.tax_rate_percent'] ?: '0') ?>">
                                <span class="input-group-text">%</span>
                            </div>
                            <div class="form-text">0 means no tax line is shown anywhere.</div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-check2 me-1"></i>Save</button>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Display Currency</h2>
                    <p class="text-muted small">GHS stays the real currency for payments and reports — this only adds an informational "&asymp; converted" line for foreign guests on guest-facing screens (booking payment, folio/invoice). Rate is set manually here, not fetched live.</p>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Currency Code</label>
                            <input type="text" class="form-control" name="billing__display_currency_code" maxlength="3" style="text-transform: uppercase;" placeholder="e.g. USD" value="<?= esc($values['billing.display_currency_code'] ?? '') ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Exchange Rate</label>
                            <div class="input-group">
                                <span class="input-group-text">1 GHS =</span>
                                <input type="number" step="0.0001" min="0" class="form-control" name="billing__display_exchange_rate" value="<?= esc($values['billing.display_exchange_rate'] ?? '') ?>">
                            </div>
                            <div class="form-text">Blank or 0 on either field hides the conversion line entirely.</div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-check2 me-1"></i>Save</button>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Website Booking Widget — Deposit</h2>
                    <p class="text-muted small">A visitor booking directly through your website widget pays this percentage of the room total online, upfront, to confirm the booking instantly — there's no staff review step before then. 100% (full prepayment) is the safest default; lower it only if you're comfortable holding a room on a partial payment.</p>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Deposit Required</label>
                            <div class="input-group">
                                <input type="number" step="1" min="1" max="100" class="form-control" name="billing__widget_deposit_percent" value="<?= esc($values['billing.widget_deposit_percent'] ?: '100') ?>">
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-check2 me-1"></i>Save</button>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Loyalty Programme</h2>
                    <p class="text-muted small">Points are earned automatically on every real payment recorded on a folio, wherever it happens — front desk, check-in, or the restaurant.</p>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Earn Rate</label>
                            <div class="input-group">
                                <span class="input-group-text">GHS</span>
                                <input type="number" step="1" min="1" class="form-control" name="loyalty__points_per_ghs_rate" value="<?= esc($values['loyalty.points_per_ghs_rate'] ?: '10') ?>">
                                <span class="input-group-text">= 1 point</span>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Silver Tier At</label>
                            <div class="input-group">
                                <input type="number" step="1" min="0" class="form-control" name="loyalty__tier_silver_threshold" value="<?= esc($values['loyalty.tier_silver_threshold'] ?: '500') ?>">
                                <span class="input-group-text">points</span>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Gold Tier At</label>
                            <div class="input-group">
                                <input type="number" step="1" min="0" class="form-control" name="loyalty__tier_gold_threshold" value="<?= esc($values['loyalty.tier_gold_threshold'] ?: '2000') ?>">
                                <span class="input-group-text">points</span>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Redemption Value</label>
                            <div class="input-group">
                                <span class="input-group-text">GHS</span>
                                <input type="number" step="0.01" min="0.01" class="form-control" name="loyalty__redemption_value_per_point" value="<?= esc($values['loyalty.redemption_value_per_point'] ?: '0.10') ?>">
                                <span class="input-group-text">/ point</span>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-check2 me-1"></i>Save</button>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Expense Approval</h2>
                    <p class="text-muted small">Expenses logged below this amount are approved automatically. At or above it, they sit pending until a manager reviews them — only approved expenses count toward the Profit &amp; Loss report.</p>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Auto-Approval Threshold</label>
                            <div class="input-group">
                                <span class="input-group-text">GHS</span>
                                <input type="number" step="0.01" min="0" class="form-control" name="expenses__approval_threshold_amount" value="<?= esc($values['expenses.approval_threshold_amount'] ?: '500') ?>">
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-check2 me-1"></i>Save</button>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Executive Dining Membership</h2>
                    <p class="text-muted small">A separate, staff-enrolled club (distinct from the loyalty programme above). Benefit text is free-form — shown to staff on the guest's Executive Dining card.</p>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Silver Benefits</label>
                            <textarea class="form-control" name="dining__silver_benefits" rows="2" placeholder="e.g. 1 free dessert per visit"><?= esc($values['dining.silver_benefits'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Gold Benefits</label>
                            <textarea class="form-control" name="dining__gold_benefits" rows="2" placeholder="e.g. 2 free desserts/month, 10% off food"><?= esc($values['dining.gold_benefits'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Platinum Benefits</label>
                            <textarea class="form-control" name="dining__platinum_benefits" rows="2" placeholder="e.g. Complimentary bottle of wine, priority seating"><?= esc($values['dining.platinum_benefits'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Membership Duration</label>
                            <div class="input-group">
                                <input type="number" step="1" min="1" class="form-control" name="dining__membership_duration_months" value="<?= esc($values['dining.membership_duration_months'] ?: '12') ?>">
                                <span class="input-group-text">months</span>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-check2 me-1"></i>Save</button>
                </div>
            </div>
        </form>
    </div>

    <div class="tab-pane fade" id="tab-integrations">
        <p class="text-muted">
            Stored per-hotel in this tenant's own database — never in a shared config file, since
            every hotel has its own Hubtel and WhatsApp accounts. Secret fields are encrypted at
            rest and shown masked below; leave a secret field blank when saving to keep its
            current value.
        </p>

        <form action="<?= site_url('settings') ?>" method="post">
            <?= csrf_field() ?>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Hubtel Checkout (payments)</h2>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Client ID</label>
                            <input type="text" class="form-control" name="hubtel__client_id" value="<?= esc($values['hubtel.client_id']) ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Client Secret</label>
                            <input type="password" class="form-control" name="hubtel__client_secret" placeholder="<?= $values['hubtel.client_secret'] ? 'Configured — leave blank to keep' : 'Not configured' ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Merchant Account Number</label>
                            <input type="text" class="form-control" name="hubtel__merchant_account_number" value="<?= esc($values['hubtel.merchant_account_number']) ?>">
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Hubtel SMS</h2>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Client ID</label>
                            <input type="text" class="form-control" name="hubtel__sms__client_id" value="<?= esc($values['hubtel.sms.client_id']) ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Client Secret</label>
                            <input type="password" class="form-control" name="hubtel__sms__client_secret" placeholder="<?= $values['hubtel.sms.client_secret'] ? 'Configured — leave blank to keep' : 'Not configured' ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Sender ID</label>
                            <input type="text" class="form-control" name="hubtel__sms__sender_id" value="<?= esc($values['hubtel.sms.sender_id']) ?>" placeholder="e.g. MaxYieldsPMS">
                        </div>
                    </div>
                    <hr>
                    <div class="row g-2 align-items-end">
                        <div class="col-md-6">
                            <label class="form-label small">Send a real test SMS to</label>
                            <input type="text" class="form-control form-control-sm" id="testSmsPhone" placeholder="e.g. 024 123 4567">
                        </div>
                        <div class="col-md-3">
                            <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="testSmsBtn">Send Test SMS</button>
                        </div>
                    </div>
                    <div class="small mt-2 d-none" id="testSmsResult"></div>
                    <div class="form-text">Tests whatever is currently saved above, not unsaved changes — save first if you just edited these fields. Sends a real SMS using your Hubtel credits.</div>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">WhatsApp (Meta Cloud API)</h2>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label small">Phone Number ID</label>
                            <input type="text" class="form-control" name="whatsapp__phone_number_id" value="<?= esc($values['whatsapp.phone_number_id']) ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label small">Access Token</label>
                            <input type="password" class="form-control" name="whatsapp__access_token" placeholder="<?= $values['whatsapp.access_token'] ? 'Configured — leave blank to keep' : 'Not configured' ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label small">Webhook Verify Token</label>
                            <input type="password" class="form-control" name="whatsapp__webhook_verify_token" placeholder="<?= $values['whatsapp.webhook_verify_token'] ? 'Configured — leave blank to keep' : 'Not configured' ?>">
                            <div class="form-text">A string you choose, entered on both sides — required for the WhatsApp Concierge (see the AI Features tab) to receive inbound messages from Meta.</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label small">Webhook Callback URL</label>
                            <input type="text" class="form-control" readonly value="<?= esc($conciergeWebhookUrl) ?>">
                            <div class="form-text">Paste this and the verify token above into your Meta App's WhatsApp &gt; Configuration &gt; Webhook settings.</div>
                        </div>
                    </div>
                    <hr>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="testWhatsappBtn">Test Connection</button>
                    <div class="small mt-2 d-none" id="testWhatsappResult"></div>
                    <div class="form-text">Verifies the Phone Number ID and Access Token above are valid and authenticate with Meta — doesn't send a real message (that needs a template your Meta account has already had approved, which varies per hotel).</div>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Email (SMTP)</h2>
                    <p class="text-muted small">Used for staff-initiated sends like "Email Invoice" from a folio — separate from the guest-messaging channels below, which are SMS/WhatsApp only.</p>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label small">SMTP Host</label>
                            <input type="text" class="form-control" name="email__smtp_host" value="<?= esc($values['email.smtp_host']) ?>" placeholder="e.g. smtp.gmail.com">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Port</label>
                            <input type="number" class="form-control" name="email__smtp_port" value="<?= esc($values['email.smtp_port'] ?: 587) ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Encryption</label>
                            <select class="form-select" name="email__smtp_encryption">
                                <?php foreach (['tls' => 'TLS', 'ssl' => 'SSL'] as $key => $label): ?>
                                    <option value="<?= $key ?>" <?= ($values['email.smtp_encryption'] ?: 'tls') === $key ? 'selected' : '' ?>><?= $label ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">SMTP Username</label>
                            <input type="text" class="form-control" name="email__smtp_username" value="<?= esc($values['email.smtp_username']) ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">SMTP Password</label>
                            <input type="password" class="form-control" name="email__smtp_password" placeholder="<?= $values['email.smtp_password'] ? 'Configured — leave blank to keep' : 'Not configured' ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">From Name</label>
                            <input type="text" class="form-control" name="email__from_name" value="<?= esc($values['email.from_name']) ?>" placeholder="<?= esc($tenant->hotel_name ?? 'Your Hotel') ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label small">From Address</label>
                            <input type="email" class="form-control" name="email__from_address" value="<?= esc($values['email.from_address']) ?>" placeholder="e.g. frontdesk@yourhotel.com">
                        </div>
                    </div>
                    <hr>
                    <div class="row g-2 align-items-end">
                        <div class="col-md-6">
                            <label class="form-label small">Send a real test email to</label>
                            <input type="email" class="form-control form-control-sm" id="testEmailAddress" placeholder="e.g. you@yourhotel.com">
                        </div>
                        <div class="col-md-3">
                            <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="testEmailBtn">Send Test Email</button>
                        </div>
                    </div>
                    <div class="small mt-2 d-none" id="testEmailResult"></div>
                    <div class="form-text">Tests whatever is currently saved above, not unsaved changes — save first if you just edited these fields.</div>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Message Channels</h2>
                    <p class="text-muted small">Choose WhatsApp, SMS, or both for each automated message type.</p>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Booking Confirmation</label>
                            <select class="form-select" name="messaging__booking_confirmation__channel">
                                <?php foreach ($lookups->messagingChannels as $key => $meta): ?>
                                    <option value="<?= esc($key) ?>" <?= $values['messaging.booking_confirmation.channel'] === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Pre-Arrival Reminder</label>
                            <select class="form-select" name="messaging__pre_arrival__channel">
                                <?php foreach ($lookups->messagingChannels as $key => $meta): ?>
                                    <option value="<?= esc($key) ?>" <?= $values['messaging.pre_arrival.channel'] === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Post-Stay Feedback Request</label>
                            <select class="form-select" name="messaging__post_stay_feedback__channel">
                                <?php foreach ($lookups->messagingChannels as $key => $meta): ?>
                                    <option value="<?= esc($key) ?>" <?= $values['messaging.post_stay_feedback.channel'] === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Birthday Offer</label>
                            <select class="form-select" name="messaging__birthday_offer__channel">
                                <?php foreach ($lookups->messagingChannels as $key => $meta): ?>
                                    <option value="<?= esc($key) ?>" <?= $values['messaging.birthday_offer.channel'] === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Anniversary Offer</label>
                            <select class="form-select" name="messaging__anniversary_offer__channel">
                                <?php foreach ($lookups->messagingChannels as $key => $meta): ?>
                                    <option value="<?= esc($key) ?>" <?= $values['messaging.anniversary_offer.channel'] === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Birthday &amp; Anniversary Marketing</h2>
                    <p class="text-muted small">Sent automatically once a day per guest whose birthday/anniversary is today (<code>php spark guests:send-birthday-offers</code>). Use <code>{name}</code> for the guest's first name.</p>
                    <div class="mb-3">
                        <label class="form-label small">Birthday Message</label>
                        <textarea class="form-control" name="marketing__birthday_offer_message" rows="2" placeholder="Happy Birthday, {name}! Enjoy 15% off your next stay with us this month."><?= esc($values['marketing.birthday_offer_message'] ?? '') ?></textarea>
                    </div>
                    <div class="mb-1">
                        <label class="form-label small">Anniversary Message</label>
                        <textarea class="form-control" name="marketing__anniversary_offer_message" rows="2" placeholder="Happy Anniversary, {name}! Celebrate with a complimentary room upgrade on your next visit."><?= esc($values['marketing.anniversary_offer_message'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <button type="submit" class="btn btn-primary">Save Settings</button>
        </form>
    </div>

    <div class="tab-pane fade" id="tab-widget">
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h2 class="h6"><i class="bi bi-window me-1"></i>Embed Your Booking Widget</h2>
                <p class="text-muted small">Paste this on your own website (any builder — WordPress, Wix, Squarespace, plain HTML) to let visitors search availability and book a room directly, with instant online confirmation. No plugin needed.</p>
                <div class="input-group">
                    <textarea class="form-control font-monospace small" id="widgetSnippet" rows="2" readonly><iframe src="<?= esc($widgetEmbedUrl) ?>" style="width: 100%; max-width: 480px; height: 640px; border: 0; border-radius: 12px;" title="Book a room"></iframe></textarea>
                    <button type="button" class="btn btn-outline-secondary" id="copySnippetBtn"><i class="bi bi-clipboard me-1"></i>Copy</button>
                </div>
                <div class="form-text">Deposit-to-confirm percentage is set on the Billing tab under "Website Booking Widget — Deposit".</div>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-body">
                <h2 class="h6">Preview</h2>
                <iframe src="<?= esc($widgetEmbedUrl) ?>" style="width: 100%; max-width: 480px; height: 640px; border: 1px solid #eef0f3; border-radius: 12px;" title="Widget preview"></iframe>
            </div>
        </div>
    </div>

    <div class="tab-pane fade" id="tab-ai">
        <p class="text-muted">
            Real Claude AI features, built on top of your own hotel's real data — never fabricated
            figures. Distinct from the rule-based <a href="<?= site_url('ai-modules') ?>">AI Modules</a>
            page, which doesn't call any AI service. See each feature's own guardrails below.
        </p>

        <form action="<?= site_url('settings') ?>" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="ai_settings_submitted" value="1">

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Anthropic API</h2>
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <label class="form-label small">API Key</label>
                            <input type="password" class="form-control" name="ai__claude_api_token" placeholder="<?= $values['ai.claude_api_token'] ? 'Configured — leave blank to keep' : 'Not configured — AI features will show a clear error until this is set' ?>">
                            <div class="form-text">From your Anthropic Console — stored encrypted, same as your Hubtel/WhatsApp credentials.</div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label small">Model</label>
                            <input type="text" class="form-control" name="ai__claude_model" value="<?= esc($values['ai.claude_model'] ?? '') ?>" placeholder="claude-sonnet-5">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label small">Brand Voice <span class="text-muted fw-normal">(optional)</span></label>
                            <input type="text" class="form-control" name="ai__brand_voice" value="<?= esc($values['ai.brand_voice'] ?? '') ?>" placeholder="e.g. warm and upscale, playful and casual, formal and traditional">
                            <div class="form-text">Used by the Menu &amp; Event Description Writer to match your hotel's tone — defaults to a professional/warm/welcoming tone if left blank.</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Staff &amp; Internal Features</h2>
                    <p class="text-muted small">On by default — none of these are guest-facing.</p>
                    <?php
                    $staffFeatures = [
                        'ai.kpi_narration_enabled'        => ['label' => 'KPI Narration', 'desc' => 'Plain-language summary of the Reports page\'s real computed KPIs.'],
                        'ai.maintenance_triage_enabled'   => ['label' => 'Maintenance Triage', 'desc' => 'Suggests a priority/handling role from a work order\'s title and notes.'],
                        'ai.daily_briefing_enabled'       => ['label' => 'Daily Briefing', 'desc' => 'Morning summary of arrivals, VIPs, low stock, and open tickets — on the Dashboard. Also run daily via <code>php spark ai:daily-briefing</code>.'],
                        'ai.smart_guest_search_enabled'   => ['label' => 'Smart Guest Search', 'desc' => 'Natural-language guest search over notes/preferences/complaints &mdash; on the Guests page.'],
                        'ai.staff_assistant_enabled'      => ['label' => 'Staff Booking Assistant', 'desc' => 'Read-only chat over real availability/rates/bookings &mdash; in the sidebar nav.'],
                        'ai.menu_event_writer_enabled'    => ['label' => 'Menu &amp; Event Description Writer', 'desc' => 'Drafts a description from a short prompt &mdash; on the Menu Item and Event forms.'],
                        'ai.preference_inference_enabled' => ['label' => 'Guest Preference Inference', 'desc' => 'Background summary of a guest\'s real order/stay history &mdash; run via <code>php spark ai:infer-guest-preferences</code>, shown on the guest profile.'],
                        'ai.anomaly_flagging_enabled'     => ['label' => 'Revenue/Occupancy Anomaly Flagging', 'desc' => 'Flags unusual week-over-week patterns &mdash; run via <code>php spark ai:flag-anomalies</code>, shown under AI Alerts.'],
                        'ai.corporate_summary_enabled'    => ['label' => 'Corporate Account Health Summary', 'desc' => 'Short trend note comparing a corporate account\'s real spend this month vs last &mdash; on the account\'s monthly statement PDF.'],
                    ];
                    foreach ($staffFeatures as $key => $meta): ?>
                        <div class="form-check form-switch mb-2">
                            <input class="form-check-input" type="checkbox" role="switch" name="<?= str_replace('.', '__', $key) ?>" id="<?= str_replace('.', '_', $key) ?>" <?= $aiToggles[$key] ? 'checked' : '' ?>>
                            <label class="form-check-label" for="<?= str_replace('.', '_', $key) ?>"><?= $meta['label'] ?> <span class="text-muted small d-block"><?= $meta['desc'] ?></span></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Guest-Facing Features</h2>
                    <p class="text-muted small">Off by default. Even once enabled, messages are only <strong>drafted</strong> for staff review — turning on a feature here does not send anything to a guest by itself. A separate "auto-send" flag (also off by default) is what's required for a draft to go out without a human clicking Send.</p>
                    <div class="row g-2 align-items-end mb-3">
                        <div class="col-md-4">
                            <label class="form-label small">Pre-Arrival Upsell: Days Ahead</label>
                            <input type="number" min="1" max="14" class="form-control form-control-sm" name="ai__pre_arrival_upsell_days_ahead" value="<?= esc($values['ai.pre_arrival_upsell_days_ahead'] ?: '2') ?>">
                            <div class="form-text">How many days before check-in to draft the suggestion.</div>
                        </div>
                    </div>
                    <?php
                    $guestFeatures = [
                        'ai.post_checkout_thankyou_enabled' => ['label' => 'Post-Checkout Thank-You', 'autosend' => 'ai.autosend_post_checkout_thankyou', 'desc' => 'Drafted from that stay\'s real folio/event history when a guest checks out &mdash; queued under Guest Message Drafts unless auto-send is also on.'],
                        'ai.pre_arrival_upsell_enabled'     => ['label' => 'Pre-Arrival Upsell Suggestions', 'autosend' => 'ai.autosend_pre_arrival_upsell', 'desc' => 'Only suggests add-ons/upgrades confirmed genuinely available &mdash; run via <code>php spark ai:pre-arrival-upsell</code>, queued under Guest Message Drafts.'],
                        'ai.concierge_enabled'              => ['label' => 'WhatsApp Concierge', 'autosend' => 'ai.autosend_concierge_replies', 'desc' => 'Answers FAQs about check-in/out, wifi, dining, and events for a real guest with an active or upcoming booking; hands off anything booking/rate/payment/complaint-related to staff. Needs WhatsApp configured under Integrations, and replies are reviewed in the <a href="' . site_url('concierge') . '">WhatsApp Concierge</a> inbox unless auto-send is on.'],
                    ];
                    foreach ($guestFeatures as $key => $meta): ?>
                        <div class="row align-items-center mb-2">
                            <div class="col-md-6">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" role="switch" name="<?= str_replace('.', '__', $key) ?>" id="<?= str_replace('.', '_', $key) ?>" <?= $aiToggles[$key] ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="<?= str_replace('.', '_', $key) ?>"><?= $meta['label'] ?> <span class="text-muted small d-block"><?= $meta['desc'] ?></span></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" role="switch" name="<?= str_replace('.', '__', $meta['autosend']) ?>" id="<?= str_replace('.', '_', $meta['autosend']) ?>" <?= $aiToggles[$meta['autosend']] ? 'checked' : '' ?>>
                                    <label class="form-check-label small" for="<?= str_replace('.', '_', $meta['autosend']) ?>">Auto-send (skip staff review)</label>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h2 class="h6">Concierge Knowledge Base</h2>
                    <p class="text-muted small">What the WhatsApp Concierge is allowed to tell a guest about your hotel. Any field left blank here means the concierge will say it'll check with the front desk rather than guessing — it never invents check-in times, wifi details, or policies.</p>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Check-In Time</label>
                            <input type="text" class="form-control" name="hotel__check_in_time" value="<?= esc($values['hotel.check_in_time'] ?? '') ?>" placeholder="e.g. 2:00 PM">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small">Check-Out Time</label>
                            <input type="text" class="form-control" name="hotel__check_out_time" value="<?= esc($values['hotel.check_out_time'] ?? '') ?>" placeholder="e.g. 12:00 PM (noon)">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label small">Wifi Info</label>
                            <input type="text" class="form-control" name="hotel__wifi_info" value="<?= esc($values['hotel.wifi_info'] ?? '') ?>" placeholder="e.g. Network &quot;MaxYields-Guest&quot;, password on your room key card">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label small">General Guest Info</label>
                            <textarea class="form-control" name="hotel__guest_info_faq" rows="3" placeholder="Directions, parking, breakfast hours, what's included, general policies — anything else guests commonly ask about."><?= esc($values['hotel.guest_info_faq'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <button type="submit" class="btn btn-primary">Save AI Settings</button>
            <a href="<?= site_url('ai-call-log') ?>" class="btn btn-outline-secondary">View AI Call Log</a>
        </form>
    </div>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
document.getElementById('copySnippetBtn')?.addEventListener('click', function () {
    const el = document.getElementById('widgetSnippet');
    navigator.clipboard.writeText(el.value).then(() => {
        this.innerHTML = '<i class="bi bi-check2 me-1"></i>Copied';
        setTimeout(() => { this.innerHTML = '<i class="bi bi-clipboard me-1"></i>Copy'; }, 2000);
    });
});

/**
 * Shared by the three "Test Connection" buttons on the Integrations
 * tab — each just supplies its own URL, button, result element, and
 * (for SMS/Email) the extra body param to send. window.maxyieldsPost() is
 * the global CSRF-aware AJAX helper from layouts/main.php.
 */
function runConnectionTest(btnId, resultId, url, body, defaultLabel) {
    const btn = document.getElementById(btnId);
    const result = document.getElementById(resultId);
    if (!btn) { return; }

    btn.addEventListener('click', function () {
        const extraBody = typeof body === 'function' ? body() : body;
        if (extraBody === null) { return; } // validation failed client-side, e.g. empty phone/email

        btn.disabled = true;
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Testing...';
        result.classList.remove('d-none', 'text-success', 'text-danger');
        result.textContent = '';

        window.maxyieldsPost(url, extraBody)
            .then(function (data) {
                result.classList.add(data.success ? 'text-success' : 'text-danger');
                result.innerHTML = '<i class="bi ' + (data.success ? 'bi-check-circle' : 'bi-x-circle') + ' me-1"></i>' + (data.success ? data.message : data.error);
            })
            .catch(function () {
                result.classList.add('text-danger');
                result.textContent = 'Could not reach the server — please try again.';
            })
            .finally(function () {
                btn.disabled = false;
                btn.innerHTML = originalHtml || defaultLabel;
            });
    });
}

runConnectionTest('testSmsBtn', 'testSmsResult', '<?= site_url('settings/test-sms') ?>', function () {
    const phone = document.getElementById('testSmsPhone').value.trim();
    if (!phone) {
        const el = document.getElementById('testSmsResult');
        el.classList.remove('d-none');
        el.classList.add('text-danger');
        el.textContent = 'Enter a phone number first.';
        return null;
    }
    return { test_phone: phone };
}, 'Send Test SMS');

runConnectionTest('testEmailBtn', 'testEmailResult', '<?= site_url('settings/test-email') ?>', function () {
    const email = document.getElementById('testEmailAddress').value.trim();
    if (!email) {
        const el = document.getElementById('testEmailResult');
        el.classList.remove('d-none');
        el.classList.add('text-danger');
        el.textContent = 'Enter an email address first.';
        return null;
    }
    return { test_email: email };
}, 'Send Test Email');

runConnectionTest('testWhatsappBtn', 'testWhatsappResult', '<?= site_url('settings/test-whatsapp') ?>', {}, 'Test Connection');
</script>
<?= $this->endSection() ?>
