<?php

require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$branding = settings_get_branding($conn, $orgId);
$flash = settings_flash_message();
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $appearance = $_POST['appearance'] ?? 'dark';
    $accentColor = $_POST['accent_color'] ?? 'blue';
    $allowedAppearances = ['dark', 'light'];
    $allowedColors = ['blue', 'green', 'red', 'orange', 'custom'];

    if (!in_array($appearance, $allowedAppearances, true)) {
        $errors[] = 'Invalid appearance option selected.';
    }
    if (!in_array($accentColor, $allowedColors, true)) {
        $errors[] = 'Invalid accent colour selected.';
    }

    if (!$errors) {
        if (settings_upsert_branding($conn, $orgId, $appearance, $accentColor)) {
            settings_set_flash('success', 'Branding preferences saved successfully.');
            header('Location: branding.php');
            exit();
        }
        $errors[] = 'Unable to save branding preferences right now.';
    }

    $branding['appearance'] = $appearance;
    $branding['accent_color'] = $accentColor;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Branding | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
  <link rel="stylesheet" href="branding.css">
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-palette'); ?>

  <main class="profile-layout">
    <?php settings_render_sidebar('branding'); ?>

    <section class="profile-main">
      <div class="profile-head">
        <h1>Branding</h1>
      </div>

      <div class="profile-card">
        <?php if (!empty($flash['message'])): ?>
          <div class="alert-ok"><?php echo htmlspecialchars($flash['message']); ?></div>
        <?php endif; ?>

        <?php if ($errors): ?>
          <div class="alert-err">
            <div class="alert-err-title">Please fix the following:</div>
            <ul>
              <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>

        <form method="POST">
          <h2>Appearance</h2>
          <div class="appearance-grid">
            <label class="pane-option <?php echo ($branding['appearance'] ?? 'dark') === 'dark' ? 'selected' : ''; ?>">
              <input type="radio" name="appearance" value="dark" <?php echo ($branding['appearance'] ?? 'dark') === 'dark' ? 'checked' : ''; ?> hidden>
              <div class="pane-preview">
                <div class="dark-sidebar-preview">
                  <div class="bar accent"></div>
                  <div class="bar"></div>
                  <div class="bar"></div>
                  <div class="bar"></div>
                </div>
                <div class="dark-main-preview">
                  <div class="mini-bar"></div>
                  <div class="mini-bar short"></div>
                  <div class="mini-bar"></div>
                </div>
              </div>
              <div class="pane-label"><i class="fa-solid fa-moon"></i> DARK PANE</div>
            </label>

            <label class="pane-option <?php echo ($branding['appearance'] ?? 'dark') === 'light' ? 'selected' : ''; ?>">
              <input type="radio" name="appearance" value="light" <?php echo ($branding['appearance'] ?? 'dark') === 'light' ? 'checked' : ''; ?> hidden>
              <div class="pane-preview">
                <div class="light-sidebar-preview">
                  <div class="bar accent"></div>
                  <div class="bar"></div>
                  <div class="bar"></div>
                  <div class="bar"></div>
                </div>
                <div class="light-main-preview">
                  <div class="mini-bar"></div>
                  <div class="mini-bar short"></div>
                  <div class="mini-bar"></div>
                </div>
              </div>
              <div class="pane-label"><i class="fa-regular fa-sun"></i> LIGHT PANE</div>
            </label>
          </div>

          <h2 style="margin-top:28px;">Accent Color</h2>
          <div class="accent-grid">
            <?php
            $colors = [
                'blue' => 'Blue',
                'green' => 'Green',
                'red' => 'Red',
                'orange' => 'Orange',
                'custom' => '',
            ];
            foreach ($colors as $value => $label): ?>
              <label class="swatch swatch-<?php echo htmlspecialchars($value); ?> <?php echo ($branding['accent_color'] ?? 'blue') === $value ? 'selected' : ''; ?>">
                <input type="radio" name="accent_color" value="<?php echo htmlspecialchars($value); ?>" <?php echo ($branding['accent_color'] ?? 'blue') === $value ? 'checked' : ''; ?> hidden>
                <?php echo htmlspecialchars($label); ?>
              </label>
            <?php endforeach; ?>
          </div>

          <div class="branding-note">
            <strong>Note:</strong> These preferences will be applied across your payroll settings screens.
          </div>

          <div class="profile-footer" style="margin-top:24px;">
            <button class="save-btn" type="submit">Save</button>
            <div></div>
          </div>
        </form>
      </div>
    </section>
  </main>

  <script>
    document.querySelectorAll('.pane-option input, .swatch input').forEach(function (input) {
      input.addEventListener('change', function () {
        if (input.name === 'appearance') {
          document.querySelectorAll('.pane-option').forEach(function (el) { el.classList.remove('selected'); });
          input.closest('.pane-option').classList.add('selected');
        }
        if (input.name === 'accent_color') {
          document.querySelectorAll('.swatch').forEach(function (el) { el.classList.remove('selected'); });
          input.closest('.swatch').classList.add('selected');
        }
      });
    });
  </script>
</body>
</html>
