<?php declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/security.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mailer.php';
require_once __DIR__ . '/../includes/icons.php';
require_once __DIR__ . '/../includes/brand_assets.php';

// Already logged in
if (is_logged_in()) {
  header('Location: dashboard.php');
  exit;
}

$error        = '';
$show_pending = false;
$field_errors = [];

// Preserve inputs on error
$form = [
  'business_name' => '',
  'name'          => '',
  'email'         => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!csrf_post_is_valid()) {
    $error = 'Security token expired. Please refresh and try again.';
  } else {
    $business_name = trim_str($_POST['business_name'] ?? '');
    $name          = trim_str($_POST['name'] ?? '');
    $email         = trim_str($_POST['email'] ?? '');
    $password      = $_POST['password'] ?? '';
    $password2     = $_POST['password2'] ?? '';
    $agreed        = !empty($_POST['agreed']);

    $form = compact('business_name', 'name', 'email');

    // Validation
    if ($business_name === '')
      $field_errors['business_name'] = 'Business name is required.';
    if ($name === '')
      $field_errors['name'] = 'Your full name is required.';

    if ($email === '') {
      $field_errors['email'] = 'Email address is required.';
    } elseif (!validate_email($email)) {
      $field_errors['email'] = 'Please enter a valid email address.';
    }

    $pass_error = validate_new_password($password);
    if ($pass_error) {
      $field_errors['password'] = $pass_error;
    } elseif ($password !== $password2) {
      $field_errors['password2'] = 'Passwords do not match.';
    }

    if (!$agreed) {
      $field_errors['agreed'] = 'You must agree to the Terms of Service to register.';
    }

    if (empty($field_errors)) {
      // Check duplicate email
      $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
      $stmt->execute([$email]);
      if ($stmt->fetch()) {
        $field_errors['email'] = 'An account with this email already exists.';
      }
    }

    if (empty($field_errors)) {
      try {
        $pdo->beginTransaction();

        $hashed = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare(
          "INSERT INTO clients (business_name, status) VALUES (?, 'pending')"
        );
        $stmt->execute([$business_name]);
        $client_id = (int) $pdo->lastInsertId();

        $stmt = $pdo->prepare(
          "INSERT INTO users (client_id, name, email, password, role)
                   VALUES (?, ?, ?, ?, 'admin')"
        );
        $stmt->execute([$client_id, $name, $email, $hashed]);

        // Audit log
        if (function_exists('write_audit_log')) {
          write_audit_log($pdo, $client_id, null, 'CLIENT_REGISTERED_PENDING', 'client', $client_id, [
            'business_name' => $business_name,
            'email'         => $email,
          ]);
        }

        $pdo->commit();
        try {
          send_superadmin_new_pending_signup_email($pdo, $business_name, $name, $email, $client_id);
        } catch (Throwable $e) {
          error_log('Signup notify email: ' . $e->getMessage());
        }
        $show_pending = true;
      } catch (\Throwable $e) {
        $pdo->rollBack();
        $error = 'Registration failed due to a server error. Please try again.';
      }
    }
  }

  csrf_regenerate();
}

// ---- Render ----
$page_title      = 'Create Account — TindaFlow';
$page_body_class = 'auth-page-body';
$auth_css        = true;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <meta name="theme-color" content="<?= h(PosBrandAssets::THEME_COLOR) ?>">
  <meta name="color-scheme" content="light">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">
  <meta name="description" content="Multi-tenant point of sale for small businesses">
  <title><?= h($page_title) ?></title>
  <link rel="icon" type="image/png" href="<?= h(pos_brand_url(PosBrandAssets::FAVICON, '../')) ?>">
  <link rel="apple-touch-icon" href="<?= h(pos_brand_url(PosBrandAssets::APPLE_TOUCH_ICON, '../')) ?>">
  <link rel="manifest" href="../manifest.json">
  <link rel="stylesheet" href="../assets/css/style.css">
  <link rel="stylesheet" href="../assets/css/style-auth.css">
</head>
<body class="auth-page-body">
<div class="auth-shell signup">

  <!-- ═══════════════════════════════════════════════
       LEFT — Brand panel
  ═══════════════════════════════════════════════ -->
  <aside class="auth-brand signup">
    <div class="auth-brand-texture"></div>

    <div class="auth-brand-top">
      <a href="<?= pos_base_url() ?>index.php" class="auth-logo">
        <img src="<?= h(pos_brand_url(PosBrandAssets::LOGO_AUTH, '../')) ?>"
             alt="<?= h(PosBrandAssets::SITE_NAME) ?>"
             class="auth-logo-img">
      </a>
      <div class="auth-logo-tagline">Smart tools para sa iyong tindahan</div>
    </div>

    <div class="auth-brand-body">
      <div class="auth-pos-preview">
        <div class="auth-pos-preview-row">
          <span class="auth-pos-item-name">Bottled Water ×2</span>
          <span class="auth-pos-item-price">₱28.00</span>
        </div>
        <div class="auth-pos-preview-row">
          <span class="auth-pos-item-name">Coca-Cola ×1</span>
          <span class="auth-pos-item-price">₱20.00</span>
        </div>
        <div class="auth-pos-preview-row">
          <span class="auth-pos-item-name">Lucky Me ×3</span>
          <span class="auth-pos-item-price">₱45.00</span>
        </div>
        <div class="auth-pos-total">
          <span class="auth-pos-total-label">Total</span>
          <span class="auth-pos-total-value">₱93.00</span>
        </div>
      </div>

      <div class="auth-brand-headline">
        Start managing your tindahan<br><em>the right way.</em>
      </div>
      <div class="auth-brand-sub">
        Join TindaFlow — the POS built for small Filipino businesses. Free first month, no credit card needed.
      </div>
    </div>

    <div class="auth-brand-bottom">
      <div class="auth-trust-list">
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          First month completely free
        </div>
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          Personal setup assistance
        </div>
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          No automatic charges — ever
        </div>
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          Filipino support, Philippine time
        </div>
      </div>
    </div>
  </aside>

  <!-- ═══════════════════════════════════════════════
       RIGHT — Sign up form / Pending state
  ═══════════════════════════════════════════════ -->
  <main class="auth-form-panel signup">
    <div class="auth-form-card">

      <?php if ($show_pending): ?>
      <!-- ── PENDING APPROVAL STATE ── -->
      <div class="auth-pending-card">
        <div class="auth-pending-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="12" r="10"/>
            <polyline points="12 6 12 12 16 14"/>
          </svg>
        </div>
        <div class="auth-pending-title">Application received!</div>
        <p class="auth-pending-text">
          Thanks, <strong><?= html_escape($form['name']) ?></strong>! Your TindaFlow account for
          <strong><?= html_escape($form['business_name']) ?></strong> is under review.
          We'll get back to you within 24 hours.
        </p>
        <div class="auth-pending-steps">
          <div class="auth-pending-step">
            <div class="auth-pending-step-num">1</div>
            We review your application (usually within 24 hours)
          </div>
          <div class="auth-pending-step">
            <div class="auth-pending-step-num">2</div>
            We reach out personally to confirm your setup
          </div>
          <div class="auth-pending-step">
            <div class="auth-pending-step-num">3</div>
            Your store goes live — your free month starts
          </div>
        </div>
        <a href="login.php" class="auth-btn auth-btn-ghost">
          Back to Login
        </a>
      </div>

      <?php else: ?>
      <!-- ── SIGN UP FORM ── -->
      <div class="auth-form-header">
        <div class="auth-form-eyebrow">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
            <path d="M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2"/>
            <circle cx="9" cy="7" r="4"/>
            <line x1="19" y1="8" x2="19" y2="14"/>
            <line x1="22" y1="11" x2="16" y2="11"/>
          </svg>
          New Business Account
        </div>
        <h1 class="auth-form-title">Create your account</h1>
        <p class="auth-form-subtitle">Register your business on TindaFlow. Free for the first month.</p>
      </div>

      <?php if ($error !== ''): ?>
        <div class="auth-alert auth-alert-error" role="alert">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
          </svg>
          <?= html_escape($error) ?>
        </div>
      <?php endif; ?>

      <form method="POST" action="signup.php" id="signup-form" novalidate>
        <input type="hidden" name="csrf_token" value="<?= html_escape(csrf_token()) ?>">

        <!-- Business name -->
        <div class="auth-field">
          <div class="auth-field-label">
            <label class="auth-label" for="business_name">Business / Store name</label>
          </div>
          <div class="auth-input-wrap">
            <svg class="auth-input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/>
              <polyline points="9 22 9 12 15 12 15 22"/>
            </svg>
            <input
              type="text"
              id="business_name"
              name="business_name"
              class="auth-input <?= isset($field_errors['business_name']) ? 'is-error' : '' ?>"
              placeholder="dela Cruz Sari-Sari Store"
              value="<?= html_escape($form['business_name']) ?>"
              autocomplete="organization"
              required
              autofocus
            >
          </div>
          <?php if (isset($field_errors['business_name'])): ?>
            <div class="auth-field-hint hint-error">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              <?= html_escape($field_errors['business_name']) ?>
            </div>
          <?php endif; ?>
        </div>

        <!-- Full name -->
        <div class="auth-field">
          <div class="auth-field-label">
            <label class="auth-label" for="name">Your full name</label>
          </div>
          <div class="auth-input-wrap">
            <svg class="auth-input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/>
              <circle cx="12" cy="7" r="4"/>
            </svg>
            <input
              type="text"
              id="name"
              name="name"
              class="auth-input <?= isset($field_errors['name']) ? 'is-error' : '' ?>"
              placeholder="Juan dela Cruz"
              value="<?= html_escape($form['name']) ?>"
              autocomplete="name"
              required
            >
          </div>
          <?php if (isset($field_errors['name'])): ?>
            <div class="auth-field-hint hint-error">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              <?= html_escape($field_errors['name']) ?>
            </div>
          <?php endif; ?>
        </div>

        <!-- Email -->
        <div class="auth-field">
          <div class="auth-field-label">
            <label class="auth-label" for="email">Email address</label>
          </div>
          <div class="auth-input-wrap">
            <svg class="auth-input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
              <polyline points="22,6 12,13 2,6"/>
            </svg>
            <input
              type="email"
              id="email"
              name="email"
              class="auth-input <?= isset($field_errors['email']) ? 'is-error' : '' ?>"
              placeholder="juan@example.com"
              value="<?= html_escape($form['email']) ?>"
              autocomplete="email"
              required
            >
          </div>
          <?php if (isset($field_errors['email'])): ?>
            <div class="auth-field-hint hint-error">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              <?= html_escape($field_errors['email']) ?>
            </div>
          <?php endif; ?>
        </div>

        <!-- Password -->
        <div class="auth-field">
          <div class="auth-field-label">
            <label class="auth-label" for="password">Password</label>
          </div>
          <div class="auth-input-wrap">
            <svg class="auth-input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
              <path d="M7 11V7a5 5 0 0110 0v4"/>
            </svg>
            <input
              type="password"
              id="password"
              name="password"
              class="auth-input has-toggle <?= isset($field_errors['password']) ? 'is-error' : '' ?>"
              placeholder="Min. 10 characters"
              autocomplete="new-password"
              required
              minlength="10"
            >
            <button type="button" class="auth-password-toggle" aria-label="Show/hide password" data-target="password">
              <svg class="icon-eye" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
              <svg class="icon-eye-off" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none;">
                <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/>
                <line x1="1" y1="1" x2="23" y2="23"/>
              </svg>
            </button>
          </div>
          <!-- Password strength meter -->
          <div class="auth-strength" id="strength-wrap" style="display:none;">
            <div class="auth-strength-bar">
              <div class="auth-strength-seg" id="seg-1"></div>
              <div class="auth-strength-seg" id="seg-2"></div>
              <div class="auth-strength-seg" id="seg-3"></div>
              <div class="auth-strength-seg" id="seg-4"></div>
            </div>
            <span class="auth-strength-label" id="strength-label"></span>
          </div>
          <?php if (isset($field_errors['password'])): ?>
            <div class="auth-field-hint hint-error">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              <?= html_escape($field_errors['password']) ?>
            </div>
          <?php else: ?>
            <div class="auth-field-hint hint-muted">
              Min. 10 characters, must include letters and numbers.
            </div>
          <?php endif; ?>
        </div>

        <!-- Confirm password -->
        <div class="auth-field">
          <div class="auth-field-label">
            <label class="auth-label" for="password2">Confirm password</label>
          </div>
          <div class="auth-input-wrap">
            <svg class="auth-input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <polyline points="9 11 12 14 22 4"/>
              <path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/>
            </svg>
            <input
              type="password"
              id="password2"
              name="password2"
              class="auth-input has-toggle <?= isset($field_errors['password2']) ? 'is-error' : '' ?>"
              placeholder="Repeat your password"
              autocomplete="new-password"
              required
            >
            <button type="button" class="auth-password-toggle" aria-label="Show/hide confirm password" data-target="password2">
              <svg class="icon-eye" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
              <svg class="icon-eye-off" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none;">
                <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/>
                <line x1="1" y1="1" x2="23" y2="23"/>
              </svg>
            </button>
          </div>
          <?php if (isset($field_errors['password2'])): ?>
            <div class="auth-field-hint hint-error">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              <?= html_escape($field_errors['password2']) ?>
            </div>
          <?php endif; ?>
        </div>

        <!-- Terms agreement -->
        <label class="auth-checkbox-wrap">
          <input
            type="checkbox"
            name="agreed"
            class="auth-checkbox"
            <?= !empty($_POST['agreed']) ? 'checked' : '' ?>
          >
          <span class="auth-checkbox-label">
            I agree to TindaFlow's
            <a href="<?= pos_base_url() ?>terms.html" target="_blank">Terms of Service</a>
            and
            <a href="<?= pos_base_url() ?>privacy.html" target="_blank">Privacy Policy</a>.
          </span>
        </label>
        <?php if (isset($field_errors['agreed'])): ?>
          <div class="auth-field-hint hint-error" style="margin-top:-0.5rem;margin-bottom:0.75rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
            <?= html_escape($field_errors['agreed']) ?>
          </div>
        <?php endif; ?>

        <button type="submit" class="auth-btn auth-btn-primary" id="signup-btn">
          Create Account
        </button>
      </form>

      <div class="auth-switch">
        Already have an account? <a href="login.php">Sign in</a>
      </div>

      <?php endif; // end show_pending ?>

    </div>

    <footer class="auth-footer">
      <span class="app-footer-inner">
        <span style="color:#1a5c4a;">Tinda</span><span style="color:#f59e0b;">Flow</span>
        · Secure register for small retail
      </span>
    </footer>
  </main>

</div>

<script>
(function () {
  // Password visibility toggle
  document.querySelectorAll('.auth-password-toggle').forEach(function (btn) {
    btn.setAttribute('aria-pressed', 'false');
    btn.addEventListener('click', function () {
      var input  = document.getElementById(btn.dataset.target);
      var eyeOn  = btn.querySelector('.icon-eye');
      var eyeOff = btn.querySelector('.icon-eye-off');
      if (!input) return;
      var isConfirm = btn.dataset.target === 'password2';
      if (input.type === 'password') {
        input.type = 'text';
        eyeOn.style.display  = 'none';
        eyeOff.style.display = '';
        btn.setAttribute('aria-pressed', 'true');
        btn.setAttribute('aria-label', isConfirm ? 'Hide confirm password' : 'Hide password');
      } else {
        input.type = 'password';
        eyeOn.style.display  = '';
        eyeOff.style.display = 'none';
        btn.setAttribute('aria-pressed', 'false');
        btn.setAttribute('aria-label', isConfirm ? 'Show confirm password' : 'Show password');
      }
    });
  });

  // Password strength meter
  var passInput     = document.getElementById('password');
  var strengthWrap  = document.getElementById('strength-wrap');
  var strengthLabel = document.getElementById('strength-label');
  var segs = [
    document.getElementById('seg-1'),
    document.getElementById('seg-2'),
    document.getElementById('seg-3'),
    document.getElementById('seg-4'),
  ];

  function getStrength(val) {
    var score = 0;
    if (val.length >= 10)          score++;
    if (/[A-Z]/.test(val))         score++;
    if (/[0-9]/.test(val))         score++;
    if (/[^A-Za-z0-9]/.test(val))  score++;
    return score;
  }

  var levels = [
    { cls: 'seg-weak',   label: 'Weak',   labelCls: 'label-weak'   },
    { cls: 'seg-fair',   label: 'Fair',   labelCls: 'label-fair'   },
    { cls: 'seg-good',   label: 'Good',   labelCls: 'label-good'   },
    { cls: 'seg-strong', label: 'Strong', labelCls: 'label-strong' },
  ];

  if (passInput) {
    passInput.addEventListener('input', function () {
      var val = passInput.value;
      if (val.length === 0) { strengthWrap.style.display = 'none'; return; }
      strengthWrap.style.display = '';
      var score = Math.max(1, getStrength(val));
      var level = levels[score - 1];
      segs.forEach(function (seg, i) {
        seg.className = 'auth-strength-seg' + (i < score ? ' ' + level.cls : '');
      });
      strengthLabel.textContent = level.label;
      strengthLabel.className   = 'auth-strength-label ' + level.labelCls;
    });
  }

  // Confirm password match indicator
  var pass2Input = document.getElementById('password2');
  if (pass2Input) {
    pass2Input.addEventListener('input', function () {
      if (pass2Input.value === '') return;
      if (pass2Input.value === passInput.value) {
        pass2Input.classList.add('is-success');
        pass2Input.classList.remove('is-error');
      } else {
        pass2Input.classList.add('is-error');
        pass2Input.classList.remove('is-success');
      }
    });
  }

  // Loading state on submit
  var form = document.getElementById('signup-form');
  var btn  = document.getElementById('signup-btn');
  if (form) {
    form.addEventListener('submit', function () {
      btn.disabled = true;
      btn.innerHTML = '<span class="auth-spinner"></span> Creating account\u2026';
    });
  }
})();
</script>

</body>
</html>