<?php
declare(strict_types=1);

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/../../config/auth.php";

require_admin();

$success = "";
$error   = "";

// Create user (Rep/Admin) — (Admin normally creates Reps)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $token = (string)($_POST['csrf'] ?? '');
    if (!csrf_validate($token)) {
        $error = "Invalid request.";
    } else {
        $name     = trim((string)($_POST['name'] ?? ''));
        $email    = strtolower(trim((string)($_POST['email'] ?? '')));
        $password = (string)($_POST['password'] ?? '');
        $role     = (string)($_POST['role'] ?? 'REP');
        $active   = (int)($_POST['active'] ?? 1);

        if ($name === '' || $email === '' || $password === '') {
            $error = "Name, Email and Password are required.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email.";
        } elseif (!in_array($role, ['ADMIN', 'REP'], true)) {
            $error = "Invalid role.";
        } elseif (strlen($password) < 6) {
            $error = "Password must be at least 6 characters.";
        } else {
            // check duplicate
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $error = "Email already exists.";
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO users (name, email, password_hash, role, active)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$name, $email, $hash, $role, $active]);

                $success = "User created: {$email}";
            }
        }
    }
}

// Toggle active
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'toggle') {
    $token = (string)($_POST['csrf'] ?? '');
    if (!csrf_validate($token)) {
        $error = "Invalid request.";
    } else {
        $userId = (int)($_POST['user_id'] ?? 0);
        if ($userId <= 0) {
            $error = "Invalid user.";
        } else {
            // prevent admin from disabling themselves
            $me = current_user();
            if ($me && (int)$me['id'] === $userId) {
                $error = "You cannot disable your own account.";
            } else {
                $stmt = $pdo->prepare("UPDATE users SET active = IF(active=1,0,1) WHERE id=?");
                $stmt->execute([$userId]);
                $success = "User status updated.";
            }
        }
    }
}

// fetch list
$users = $pdo->query("SELECT id, name, email, role, active, created_at FROM users ORDER BY id DESC")->fetchAll();

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Admin - Users</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <style>
    *{margin:0;padding:0;box-sizing:border-box}
    html,body{height:100%;width:100%}
    body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;background:#f8fafc;color:#1e293b}
    
    /* Header */
    .header{background:linear-gradient(135deg,#0f172a 0%,#1e293b 100%);color:#fff;padding:16px;position:sticky;top:0;z-index:100;box-shadow:0 2px 8px rgba(15,23,42,0.1)}
    .header-content{max-width:1200px;margin:0 auto}
    .header-title{font-size:20px;font-weight:700;margin-bottom:8px}
    .header-subtitle{font-size:13px;opacity:0.9}
    .header-buttons{display:flex;gap:8px;margin-top:12px;flex-wrap:wrap}
    
    /* Main Container */
    .container{max-width:1200px;margin:0 auto;padding:16px;min-height:100vh;display:flex;flex-direction:column}
    
    /* Messages */
    .msg-ok{background:#dcfce7;border:1px solid #bbf7d0;color:#14532d;padding:12px;border-radius:8px;margin-bottom:16px;font-size:14px;line-height:1.5}
    .msg-er{background:#fee2e2;border:1px solid #fecaca;color:#991b1b;padding:12px;border-radius:8px;margin-bottom:16px;font-size:14px;line-height:1.5}
    
    /* Card */
    .card{background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:20px;margin-bottom:20px;box-shadow:0 1px 3px rgba(0,0,0,0.05)}
    .card h3{font-size:18px;font-weight:700;margin:0 0 16px;color:#0f172a}
    
    /* Forms */
    label{display:block;font-size:14px;font-weight:500;margin:12px 0 6px;color:#1e293b}
    input,select{width:100%;padding:10px 12px;border:1px solid #cbd5e1;border-radius:8px;font-size:14px;font-family:inherit;color:#1e293b}
    input:focus,select:focus{outline:none;border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,0.1)}
    
    /* Form Grid */
    .row{display:grid;grid-template-columns:1fr;gap:12px;margin-bottom:12px}
    
    /* Buttons */
    .btn{display:inline-block;background:#3b82f6;color:#fff;text-decoration:none;padding:12px 16px;border-radius:8px;font-size:14px;font-weight:600;border:none;cursor:pointer;transition:background 0.2s,transform 0.1s;touch-action:manipulation}
    .btn:hover{background:#2563eb}
    .btn:active{transform:scale(0.98)}
    .btn-secondary{background:#6b7280;margin-left:8px}
    .btn-secondary:hover{background:#4b5563}
    .btn-danger{background:#ef4444}
    .btn-danger:hover{background:#dc2626}
    
    /* Button Block */
    .btn-block{width:100%;display:block;padding:12px;text-align:center;margin-top:12px}
    
    /* Pills */
    .pill{padding:6px 10px;border-radius:999px;font-size:12px;font-weight:500;display:inline-block}
    .on{background:#dcfce7;color:#14532d}
    .off{background:#fee2e2;color:#991b1b}
    
    /* Table Responsive */
    .table-responsive{overflow-x:auto;-webkit-overflow-scrolling:touch}
    table{width:100%;border-collapse:collapse;font-size:14px}
    th{background:#f1f5f9;padding:12px;text-align:left;font-weight:600;border-bottom:2px solid #e2e8f0}
    td{padding:12px;border-bottom:1px solid #e2e8f0}
    tr:last-child td{border-bottom:none}
    
    /* Mobile Table Layout */
    @media(max-width:768px){
      table,thead,tbody,th,td,tr{display:block;width:100%}
      thead{display:none}
      tr{border:1px solid #e2e8f0;border-radius:8px;margin-bottom:12px;overflow:hidden}
      td{text-align:right;padding:10px;padding-left:50%;position:relative;border:none;background:#f8fafc}
      td:before{content:attr(data-label);position:absolute;left:10px;font-weight:600;color:#475569;width:45%}
      td:last-child{border-bottom:none}
    }
    
    /* Responsive Grid */
    @media(min-width:640px){
      .header-content{display:flex;justify-content:space-between;align-items:flex-start}
      .header-buttons{justify-content:flex-end;margin-top:0}
      .row{grid-template-columns:1fr 1fr;gap:16px}
      .container{padding:24px}
    }
    
    @media(min-width:1024px){
      .row{grid-template-columns:repeat(3,1fr)}
      .container{padding:32px}
      .row.two-col{grid-template-columns:1fr 1fr}
    }
    
    /* Safe area for notches */
    @supports(padding:max(0px)){
      .header{padding-left:max(16px,env(safe-area-inset-left));padding-right:max(16px,env(safe-area-inset-right));padding-top:max(16px,env(safe-area-inset-top));padding-bottom:16px}
      .container{padding-left:max(16px,env(safe-area-inset-left));padding-right:max(16px,env(safe-area-inset-right))}
    }
  </style>
</head>
<body>
<div class="header">
  <div class="header-content">
    <div>
      <div class="header-title">Admin: Users</div>
      <div class="header-subtitle">Create Reps and manage access</div>
    </div>
    <div class="header-buttons">
      <a class="btn" href="/school-crm/public/dashboard.php">Dashboard</a>
      <a class="btn btn-secondary" href="/school-crm/logout.php">Logout</a>
    </div>
  </div>
</div>

<div class="container">

  <?php if ($success): ?><div class="msg-ok"><?= htmlspecialchars($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="msg-er"><?= htmlspecialchars($error) ?></div><?php endif; ?>

  <div class="card">
    <h3>Create User</h3>
    <form method="post">
      <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">

      <div class="row">
        <div>
          <label>Name</label>
          <input name="name" required>
        </div>
        <div>
          <label>Email</label>
          <input type="email" name="email" required>
        </div>
      </div>

      <div class="row">
        <div>
          <label>Password</label>
          <input type="text" name="password" placeholder="Min 6 chars" required>
        </div>
        <div>
          <label>Role</label>
          <select name="role">
            <option value="REP">REP</option>
            <option value="ADMIN">ADMIN</option>
          </select>
        </div>
        <div>
          <label>Active</label>
          <select name="active">
            <option value="1">Yes</option>
            <option value="0">No</option>
          </select>
        </div>
      </div>

      <button class="btn btn-block" type="submit" style="border:0;cursor:pointer;">Create User</button>
    </form>
  </div>

  <div class="card">
    <h3>Users List</h3>
    <div class="table-responsive">
      <table>
        <thead>
          <tr>
            <th>ID</th><th>Name</th><th>Email</th><th>Role</th><th>Status</th><th>Created</th><th>Action</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $u): ?>
          <tr>
            <td data-label="ID"><?= (int)$u['id'] ?></td>
            <td data-label="Name"><?= htmlspecialchars($u['name']) ?></td>
            <td data-label="Email"><?= htmlspecialchars($u['email']) ?></td>
            <td data-label="Role"><?= htmlspecialchars($u['role']) ?></td>
            <td data-label="Status">
              <?php if ((int)$u['active'] === 1): ?>
                <span class="pill on">ACTIVE</span>
              <?php else: ?>
                <span class="pill off">INACTIVE</span>
              <?php endif; ?>
            </td>
            <td data-label="Created"><?= htmlspecialchars($u['created_at']) ?></td>
            <td data-label="Action">
              <form method="post" style="display:inline;">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                <button class="btn btn-danger" type="submit" style="border:0;cursor:pointer;padding:8px 12px;font-size:13px;">
                  Toggle
                </button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
</body>
</html>
