<?php
$isAdmin = !empty($isAdmin);
$currentIndustry = $currentIndustry ?? 'distribution';
$industries = $industries ?? [];
$integrations = $integrations ?? [];
$marketingConnections = $marketingConnections ?? [];
$current = $industries[$currentIndustry] ?? ['letter' => 'A', 'name' => 'Distribution'];
$industryMeta = [
    'distribution' => ['bi-box-seam-fill', '#2563eb', '#eff6ff'],
    'software' => ['bi-laptop-fill', '#7c3aed', '#f3e8ff'],
    'contract' => ['bi-building-fill', '#ea580c', '#fff7ed'],
    'service' => ['bi-tools', '#0f766e', '#f0fdfa'],
];
$personalCards = [
    ['outlook', 'email', 'Outlook email', 'bi-envelope-fill', '#2563eb', '#eff6ff'],
    ['gmail', 'email', 'Gmail email', 'bi-google', '#dc2626', '#fef2f2'],
    ['outlook', 'calendar', 'Outlook calendar', 'bi-calendar3', '#2563eb', '#eff6ff'],
    ['gmail', 'calendar', 'Google calendar', 'bi-calendar-check-fill', '#16a34a', '#f0fdf4'],
];
$marketingTools = [
    ['mailchimp', 'Mailchimp', 'Group email lists', 'bi-envelope-paper-heart-fill', '#ea580c', '#fff7ed'],
    ['constant_contact', 'Constant Contact', 'Group email lists', 'bi-people-fill', '#2563eb', '#eff6ff'],
    ['outlook', 'Outlook', 'Marketing mailbox', 'bi-microsoft', '#2563eb', '#eff6ff'],
    ['gmail', 'Gmail', 'Marketing mailbox', 'bi-google', '#dc2626', '#fef2f2'],
];
$isOn = static function (array $map, string $key): bool {
    return ($map[$key]['status'] ?? '') === 'connected';
};
$personalOn = 0;
foreach ($personalCards as $c) {
    if ($isOn($integrations, $c[0] . '_' . $c[1])) {
        $personalOn++;
    }
}
$mktOn = 0;
foreach ($marketingTools as $t) {
    if ($isOn($marketingConnections, $t[0])) {
        $mktOn++;
    }
}
$summaries = [
    [$current['letter'] ?? 'A', $current['name'] ?? 'Setup', 'bi-buildings', '#2563eb', '#eff6ff'],
    [(string) $personalOn . '/4', 'Mail & calendar', 'bi-envelope-fill', '#16a34a', '#f0fdf4'],
    [$isAdmin ? (string) $mktOn . '/4' : '—', $isAdmin ? 'Email tools' : 'Admin tools', 'bi-megaphone-fill', '#ea580c', '#fff7ed'],
    ['Off', 'Live OAuth', 'bi-shield-lock-fill', '#7c3aed', '#f3e8ff'],
];
?>
<div class="set-page">
  <div class="mb-3">
    <h1 class="page-title">Settings</h1>
    <p class="page-sub mb-0">Company setup and mail flags. Names, stages, fields, and permissions are under Setup.</p>
  </div>

  <div class="task-summary mb-3">
    <?php foreach ($summaries as $s): ?>
      <div class="task-summary-card" style="--task-accent: <?= e($s[3]) ?>; --task-tint: <?= e($s[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($s[2]) ?>"></i></div>
        <div>
          <div class="task-summary-n"><?= e($s[0]) ?></div>
          <div class="task-summary-l"><?= e($s[1]) ?></div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <?php if ($isAdmin): ?>
  <a class="set-section d-block mb-3 text-decoration-none" href="<?= e(url('setup')) ?>">
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-sliders"></i> Setup tools</div>
        <p class="set-section-sub mb-0">Rename words, edit stages, add boxes, set alerts, and publish.</p>
      </div>
      <span class="btn btn-primary">Open setup</span>
    </div>
  </a>
  <form class="set-section ajax-form mb-3" action="<?= e(url('settings/timezone')) ?>" method="post">
    <?= csrf_field() ?>
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-clock"></i> Company time</div>
        <p class="set-section-sub">Home greetings, due dates, and “today” filters use this zone for everyone in the company.</p>
      </div>
      <button class="btn btn-primary set-save" type="submit">Save time</button>
    </div>
    <div class="set-tz">
      <label class="form-label" for="companyTimezone">Time zone</label>
      <select class="form-select" id="companyTimezone" name="timezone">
        <?php foreach (($timezoneOptions ?? []) as $tzId => $tzLabel): ?>
          <option value="<?= e((string) $tzId) ?>" <?= ($timezone ?? '') === $tzId ? 'selected' : '' ?>><?= e($tzLabel) ?></option>
        <?php endforeach; ?>
      </select>
      <p class="set-tz-now">Right now this is <strong><?= e(date('g:i A')) ?></strong> on <?= e(date('l, M j')) ?>.</p>
    </div>
  </form>
  <form class="set-section ajax-form mb-3" action="<?= e(url('settings/industry')) ?>" method="post">
    <?= csrf_field() ?>
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-buildings"></i> Industry setup</div>
        <p class="set-section-sub">Pick one. Screens and deal stages change. This is not a new website.</p>
      </div>
      <button class="btn btn-primary set-save" type="submit">Save setup</button>
    </div>
    <div class="set-industry-grid">
      <?php foreach ($industries as $code => $tpl):
          $meta = $industryMeta[$code] ?? ['bi-grid', '#2563eb', '#eff6ff'];
          $on = $currentIndustry === $code;
          $stages = count($tpl['stages'] ?? []);
      ?>
        <label class="set-industry <?= $on ? 'is-on' : '' ?>" style="--set-accent: <?= e($meta[1]) ?>; --set-tint: <?= e($meta[2]) ?>">
          <input class="visually-hidden" type="radio" name="industry_code" value="<?= e($code) ?>" <?= $on ? 'checked' : '' ?>>
          <span class="set-industry-icon"><i class="bi <?= e($meta[0]) ?>"></i></span>
          <span class="set-industry-body">
            <span class="set-industry-kicker">Setup <?= e($tpl['letter']) ?></span>
            <span class="set-industry-name"><?= e($tpl['name']) ?></span>
            <span class="set-industry-sum"><?= e($tpl['summary']) ?></span>
            <span class="set-industry-meta"><?= (int) $stages ?> deal stages</span>
          </span>
          <?php if ($on): ?><span class="set-pill is-on">Current</span><?php endif; ?>
        </label>
      <?php endforeach; ?>
    </div>
  </form>

  <div class="set-section mb-3">
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-megaphone"></i> Marketing email tools</div>
        <p class="set-section-sub mb-0">Mark which tool this company uses for group email. A data sync must never undo an unsubscribe.</p>
      </div>
    </div>
    <div class="set-connect-grid">
      <?php foreach ($marketingTools as $t):
          $on = $isOn($marketingConnections, $t[0]);
      ?>
        <div class="set-connect <?= $on ? 'is-on' : '' ?>" style="--set-accent: <?= e($t[4]) ?>; --set-tint: <?= e($t[5]) ?>">
          <span class="set-connect-icon"><i class="bi <?= e($t[3]) ?>"></i></span>
          <div class="min-w-0">
            <div class="set-connect-name"><?= e($t[1]) ?></div>
            <div class="set-connect-sum"><?= e($t[2]) ?></div>
          </div>
          <span class="set-pill <?= $on ? 'is-on' : 'is-off' ?>"><?= $on ? 'On' : 'Off' ?></span>
          <form class="ajax-form" action="<?= e(url('settings/marketing-connect')) ?>" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="provider" value="<?= e($t[0]) ?>">
            <input type="hidden" name="status" value="<?= $on ? 'disconnected' : 'connected' ?>">
            <button class="btn btn-sm <?= $on ? 'btn-outline-danger' : 'btn-primary' ?> set-connect-btn" type="submit"><?= $on ? 'Turn off' : 'Turn on' ?></button>
          </form>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php else: ?>
  <div class="set-section mb-3">
        <div class="set-section-title"><i class="bi bi-buildings"></i> Company setup</div>
    <p class="set-section-sub">Admins pick the industry. Deal stages follow that setup.</p>
    <div class="set-industry is-on" style="--set-accent: <?= e(($industryMeta[$currentIndustry] ?? ['', '#2563eb', '#eff6ff'])[1]) ?>; --set-tint: <?= e(($industryMeta[$currentIndustry] ?? ['', '#2563eb', '#eff6ff'])[2]) ?>">
      <span class="set-industry-icon"><i class="bi <?= e(($industryMeta[$currentIndustry] ?? ['bi-buildings'])[0]) ?>"></i></span>
      <span class="set-industry-body">
        <span class="set-industry-kicker">Setup <?= e($current['letter'] ?? '') ?></span>
        <span class="set-industry-name"><?= e($current['name'] ?? '') ?></span>
        <span class="set-industry-sum"><?= e($current['summary'] ?? '') ?></span>
      </span>
      <span class="set-pill is-on">Current</span>
    </div>
  </div>
  <?php endif; ?>

  <?php if ($isAdmin):
      $tipsOn = !empty($smartTipsOn);
  ?>
  <div class="set-section mb-3">
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-lightbulb"></i> Smart tips</div>
        <p class="set-section-sub mb-0">Short next-step help on Home. No extra menu. The Customer Portal stays as it is.</p>
      </div>
    </div>
    <div class="set-connect <?= $tipsOn ? 'is-on' : '' ?>" style="--set-accent:#d97706;--set-tint:#fffbeb">
      <span class="set-connect-icon"><i class="bi bi-lightbulb-fill"></i></span>
      <div class="min-w-0">
        <div class="set-connect-name">Tips on Home</div>
        <div class="set-connect-sum">Sales, manager, service, and marketing see next actions and risk from CRM data.</div>
      </div>
      <span class="set-pill <?= $tipsOn ? 'is-on' : 'is-off' ?>"><?= $tipsOn ? 'On' : 'Off' ?></span>
      <form class="ajax-form" action="<?= e(url('settings/tips')) ?>" method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="status" value="<?= $tipsOn ? 'off' : 'on' ?>">
        <button class="btn btn-sm <?= $tipsOn ? 'btn-outline-danger' : 'btn-primary' ?> set-connect-btn" type="submit"><?= $tipsOn ? 'Turn off' : 'Turn on' ?></button>
      </form>
    </div>
  </div>
  <?php endif; ?>

  <?php if ($isAdmin):
      $commerce = $commerce ?? ['customer_portal_on' => 0, 'systems' => []];
      $portalPages = $portalPages ?? [];
      $customerUsers = $customerUsers ?? [];
      $accounts = $accounts ?? [];
      $pageMeta = \App\Services\CommerceService::PAGES;
      $systemMeta = [
          ['orders', 'Order system', 'Pull real orders onto the customer', 'bi-bag-check-fill', '#2563eb', '#eff6ff'],
          ['accounting', 'Accounts / invoices', 'Bills and payments the customer can see', 'bi-receipt', '#16a34a', '#f0fdf4'],
          ['service', 'Service system', 'Jobs and equipment for field work', 'bi-tools', '#0f766e', '#f0fdfa'],
      ];
  ?>
  <div class="set-section mb-3">
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-hdd-network"></i> Connect other systems</div>
        <p class="set-section-sub mb-0">Mark which company system this Staff Portal uses. This is a flag only — no live OAuth in this phase.</p>
      </div>
    </div>
    <div class="set-connect-grid">
      <?php foreach ($systemMeta as $t):
          $on = (($commerce['systems'][$t[0]] ?? '') === 'connected');
      ?>
        <div class="set-connect <?= $on ? 'is-on' : '' ?>" style="--set-accent: <?= e($t[4]) ?>; --set-tint: <?= e($t[5]) ?>">
          <span class="set-connect-icon"><i class="bi <?= e($t[3]) ?>"></i></span>
          <div class="min-w-0">
            <div class="set-connect-name"><?= e($t[1]) ?></div>
            <div class="set-connect-sum"><?= e($t[2]) ?></div>
          </div>
          <span class="set-pill <?= $on ? 'is-on' : 'is-off' ?>"><?= $on ? 'On' : 'Off' ?></span>
          <form class="ajax-form" action="<?= e(url('settings/system')) ?>" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="system" value="<?= e($t[0]) ?>">
            <input type="hidden" name="status" value="<?= $on ? 'disconnected' : 'connected' ?>">
            <button class="btn btn-sm <?= $on ? 'btn-outline-danger' : 'btn-primary' ?> set-connect-btn" type="submit"><?= $on ? 'Turn off' : 'Turn on' ?></button>
          </form>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <form class="set-section ajax-form mb-3" action="<?= e(url('settings/portal')) ?>" method="post">
    <?= csrf_field() ?>
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-door-open"></i> Customer Portal</div>
        <p class="set-section-sub">A separate website and login for your customer. They never see this Staff Portal. Pick which pages they may open.</p>
      </div>
      <button class="btn btn-primary" type="submit">Save portal</button>
    </div>
    <label class="sup-check mb-3">
      <input type="checkbox" name="customer_portal_on" value="1" <?= !empty($commerce['customer_portal_on']) ? 'checked' : '' ?>>
      Turn the Customer Portal on
    </label>
    <p class="small text-muted">Sign-in: <code>/crm/customer-portal/login</code></p>
    <div class="sup-checks mb-3">
      <?php foreach ($pageMeta as $key => $label): ?>
        <label class="sup-check"><input type="checkbox" name="pages[<?= e($key) ?>]" value="1" <?= !empty($portalPages[$key]) ? 'checked' : '' ?>> <?= e($label) ?></label>
      <?php endforeach; ?>
    </div>
    <input type="hidden" name="systems[orders]" value="<?= e($commerce['systems']['orders'] ?? 'disconnected') ?>">
    <input type="hidden" name="systems[accounting]" value="<?= e($commerce['systems']['accounting'] ?? 'disconnected') ?>">
    <input type="hidden" name="systems[service]" value="<?= e($commerce['systems']['service'] ?? 'disconnected') ?>">
  </form>

  <div class="set-section mb-3">
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-person-badge"></i> Customer logins</div>
        <p class="set-section-sub mb-0">Each login belongs to one customer company. They see only that company.</p>
      </div>
    </div>
    <?php if (!$customerUsers): ?>
      <p class="text-muted">No customer logins yet.</p>
    <?php else: foreach ($customerUsers as $cu): ?>
      <div class="com-row com-static">
        <div class="com-ico"><i class="bi bi-person"></i></div>
        <div class="min-w-0 flex-grow-1">
          <div class="com-name"><?= e($cu['first_name'] . ' ' . $cu['last_name']) ?></div>
          <div class="com-sub"><?= e($cu['email']) ?> · <?= e($cu['account_name']) ?></div>
        </div>
        <span class="com-pill com-<?= e($cu['status']) ?>"><?= e($cu['status']) ?></span>
        <form class="ajax-form" action="<?= e(url('settings/customer-users/' . $cu['id'] . '/toggle')) ?>" method="post">
          <?= csrf_field() ?>
          <button class="btn btn-sm btn-outline-secondary" type="submit"><?= $cu['status'] === 'active' ? 'Stop' : 'Resume' ?></button>
        </form>
      </div>
    <?php endforeach; endif; ?>
    <form class="ajax-form mt-3" action="<?= e(url('settings/customer-users')) ?>" method="post">
      <?= csrf_field() ?>
      <div class="row g-2">
        <div class="col-md-4"><select class="form-select" name="account_id" required><option value="">Customer</option><?php foreach ($accounts as $acc): ?><option value="<?= (int) $acc['id'] ?>"><?= e($acc['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><input class="form-control" name="first_name" placeholder="First" required></div>
        <div class="col-md-2"><input class="form-control" name="last_name" placeholder="Last" required></div>
        <div class="col-md-2"><input class="form-control" type="email" name="email" placeholder="Email" required></div>
        <div class="col-md-2"><input class="form-control" type="password" name="password" placeholder="Password" required minlength="8"></div>
      </div>
      <button class="btn btn-primary mt-2" type="submit">Add customer login</button>
    </form>
  </div>
  <?php endif; ?>

  <div class="set-section">
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-envelope"></i> Personal email and calendar</div>
        <p class="set-section-sub mb-0">Turn on Outlook or Gmail so logged one-to-one mail is labeled correctly.</p>
      </div>
    </div>
    <div class="set-connect-grid">
      <?php foreach ($personalCards as $c):
          $key = $c[0] . '_' . $c[1];
          $on = $isOn($integrations, $key);
      ?>
        <div class="set-connect <?= $on ? 'is-on' : '' ?>" style="--set-accent: <?= e($c[4]) ?>; --set-tint: <?= e($c[5]) ?>">
          <span class="set-connect-icon"><i class="bi <?= e($c[3]) ?>"></i></span>
          <div class="min-w-0">
            <div class="set-connect-name"><?= e($c[2]) ?></div>
            <div class="set-connect-sum"><?= $on ? 'Labeled in this CRM' : 'Not connected' ?></div>
          </div>
          <span class="set-pill <?= $on ? 'is-on' : 'is-off' ?>"><?= $on ? 'On' : 'Off' ?></span>
          <?php if ($isAdmin || $on): ?>
          <form class="ajax-form" action="<?= e(url('settings/connect')) ?>" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="provider" value="<?= e($c[0]) ?>">
            <input type="hidden" name="kind" value="<?= e($c[1]) ?>">
            <input type="hidden" name="status" value="<?= $on ? 'disconnected' : 'connected' ?>">
            <button class="btn btn-sm <?= $on ? 'btn-outline-danger' : 'btn-primary' ?> set-connect-btn" type="submit"><?= $on ? 'Turn off' : 'Turn on' ?></button>
          </form>
          <?php else: ?>
            <span class="small text-muted">Ask an admin</span>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
