<?php
declare(strict_types=1);
require_once __DIR__ . '/Includes.php';
require_once __DIR__ . '/pos_core.php';
pos_ensure_schema($pdo);
check_login('admin');

// POS account schema is maintained by pos_ensure_schema().

$alerts = [];
if (isset($_POST['create_business_user'])) {
  $fullName = trim((string)($_POST['full_name'] ?? ''));
  $username = strtolower(trim((string)($_POST['username'] ?? '')));
  $workspace = (string)($_POST['workspace'] ?? '');
  $role = (string)($_POST['role'] ?? '');
  $password = (string)($_POST['password'] ?? '');

  if ($fullName === '' || !preg_match('/^[a-z0-9._-]{3,80}$/', $username)) {
    $alerts[] = ['type' => 'error', 'text' => 'Enter a full name and a username of 3–80 letters, numbers, dots, dashes, or underscores.'];
  } elseif (!in_array($workspace, ['tuckshop', 'produce'], true) || !in_array($role, ['manager', 'cashier'], true)) {
    $alerts[] = ['type' => 'error', 'text' => 'Choose a valid workspace and access role.'];
  } elseif (!mavela_password_is_strong($password)) {
    $alerts[] = ['type' => 'error', 'text' => 'Use at least 10 characters with uppercase, lowercase, and a number.'];
  } else {
    try {
      $stmt = $pdo->prepare("INSERT INTO tp_users (full_name, username, password_hash, workspace, role, is_active)
        VALUES (?, ?, ?, ?, ?, 1)");
      $stmt->execute([$fullName, $username, password_hash($password, PASSWORD_DEFAULT), $workspace, $role]);
      append_system_log($pdo, 'business_user_created', "Created {$role} account {$username} for {$workspace}.", (int)$_SESSION['user_id'], 'admin', 'tp_user', (int)$pdo->lastInsertId());
      $alerts[] = ['type' => 'success', 'text' => 'Business account created successfully.'];
    } catch (PDOException $e) {
      $alerts[] = ['type' => 'error', 'text' => stripos($e->getMessage(), 'Duplicate') !== false ? 'That username is already in use.' : 'The business account could not be created.'];
    }
  }
}

if (isset($_POST['reset_business_password'])) {
  $userId = (int)($_POST['business_user_id'] ?? 0);
  $password = (string)($_POST['reset_password'] ?? '');
  if ($userId <= 0 || !mavela_password_is_strong($password)) {
    $alerts[] = ['type' => 'error', 'text' => 'Choose an account and use a strong password of at least 10 characters.'];
  } else {
    $stmt = $pdo->prepare("UPDATE tp_users SET password_hash = ? WHERE id = ? LIMIT 1");
    $stmt->execute([password_hash($password, PASSWORD_DEFAULT), $userId]);
    append_system_log($pdo, 'business_password_reset', 'Reset a business account password.', (int)$_SESSION['user_id'], 'admin', 'tp_user', $userId);
    $alerts[] = ['type' => 'success', 'text' => 'Business account password updated.'];
  }
}

if (isset($_POST['toggle_business_user'])) {
  $userId = (int)($_POST['business_user_id'] ?? 0);
  if ($userId > 0) {
    $stmt = $pdo->prepare("UPDATE tp_users SET is_active = IF(is_active = 1, 0, 1) WHERE id = ? LIMIT 1");
    $stmt->execute([$userId]);
    append_system_log($pdo, 'business_user_status_changed', 'Changed business account status.', (int)$_SESSION['user_id'], 'admin', 'tp_user', $userId);
    $alerts[] = ['type' => 'success', 'text' => 'Business account status changed.'];
  }
}

$businessUsers = $pdo->query("SELECT id, full_name, username, workspace, role, is_active, created_at
  FROM tp_users ORDER BY workspace, role, full_name")->fetchAll();
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Business Accounts | Mavela</title>
  <style>
    :root { --brand:#1d6a33; --ink:#173122; --muted:#5c6c61; --line:#dce8df; --panel:#fff; }
    * { box-sizing:border-box; }
    body { margin:0; padding:24px; font-family:system-ui,sans-serif; color:var(--ink); background:#f4f9f5; }
    main { width:min(1180px,100%); margin:auto; }
    header { display:flex; justify-content:space-between; gap:16px; align-items:center; margin-bottom:22px; }
    header h1 { margin:0; }
    header a { color:var(--brand); font-weight:800; }
    .grid { display:grid; grid-template-columns:minmax(300px,.8fr) minmax(0,1.4fr); gap:20px; }
    .panel { padding:22px; background:var(--panel); border:1px solid var(--line); border-radius:18px; box-shadow:0 12px 34px rgba(21,70,39,.08); }
    h2 { margin-top:0; }
    label { display:grid; gap:6px; margin-bottom:13px; font-weight:700; }
    input,select { width:100%; padding:10px 11px; border:1px solid var(--line); }
    button { padding:10px 14px; color:#fff; background:var(--brand); border:0; border-radius:10px; font-weight:800; cursor:pointer; }
    button.secondary { color:var(--ink); background:#eaf3ec; }
    .alert { margin:0 0 14px; padding:11px 13px; border-radius:10px; }
    .alert.success { color:#166534; background:#ecfdf3; }
    .alert.error { color:#9f1239; background:#fff1f3; }
    table { width:100%; }
    th,td { padding:11px; border-bottom:1px solid var(--line); text-align:left; }
    .status { display:inline-flex; padding:4px 8px; border-radius:999px; font-size:.78rem; font-weight:800; background:#dcfce7; color:#166534; }
    .status.off { color:#9f1239; background:#ffe4e8; }
    .actions { display:flex; gap:7px; flex-wrap:wrap; }
    .inline-reset { display:flex; gap:6px; }
    .inline-reset input { min-width:155px; }
    small { color:var(--muted); }
    @media(max-width:820px){ body{padding:14px}.grid{grid-template-columns:1fr}header{align-items:flex-start;flex-direction:column}.inline-reset{flex-direction:column} }
  </style>
</head>
<body>
<main>
  <header>
    <div><h1>Tuckshop &amp; Produce Accounts</h1><small>Create managers and cashiers, reset passwords, and suspend access.</small></div>
    <a href="admin.php">← Back to Admin Dashboard</a>
  </header>
  <?php foreach ($alerts as $alert): ?><div class="alert <?= h($alert['type']) ?>"><?= h($alert['text']) ?></div><?php endforeach; ?>
  <div class="grid">
    <section class="panel">
      <h2>Create account</h2>
      <form method="post">
        <label>Full name<input name="full_name" maxlength="120" autocomplete="name" required></label>
        <label>Username<input name="username" minlength="3" maxlength="80" pattern="[a-zA-Z0-9._-]+" autocomplete="username" required></label>
        <label>Workspace<select name="workspace" required><option value="tuckshop">Tuckshop</option><option value="produce">Produce</option></select></label>
        <label>Role<select name="role" required><option value="manager">Manager</option><option value="cashier">Cashier</option></select></label>
        <label>Temporary password<input type="password" name="password" minlength="10" autocomplete="new-password" required><small>10+ characters with uppercase, lowercase, and a number.</small></label>
        <button name="create_business_user" type="submit">Create account</button>
      </form>
    </section>
    <section class="panel">
      <h2>Existing accounts</h2>
      <?php if (!$businessUsers): ?><p>No business accounts have been created yet.</p><?php else: ?>
      <table>
        <thead><tr><th>Person</th><th>Access</th><th>Status</th><th>Actions</th></tr></thead>
        <tbody>
        <?php foreach ($businessUsers as $user): ?>
          <tr>
            <td><strong><?= h($user['full_name']) ?></strong><br><small><?= h($user['username']) ?></small></td>
            <td><?= h(ucfirst($user['workspace'])) ?><br><small><?= h(ucfirst($user['role'])) ?></small></td>
            <td><span class="status <?= (int)$user['is_active'] === 1 ? '' : 'off' ?>"><?= (int)$user['is_active'] === 1 ? 'Active' : 'Suspended' ?></span></td>
            <td>
              <div class="actions">
                <form method="post"><input type="hidden" name="business_user_id" value="<?= h($user['id']) ?>"><button class="secondary" name="toggle_business_user" type="submit"><?= (int)$user['is_active'] === 1 ? 'Suspend' : 'Activate' ?></button></form>
                <form method="post" class="inline-reset"><input type="hidden" name="business_user_id" value="<?= h($user['id']) ?>"><input type="password" name="reset_password" minlength="10" placeholder="New password" autocomplete="new-password" required><button name="reset_business_password" type="submit">Reset</button></form>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </section>
  </div>
</main>
</body>
</html>
