<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/admin_layout.php';

require_admin();
$tenantId = current_tenant_id();
$flash = '';

$tenant = get_tenant($tenantId);
$metricsStmt = db()->prepare('SELECT * FROM license_metrics WHERE tenant_id = ?');
$metricsStmt->execute([$tenantId]);
$metrics = $metricsStmt->fetch() ?: [];

$presets = ['modern_sans', 'classic_serif', 'bold_display', 'editorial', 'clean_tech'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $primary = trim((string) ($_POST['primary_color'] ?? '#1a1a1a'));
    $secondary = trim((string) ($_POST['secondary_color'] ?? '#c9a227'));
    $font = (string) ($_POST['font_pairing'] ?? 'modern_sans');
    if (!in_array($font, $presets, true)) {
        $font = 'modern_sans';
    }
    $domain = trim((string) ($_POST['custom_domain'] ?? '')) ?: null;
    $sub = trim((string) ($_POST['subdomain'] ?? '')) ?: null;
    $shopName = trim((string) ($_POST['name'] ?? ''));
    if ($shopName === '') {
        $shopName = 'Company Name Here';
    }
    $license = trim((string) ($_POST['license_status'] ?? 'active'));

    db()->prepare('UPDATE tenants SET name=?, primary_color=?, secondary_color=?, font_pairing=?, custom_domain=?, subdomain=?, license_status=? WHERE id=?')
        ->execute([$shopName, $primary, $secondary, $font, $domain, $sub, $license, $tenantId]);
    db()->prepare('UPDATE page_settings SET business_name = ? WHERE tenant_id = ?')
        ->execute([$shopName, $tenantId]);

    db()->prepare(
        'INSERT INTO license_metrics (tenant_id, subscription_type, renewal_date, sms_count_month, email_count_month, booking_count_month, notes)
         VALUES (?,?,?,?,?,?,?)
         ON DUPLICATE KEY UPDATE subscription_type=VALUES(subscription_type), renewal_date=VALUES(renewal_date),
           sms_count_month=VALUES(sms_count_month), email_count_month=VALUES(email_count_month),
           booking_count_month=VALUES(booking_count_month), notes=VALUES(notes)'
    )->execute([
        $tenantId,
        trim((string) ($_POST['subscription_type'] ?? 'starter')),
        ($_POST['renewal_date'] ?? '') !== '' ? $_POST['renewal_date'] : null,
        (int) ($_POST['sms_count_month'] ?? 0),
        (int) ($_POST['email_count_month'] ?? 0),
        (int) ($_POST['booking_count_month'] ?? 0),
        trim((string) ($_POST['notes'] ?? '')),
    ]);

    $flash = 'Branding & license settings saved.';
    $tenant = get_tenant($tenantId);
    $metricsStmt->execute([$tenantId]);
    $metrics = $metricsStmt->fetch() ?: [];
}

admin_header('Whitelabel Branding', 'branding');
if ($flash): ?><div class="flash"><?= htmlspecialchars($flash) ?></div><?php endif; ?>

<form method="post">
  <div class="panel">
    <h2>Company name</h2>
    <p class="muted">This is the header name on the public site and in the Android app. Start from the placeholder, then replace it with the shop’s real name.</p>
    <label>Company name</label>
    <input type="text" name="name" placeholder="Company Name Here" value="<?= htmlspecialchars(shop_company_name(null, $tenant ?? [])) ?>">
  </div>

  <div class="panel">
    <h2>Theme styling</h2>
    <div class="grid-2">
      <div>
        <label>Primary color (backgrounds / hero veil)</label>
        <input type="color" name="primary_color" value="<?= htmlspecialchars((string) ($tenant['primary_color'] ?? '#1a1a1a')) ?>">
      </div>
      <div>
        <label>Secondary color (buttons / accents)</label>
        <input type="color" name="secondary_color" value="<?= htmlspecialchars((string) ($tenant['secondary_color'] ?? '#c9a227')) ?>">
      </div>
    </div>
    <div style="margin-top:1rem">
      <label>Font pairing preset</label>
      <select name="font_pairing">
        <?php foreach ($presets as $key):
          $meta = font_pairing_css($key);
          ?>
          <option value="<?= $key ?>" <?= (($tenant['font_pairing'] ?? '') === $key) ? 'selected' : '' ?>>
            <?= htmlspecialchars($meta['label']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
  </div>

  <div class="panel">
    <h2>Custom domain hook</h2>
    <p class="muted">Must match the hostname slug (YOURSHOP.barber-shop.us → YOURSHOP). That is the name clients type in the Android app. Custom domains are optional.</p>
    <div class="grid-2">
      <div>
        <label>Subdomain</label>
        <input type="text" name="subdomain" value="<?= htmlspecialchars((string) ($tenant['subdomain'] ?? '')) ?>" placeholder="yourshop">
      </div>
      <div>
        <label>Custom domain</label>
        <input type="text" name="custom_domain" value="<?= htmlspecialchars((string) ($tenant['custom_domain'] ?? '')) ?>" placeholder="joesbarbershop.com">
      </div>
    </div>
  </div>

  <div class="panel">
    <h2>License metrics panel</h2>
    <div class="grid-2">
      <div>
        <label>License status</label>
        <select name="license_status">
          <?php foreach (['active', 'trial', 'past_due', 'suspended'] as $st): ?>
            <option <?= (($tenant['license_status'] ?? '') === $st) ? 'selected' : '' ?>><?= $st ?></option>
          <?php endforeach; ?>
        </select>
        <label>Subscription type</label>
        <select name="subscription_type">
          <?php foreach (['hosted_subdomain', 'starter', 'pro', 'enterprise'] as $t): ?>
            <option <?= (($metrics['subscription_type'] ?? '') === $t) ? 'selected' : '' ?>><?= $t ?></option>
          <?php endforeach; ?>
        </select>
        <label>Renewal date</label>
        <input type="date" name="renewal_date" value="<?= htmlspecialchars((string) ($metrics['renewal_date'] ?? '')) ?>">
      </div>
      <div>
        <label>SMS volume (month)</label>
        <input type="number" name="sms_count_month" value="<?= (int) ($metrics['sms_count_month'] ?? 0) ?>">
        <label>Email volume (month)</label>
        <input type="number" name="email_count_month" value="<?= (int) ($metrics['email_count_month'] ?? 0) ?>">
        <label>Bookings (month)</label>
        <input type="number" name="booking_count_month" value="<?= (int) ($metrics['booking_count_month'] ?? 0) ?>">
        <label>Notes</label>
        <textarea name="notes"><?= htmlspecialchars((string) ($metrics['notes'] ?? '')) ?></textarea>
      </div>
    </div>
  </div>

  <button class="btn" type="submit">Save branding</button>
</form>
<?php admin_footer(); ?>
