<?php
require_once __DIR__ . '/Includes.php';
require_once __DIR__ . '/pos_core.php';
try {
  pos_ensure_schema($pdo);
} catch (Throwable $e) {
  $supportCode = strtoupper(substr(hash('sha256', get_class($e) . '|' . $e->getMessage() . '|' . $e->getLine()), 0, 12));
  error_log('POS login startup failure [' . $supportCode . ']: ' . $e->getMessage());
  http_response_code(500);
  exit('POS database setup is incomplete. Upload the POS hotfix and import DB/modern_pos_hotfix.sql. Support code: ' . $supportCode);
}

$themePalette = get_school_theme_palette($pdo);
$paletteBg = (string)($themePalette['bg_cream'] ?? '#F7FBF7');
$palettePanel = (string)($themePalette['brand_ice'] ?? '#EEF7EF');
$paletteInk = (string)($themePalette['ink'] ?? '#173122');
$paletteMuted = (string)($themePalette['muted'] ?? '#4F6656');
$paletteLine = (string)($themePalette['patch_sky_soft'] ?? '#D6EEFF');
$paletteBrand = (string)($themePalette['brand_navy'] ?? '#2E8B45');
$paletteBrandDeep = (string)($themePalette['brand_navy_deep'] ?? '#1D6A33');

// The shared POS bootstrap creates and upgrades all POS tables.

if (mavela_demo_mode()) {
  $seedUsers = [
    ['Tuckshop Manager', 'tuckshop', 'TuckshopDemo7', 'tuckshop', 'manager'],
    ['Produce Manager', 'produce', 'ProduceDemo7', 'produce', 'manager'],
  ];
  $findUserStmt = $pdo->prepare("SELECT id FROM tp_users WHERE username = ? LIMIT 1");
  $insertUserStmt = $pdo->prepare("INSERT INTO tp_users (full_name, username, password_hash, workspace, role) VALUES (?, ?, ?, ?, ?)");
  foreach ($seedUsers as $seedUser) {
    $findUserStmt->execute([$seedUser[1]]);
    if (!$findUserStmt->fetch()) {
      try {
        $insertUserStmt->execute([
          $seedUser[0],
          $seedUser[1],
          password_hash($seedUser[2], PASSWORD_DEFAULT),
          $seedUser[3],
          $seedUser[4]
        ]);
      } catch (PDOException $e) {
        // Keep local demo setup idempotent.
      }
    }
  }
}

$seedProducts = mavela_demo_mode() ? [
  ['tuckshop', 'Biscuits', 'Marie Biscuits', 'packet', 0.55, 0.90, 80, 20],
  ['tuckshop', 'Sweets & Snacks', 'Assorted Sweets', 'bag', 0.40, 0.75, 120, 30],
  ['tuckshop', 'Chips', 'Potato Chips', 'packet', 0.65, 1.10, 90, 25],
  ['tuckshop', 'Fast Food', 'Mini Burgers', 'item', 1.20, 2.00, 40, 10],
  ['tuckshop', 'Bakery', 'Puffs', 'item', 0.85, 1.50, 50, 12],
  ['produce', 'Vegetables', 'Tomatoes', 'kg', 0.80, 1.30, 70, 15],
  ['produce', 'Vegetables', 'Onions', 'kg', 0.70, 1.20, 85, 20],
  ['produce', 'Livestock', 'Broilers', 'bird', 3.40, 5.00, 30, 8],
  ['produce', 'Protein', 'Fish', 'kg', 2.50, 3.80, 28, 8],
  ['produce', 'Protein', 'Eggs', 'tray', 3.00, 4.20, 24, 6]
] : [];
$findProductStmt = $pdo->prepare("SELECT id FROM tp_products WHERE workspace = ? AND product_name = ? LIMIT 1");
$insertProductStmt = $pdo->prepare("INSERT INTO tp_products
  (workspace, category, product_name, unit_label, buying_price, selling_price, stock_qty, reorder_level)
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
foreach ($seedProducts as $seedProduct) {
  $findProductStmt->execute([$seedProduct[0], $seedProduct[2]]);
  if (!$findProductStmt->fetch()) {
    $insertProductStmt->execute($seedProduct);
  }
}

if (isset($_SESSION['tp_user_id'], $_SESSION['tp_workspace'])) {
  $sessionRole = (string)($_SESSION['tp_role'] ?? 'manager');
  if ($sessionRole === 'cashier') {
    header('Location: cashier_pos.php');
    exit;
  }
  if ($_SESSION['tp_workspace'] === 'tuckshop') {
    header('Location: tuckshop_desktop.php');
    exit;
  }
  if ($_SESSION['tp_workspace'] === 'produce') {
    header('Location: produce_desktop.php');
    exit;
  }
}

$businessAccountsMissing = (int)$pdo->query("SELECT COUNT(*) FROM tp_users")->fetchColumn() === 0;
$error = $businessAccountsMissing
  ? 'No business accounts are configured. A school administrator can create them from Business Accounts in the Admin Dashboard.'
  : '';
if (isset($_POST['tp_login'])) {
  $workspace = (string)($_POST['workspace'] ?? '');
  $username = strtolower(trim((string)($_POST['username'] ?? '')));
  $password = (string)($_POST['password'] ?? '');

  if (!in_array($workspace, ['tuckshop', 'produce'], true) || $username === '' || $password === '') {
    $error = 'Workspace, username, and password are required.';
  } elseif (login_attempt_is_blocked($pdo, 'business:' . $workspace . ':' . $username)) {
    $error = 'Too many unsuccessful sign-in attempts. Please wait 15 minutes and try again.';
  } else {
    $stmt = $pdo->prepare("SELECT id, full_name, username, password_hash, workspace, role FROM tp_users WHERE username = ? AND workspace = ? AND is_active = 1 LIMIT 1");
    $stmt->execute([$username, $workspace]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, (string)$user['password_hash'])) {
      clear_login_failures($pdo, 'business:' . $workspace . ':' . $username);
      session_regenerate_id(true);
      $_SESSION['tp_user_id'] = (int)$user['id'];
      $_SESSION['tp_name'] = (string)$user['full_name'];
      $_SESSION['tp_workspace'] = (string)$user['workspace'];
      $_SESSION['tp_role'] = (string)($user['role'] ?? 'manager');

      $role = (string)($user['role'] ?? 'manager');
      if ($role === 'cashier') {
        header('Location: cashier_pos.php');
        exit;
      }

      if ($workspace === 'tuckshop') {
        header('Location: tuckshop_desktop.php');
        exit;
      }
      header('Location: produce_desktop.php');
      exit;
    }

    record_login_failure($pdo, 'business:' . $workspace . ':' . $username);
    $error = 'Invalid workspace login details.';
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tuckshop & Produce Login</title>
  <style>
    :root {
      --bg: <?= h($paletteBg) ?>;
      --panel: <?= h($palettePanel) ?>;
      --ink: <?= h($paletteInk) ?>;
      --muted: <?= h($paletteMuted) ?>;
      --brand: <?= h($paletteBrand) ?>;
      --brand-deep: <?= h($paletteBrandDeep) ?>;
      --line: <?= h($paletteLine) ?>;
    }

    * { box-sizing: border-box; }

    body {
      margin: 0;
      min-height: 100vh;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      color: var(--ink);
      background:
        radial-gradient(circle at 15% 20%, #e7f3e9 0, transparent 35%),
        radial-gradient(circle at 85% 15%, #eef7f1 0, transparent 32%),
        linear-gradient(140deg, #fbfffa 0%, var(--bg) 45%, #f3fbf6 100%);
      display: grid;
      place-items: center;
      padding: 18px;
    }

    .portal {
      width: min(980px, 100%);
      display: grid;
      gap: 14px;
      grid-template-columns: 1.2fr 1fr;
    }

    .hero,
    .card {
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: 20px;
      box-shadow: 0 10px 28px rgba(31, 86, 51, 0.12);
    }

    .hero {
      padding: 28px;
      display: grid;
      gap: 14px;
      align-content: start;
    }

    .kicker {
      display: inline-block;
      padding: 6px 10px;
      border-radius: 999px;
      background: #fff;
      border: 1px solid var(--line);
      color: var(--brand-deep);
      font-size: 12px;
      font-weight: 700;
      letter-spacing: 0.04em;
      text-transform: uppercase;
    }

    h1 {
      margin: 0;
      font-size: clamp(1.5rem, 3vw, 2.2rem);
      line-height: 1.2;
    }

    p { margin: 0; color: var(--muted); line-height: 1.55; }

    .lane-grid {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 10px;
    }

    .lane {
      border: 1px solid var(--line);
      border-radius: 12px;
      padding: 10px;
      background: #fff;
    }

    .lane strong { display: block; margin-bottom: 4px; }

    .card {
      padding: 24px;
    }

    .field {
      margin-bottom: 12px;
    }

    label {
      display: block;
      margin-bottom: 6px;
      font-size: 0.9rem;
      color: var(--brand-deep);
      font-weight: 600;
    }

    input,
    select {
      width: 100%;
      padding: 11px 12px;
      border-radius: 10px;
      border: 1px solid var(--line);
      background: #fff;
      color: var(--ink);
      font-size: 0.95rem;
    }

    input:focus,
    select:focus {
      outline: 2px solid var(--line);
      border-color: var(--brand);
    }

    .btn {
      width: 100%;
      border: 0;
      border-radius: 12px;
      padding: 12px;
      font-size: 0.95rem;
      font-weight: 700;
      color: #fff;
      background: linear-gradient(135deg, var(--brand), var(--brand-deep));
      cursor: pointer;
    }

    .btn:hover { filter: brightness(1.04); }

    .hint {
      margin-top: 12px;
      font-size: 0.84rem;
      color: var(--brand-deep);
      background: #fff;
      border: 1px solid var(--line);
      border-radius: 10px;
      padding: 9px 10px;
    }

    .error {
      margin-bottom: 10px;
      border: 1px solid #efb1b1;
      background: #fff0f0;
      color: #7f1c1c;
      border-radius: 10px;
      padding: 9px 10px;
      font-size: 0.9rem;
    }

    .actions {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      gap: 10px;
      flex-wrap: wrap;
      font-size: 0.84rem;
    }

    .actions a {
      color: var(--brand);
      text-decoration: none;
      font-weight: 600;
    }

    @media (max-width: 900px) {
      .portal {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
  <main class="portal">
    <section class="hero">
      <span class="kicker">Business Desktop</span>
      <h1>Tuckshop & Produce Projects Workspaces</h1>
      <p>Each side logs in to its own independent desktop. Tuckshop handles snacks and fast food sales, while Produce tracks agricultural products and project outputs.</p>

      <div class="lane-grid">
        <article class="lane">
          <strong>Tuckshop Workspace</strong>
          <p>Biscuits, sweets, snacks, chips, burgers, puffs and more.</p>
        </article>
        <article class="lane">
          <strong>Produce Workspace</strong>
          <p>Vegetables, tomatoes, onions, fish, broilers, eggs and stock planning.</p>
        </article>
      </div>
    </section>

    <section class="card">
      <h2 style="margin-top:0;">Workspace Login</h2>
      <?php if ($error !== ''): ?>
        <div class="error"><?= h($error) ?></div>
      <?php endif; ?>

      <form method="POST" autocomplete="off">
        <div class="field">
          <label for="workspace">Select Workspace</label>
          <select id="workspace" name="workspace" required>
            <option value="">Choose workspace</option>
            <option value="tuckshop">Tuckshop</option>
            <option value="produce">Produce & Projects</option>
          </select>
        </div>

        <div class="field">
          <label for="username">Username</label>
          <input id="username" name="username" placeholder="Your username" autocomplete="username" required>
        </div>

        <div class="field">
          <label for="password">Password</label>
          <input id="password" type="password" name="password" placeholder="Enter password" autocomplete="current-password" required>
        </div>

        <button class="btn" name="tp_login" type="submit">Sign In To Workspace</button>
      </form>

      <div class="actions">
        <a href="index.php">Back to Main System</a>
      </div>
    </section>
  </main>
</body>
</html>
