<?php
declare(strict_types=1);

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

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

$settings = reminder_settings($tenantId);
$carriers = [];
try {
    $carriers = sms_carriers_list(false);
} catch (Throwable $e) {
    $carriers = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save_settings';
    try {
        if ($action === 'save_settings') {
            db()->prepare(
                'INSERT INTO reminder_settings (
                    tenant_id, email_enabled, sms_enabled, hours_before,
                    email_from_name, email_from_address, email_subject, sms_template, email_template
                 ) VALUES (?,?,?,?,?,?,?,?,?)
                 ON DUPLICATE KEY UPDATE
                    email_enabled=VALUES(email_enabled), sms_enabled=VALUES(sms_enabled),
                    hours_before=VALUES(hours_before), email_from_name=VALUES(email_from_name),
                    email_from_address=VALUES(email_from_address), email_subject=VALUES(email_subject),
                    sms_template=VALUES(sms_template), email_template=VALUES(email_template)'
            )->execute([
                $tenantId,
                isset($_POST['email_enabled']) ? 1 : 0,
                isset($_POST['sms_enabled']) ? 1 : 0,
                max(1, (int) ($_POST['hours_before'] ?? 24)),
                trim((string) ($_POST['email_from_name'] ?? '')),
                trim((string) ($_POST['email_from_address'] ?? '')) ?: null,
                trim((string) ($_POST['email_subject'] ?? 'Appointment reminder')),
                trim((string) ($_POST['sms_template'] ?? '')),
                trim((string) ($_POST['email_template'] ?? '')) ?: null,
            ]);
            $flash = 'Reminder settings saved.';
            $settings = reminder_settings($tenantId);
        } elseif ($action === 'send_due') {
            $summary = reminder_process_due(100, $tenantId);
            $flash = sprintf(
                'Processed %d · sent %d · skipped %d · failed %d',
                $summary['processed'],
                $summary['sent'],
                $summary['skipped'],
                $summary['failed']
            );
        } elseif ($action === 'save_user') {
            $id = (int) ($_POST['id'] ?? 0);
            $name = trim((string) ($_POST['name'] ?? ''));
            $phone = trim((string) ($_POST['phone'] ?? ''));
            $email = trim((string) ($_POST['email'] ?? ''));
            $carrierId = ($_POST['carrier_id'] ?? '') !== '' ? (int) $_POST['carrier_id'] : null;
            $customDomain = trim((string) ($_POST['custom_sms_domain'] ?? ''));
            if ($name === '') {
                throw new RuntimeException('Name required');
            }
            if ($id > 0) {
                db()->prepare(
                    'UPDATE users SET name=?, phone=?, email=?, carrier_id=?, custom_sms_domain=?, sms_opt_in=?, email_opt_in=? WHERE id=? AND tenant_id=?'
                )->execute([
                    $name,
                    user_normalize_phone($phone),
                    user_normalize_email($email),
                    $carrierId,
                    $customDomain !== '' ? ltrim(strtolower($customDomain), '@') : null,
                    isset($_POST['sms_opt_in']) ? 1 : 0,
                    isset($_POST['email_opt_in']) ? 1 : 0,
                    $id,
                    $tenantId,
                ]);
                $flash = 'Client updated.';
            } else {
                user_upsert($tenantId, $name, $phone ?: null, $email ?: null, $carrierId, $customDomain ?: null);
                $flash = 'Client added.';
            }
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$users = db()->prepare(
    'SELECT u.*, c.name AS carrier_name, c.sms_domain, c.status AS carrier_status,
            (SELECT COUNT(*) FROM bookings b WHERE b.user_id = u.id) AS booking_count
     FROM users u
     LEFT JOIN sms_carriers c ON c.id = u.carrier_id
     WHERE u.tenant_id = ?
     ORDER BY u.name'
);
$users->execute([$tenantId]);
$userRows = $users->fetchAll();

$reminders = db()->prepare(
    'SELECT r.*, b.starts_at, b.customer_name, u.email AS user_email, u.phone AS user_phone
     FROM booking_reminders r
     LEFT JOIN bookings b ON b.id = r.booking_id
     LEFT JOIN users u ON u.id = r.user_id
     WHERE r.tenant_id = ?
     ORDER BY r.scheduled_for DESC
     LIMIT 40'
);
$reminders->execute([$tenantId]);
$reminderRows = $reminders->fetchAll();

$editId = (int) ($_GET['edit'] ?? 0);
$edit = null;
if ($editId) {
    $st = db()->prepare('SELECT * FROM users WHERE id = ? AND tenant_id = ?');
    $st->execute([$editId, $tenantId]);
    $edit = $st->fetch() ?: null;
}

$twilioReady = TWILIO_ACCOUNT_SID !== '' && TWILIO_AUTH_TOKEN !== '' && TWILIO_FROM_NUMBER !== '';
$smtpReady = REMINDER_MAIL_DRIVER === 'smtp' && SMTP_HOST !== '';
$mailMode = REMINDER_MAIL_DRIVER;

admin_header('Clients & Reminders', 'users');
if ($flash): ?><div class="flash"><?= htmlspecialchars($flash) ?></div><?php endif; ?>
<?php if ($error): ?><div class="flash error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<div class="panel">
  <h2>Reminder settings</h2>
  <p class="muted">
    <strong>Policy:</strong> Email is the reliable reminder channel. Carrier email-to-SMS is optional/best-effort.
    If a client’s provider doesn’t accept gateway texts (many don’t anymore), they use <strong>email</strong> — we won’t count on SMS for those carriers.
  </p>
  <p class="muted">
    Current mail driver: <code><?= htmlspecialchars($mailMode) ?></code><?= $smtpReady ? ' · SMTP ready' : ' · set SMTP in config/db.local.php to send for real' ?>.
    <?= $twilioReady ? 'Twilio keys present (optional).' : '' ?>
  </p>
  <form method="post">
    <input type="hidden" name="action" value="save_settings">
    <div class="grid-2">
      <div>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text)">
          <input type="checkbox" name="email_enabled" <?= !empty($settings['email_enabled']) ? 'checked' : '' ?>>
          Email reminders ON
        </label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.5rem">
          <input type="checkbox" name="sms_enabled" <?= !empty($settings['sms_enabled']) ? 'checked' : '' ?>>
          SMS reminders ON <span class="muted">(needs carrier on client + SMTP)</span>
        </label>
        <label style="margin-top:.75rem">Hours before appointment</label>
        <input type="number" name="hours_before" min="1" max="168" value="<?= (int) ($settings['hours_before'] ?? 24) ?>">
        <label>From name</label>
        <input type="text" name="email_from_name" value="<?= htmlspecialchars((string) ($settings['email_from_name'] ?? '')) ?>">
        <label>From email</label>
        <input type="email" name="email_from_address" value="<?= htmlspecialchars((string) ($settings['email_from_address'] ?? '')) ?>" placeholder="shop@example.com">
        <label>Email subject</label>
        <input type="text" name="email_subject" value="<?= htmlspecialchars((string) ($settings['email_subject'] ?? '')) ?>">
      </div>
      <div>
        <label>Email body template</label>
        <textarea name="email_template" rows="6"><?= htmlspecialchars((string) ($settings['email_template'] ?? "Hi {name},\n\nThis is a reminder that you have {service} on {date} at {time} with {barber} at {shop}.\n\nSee you soon!")) ?></textarea>
        <label>SMS template</label>
        <textarea name="sms_template" rows="3"><?= htmlspecialchars((string) ($settings['sms_template'] ?? 'Hi {name}, reminder: {service} on {date} at {time} with {barber}.')) ?></textarea>
        <p class="muted" style="font-size:.85rem">Tokens: {name} {service} {date} {time} {barber} {shop} {phone}</p>
      </div>
    </div>
    <button class="btn" type="submit">Save settings</button>
  </form>
  <form method="post" style="margin-top:.75rem;display:inline">
    <input type="hidden" name="action" value="send_due">
    <button class="btn secondary" type="submit">Send due reminders now</button>
  </form>
</div>

<div class="grid-2">
  <div class="panel">
    <h2><?= $edit ? 'Edit client' : 'Add client' ?></h2>
    <form method="post">
      <input type="hidden" name="action" value="save_user">
      <input type="hidden" name="id" value="<?= (int) ($edit['id'] ?? 0) ?>">
      <label>Name</label>
      <input type="text" name="name" required value="<?= htmlspecialchars((string) ($edit['name'] ?? '')) ?>">
      <label>Phone (for SMS gateway)</label>
      <input type="text" name="phone" value="<?= htmlspecialchars((string) ($edit['phone'] ?? '')) ?>">
      <label>Mobile carrier (email-to-SMS)</label>
      <select name="carrier_id">
        <option value="">— None (email only) —</option>
        <?php foreach ($carriers as $c):
          if (empty($c['is_active']) && (int) ($edit['carrier_id'] ?? 0) !== (int) $c['id']) {
              continue;
          }
          ?>
          <option value="<?= (int) $c['id'] ?>" <?= ((int) ($edit['carrier_id'] ?? 0) === (int) $c['id']) ? 'selected' : '' ?>>
            <?= htmlspecialchars($c['name']) ?>
            (<?= htmlspecialchars($c['sms_domain']) ?> · <?= htmlspecialchars($c['status']) ?>)
          </option>
        <?php endforeach; ?>
      </select>
      <label>Custom gateway domain (optional)</label>
      <input type="text" name="custom_sms_domain" placeholder="vtext.com" value="<?= htmlspecialchars((string) ($edit['custom_sms_domain'] ?? '')) ?>">
      <label>Email (for reminders)</label>
      <input type="email" name="email" value="<?= htmlspecialchars((string) ($edit['email'] ?? '')) ?>">
      <?php if ($edit): ?>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text)">
          <input type="checkbox" name="email_opt_in" <?= !empty($edit['email_opt_in']) ? 'checked' : '' ?>> Email opt-in
        </label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.35rem">
          <input type="checkbox" name="sms_opt_in" <?= !empty($edit['sms_opt_in']) ? 'checked' : '' ?>> SMS opt-in
        </label>
      <?php endif; ?>
      <button class="btn" type="submit" style="margin-top:.75rem">Save client</button>
      <?php if ($edit): ?><a class="btn secondary" href="<?= APP_BASE ?>/admin/users.php">Cancel</a><?php endif; ?>
    </form>
  </div>

  <div class="panel">
    <h2>Clients (users)</h2>
    <table class="table">
      <thead><tr><th>Name</th><th>Phone</th><th>Carrier / SMS addr</th><th>Email</th><th>Bookings</th><th></th></tr></thead>
      <tbody>
        <?php foreach ($userRows as $u):
          $gw = sms_gateway_address($u['phone'] ?? null, ($u['custom_sms_domain'] ?? null) ?: ($u['sms_domain'] ?? null));
          ?>
          <tr>
            <td><?= htmlspecialchars($u['name']) ?></td>
            <td><?= htmlspecialchars((string) ($u['phone'] ?? '—')) ?></td>
            <td>
              <?= htmlspecialchars((string) ($u['carrier_name'] ?? '—')) ?>
              <?php if ($gw): ?>
                <div class="muted" style="font-size:.75rem"><code><?= htmlspecialchars($gw) ?></code></div>
              <?php endif; ?>
            </td>
            <td><?= htmlspecialchars((string) ($u['email'] ?? '—')) ?></td>
            <td><?= (int) $u['booking_count'] ?></td>
            <td><a class="btn small secondary" href="?edit=<?= (int) $u['id'] ?>">Edit</a></td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$userRows): ?>
          <tr><td colspan="6" class="muted">No clients yet — they appear when bookings are created.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="panel">
  <h2>Recent reminders</h2>
  <table class="table">
    <thead><tr><th>When</th><th>Channel</th><th>Client</th><th>Appt</th><th>Status</th><th>Note</th></tr></thead>
    <tbody>
      <?php foreach ($reminderRows as $r): ?>
        <tr>
          <td><?= htmlspecialchars(date('M j, g:ia', strtotime((string) $r['scheduled_for']))) ?></td>
          <td><?= htmlspecialchars((string) $r['channel']) ?></td>
          <td><?= htmlspecialchars((string) ($r['customer_name'] ?? '—')) ?>
            <div class="muted" style="font-size:.8rem"><?= htmlspecialchars((string) ($r['user_email'] ?: $r['user_phone'] ?: '')) ?></div>
          </td>
          <td><?= $r['starts_at'] ? htmlspecialchars(date('M j, g:ia', strtotime((string) $r['starts_at']))) : '—' ?></td>
          <td><span class="tag"><?= htmlspecialchars((string) $r['status']) ?></span></td>
          <td class="muted" style="font-size:.8rem"><?= htmlspecialchars((string) ($r['error_message'] ?? '')) ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$reminderRows): ?>
        <tr><td colspan="6" class="muted">No reminders scheduled yet.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>
<?php admin_footer(); ?>
