<?php
$read = static function (string $key, string $fallback = '') use ($settings, $form): string {
    if (is_array($form) && array_key_exists($key, $form)) return (string) $form[$key];
    return (string) ($settings[$key]['value'] ?? $fallback);
};
$checked = static function (string $key) use ($read): string {
    return in_array(strtolower($read($key)), ['1', 'true', 'on', 'yes'], true) ? 'checked' : '';
};
?>
<?php require dirname(__DIR__) . '/components/page-header.php'; ?>
<?php if ($message): ?><div class="alert alert-success"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
<section class="card">
    <div class="card-header"><div><h2>Branding</h2><p>Upload the logo used on invoices, receipts, assessments and clinical reports.</p></div></div>
    <div class="branding-settings" style="display:flex;align-items:center;gap:18px;flex-wrap:wrap">
        <div style="width:150px;height:90px;border:1px solid #e5e7eb;border-radius:14px;display:flex;align-items:center;justify-content:center;background:#fff;overflow:hidden">
            <?php $logoFile = (string)($settings['business.logo']['value'] ?? ''); ?>
            <?php if (!empty($logoPreview)): ?>
                <img src="<?= htmlspecialchars($logoPreview, ENT_QUOTES, 'UTF-8') ?>" alt="Company logo" style="max-width:130px;max-height:75px;object-fit:contain">
            <?php else: ?>
                <span class="muted">No logo uploaded</span>
            <?php endif; ?>
        </div>
        <form method="post" action="/crm/public/settings/logo" enctype="multipart/form-data" style="display:flex;align-items:end;gap:10px;flex-wrap:wrap">
            <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
            <label class="form-field"><span>Logo (PNG or JPG, max 3 MB)</span><input type="file" name="logo" accept="image/png,image/jpeg" required></label>
            <button class="btn btn-primary" type="submit">Upload logo</button>
        </form>
    </div>
</section>
<form method="post" action="/crm/public/settings" class="form-stack settings-form">
    <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">

    <section class="card">
        <div class="card-header"><div><h2>Business profile</h2><p>Identity used across the CRM and future documents.</p></div></div>
        <div class="grid grid-2">
            <label class="form-field"><span>Business name</span><input name="business.name" value="<?= htmlspecialchars($read('business.name'), ENT_QUOTES, 'UTF-8') ?>" required></label>
            <label class="form-field"><span>Tagline</span><input name="business.tagline" value="<?= htmlspecialchars($read('business.tagline'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>Business email</span><input type="email" name="business.email" value="<?= htmlspecialchars($read('business.email'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>Business phone</span><input name="business.phone" value="<?= htmlspecialchars($read('business.phone'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>Country</span><input name="business.country" value="<?= htmlspecialchars($read('business.country'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>Website</span><input type="url" name="business.website" value="<?= htmlspecialchars($read('business.website'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field" style="grid-column:1/-1"><span>Business address</span><textarea name="business.address" rows="3"><?= htmlspecialchars($read('business.address'), ENT_QUOTES, 'UTF-8') ?></textarea></label>
        </div>
    </section>

    <section class="card">
        <div class="card-header"><div><h2>Email delivery</h2><p>Configure SMTP so the CRM can send invoices and future receipts/reports by email.</p></div></div>
        <div class="grid grid-2">
            <label class="form-field"><span>SMTP host</span><input name="mail.smtp.host" value="<?= htmlspecialchars($read('mail.smtp.host'), ENT_QUOTES, 'UTF-8') ?>" placeholder="smtp.example.com"></label>
            <label class="form-field"><span>SMTP port</span><input type="number" min="1" max="65535" name="mail.smtp.port" value="<?= htmlspecialchars($read('mail.smtp.port','587'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>SMTP username</span><input name="mail.smtp.username" value="<?= htmlspecialchars($read('mail.smtp.username'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>SMTP password</span><input type="password" name="mail.smtp.password" value="<?= htmlspecialchars($read('mail.smtp.password'), ENT_QUOTES, 'UTF-8') ?>" autocomplete="new-password"></label>
            <label class="form-field"><span>Encryption</span><select name="mail.smtp.encryption"><option value="tls" <?= $read('mail.smtp.encryption','tls')==='tls'?'selected':'' ?>>TLS</option><option value="ssl" <?= $read('mail.smtp.encryption')==='ssl'?'selected':'' ?>>SSL</option><option value="none" <?= $read('mail.smtp.encryption')==='none'?'selected':'' ?>>None</option></select></label>
            <label class="form-field"><span>Sender email</span><input type="email" name="mail.from.address" value="<?= htmlspecialchars($read('mail.from.address'), ENT_QUOTES, 'UTF-8') ?>" placeholder="info@growtooltherapies.org"></label>
            <label class="form-field" style="grid-column:1/-1"><span>Sender name</span><input name="mail.from.name" value="<?= htmlspecialchars($read('mail.from.name','Grow Tool Therapies'), ENT_QUOTES, 'UTF-8') ?>"></label>
        </div>
    </section>

    <section class="card">
        <div class="card-header"><div><h2>Regional preferences</h2><p>Defaults used when displaying dates, times and monetary values.</p></div></div>
        <div class="grid grid-2">
            <label class="form-field"><span>Currency code</span><input name="regional.currency_code" value="<?= htmlspecialchars($read('regional.currency_code'), ENT_QUOTES, 'UTF-8') ?>" maxlength="10"></label>
            <label class="form-field"><span>Currency symbol</span><input name="regional.currency_symbol" value="<?= htmlspecialchars($read('regional.currency_symbol'), ENT_QUOTES, 'UTF-8') ?>" maxlength="10"></label>
            <label class="form-field"><span>Timezone</span><input name="regional.timezone" value="<?= htmlspecialchars($read('regional.timezone'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>Language</span><input name="regional.language" value="<?= htmlspecialchars($read('regional.language'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>Date format</span><select name="regional.date_format"><option <?= $read('regional.date_format') === 'DD/MM/YYYY' ? 'selected' : '' ?>>DD/MM/YYYY</option><option <?= $read('regional.date_format') === 'MM/DD/YYYY' ? 'selected' : '' ?>>MM/DD/YYYY</option><option <?= $read('regional.date_format') === 'YYYY-MM-DD' ? 'selected' : '' ?>>YYYY-MM-DD</option></select></label>
            <label class="form-field"><span>Time format</span><select name="regional.time_format"><option <?= $read('regional.time_format') === '12-hour' ? 'selected' : '' ?>>12-hour</option><option <?= $read('regional.time_format') === '24-hour' ? 'selected' : '' ?>>24-hour</option></select></label>
            <label class="form-field"><span>Decimal places</span><input type="number" min="0" max="6" name="regional.decimal_places" value="<?= htmlspecialchars($read('regional.decimal_places'), ENT_QUOTES, 'UTF-8') ?>"></label>
        </div>
    </section>

    <section class="card">
        <div class="card-header"><div><h2>Tax settings</h2><p>Configure tax defaults for future billing workflows.</p></div></div>
        <div class="grid grid-2">
            <label class="check-option"><input type="checkbox" name="tax.enabled" value="1" <?= $checked('tax.enabled') ?>><span>Enable tax calculations</span></label>
            <label class="form-field"><span>Tax name</span><input name="tax.name" value="<?= htmlspecialchars($read('tax.name'), ENT_QUOTES, 'UTF-8') ?>"></label>
            <label class="form-field"><span>Tax rate (%)</span><input type="number" step="0.01" min="0" max="100" name="tax.rate" value="<?= htmlspecialchars($read('tax.rate'), ENT_QUOTES, 'UTF-8') ?>"></label>
        </div>
    </section>

    <section class="card">
        <div class="card-header"><div><h2>Document numbering</h2><p>Prefixes used by generated CRM references. Sequence counters remain in the numbering table.</p></div></div>
        <div class="grid grid-2">
            <?php foreach ([
                'patient' => 'Patient prefix', 'assessment' => 'Assessment prefix', 'report' => 'Report prefix',
                'invoice' => 'Invoice prefix', 'receipt' => 'Receipt prefix', 'quotation' => 'Quotation prefix'
            ] as $key => $label): ?>
                <label class="form-field"><span><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></span><input name="numbering.<?= $key ?>.prefix" value="<?= htmlspecialchars($read('numbering.' . $key . '.prefix'), ENT_QUOTES, 'UTF-8') ?>" maxlength="30"></label>
            <?php endforeach; ?>
        </div>
    </section>

    <div class="form-actions"><a class="btn btn-secondary" href="/crm/public/">Cancel</a><button class="btn btn-primary" type="submit">Save settings</button></div>
</form>
