<?php
// admin/user_edit.php
// Classic TowLens – medium popup to edit a single user (system admin only)

session_start();

$config = require __DIR__ . '/../lib/config.php';
require __DIR__ . '/../lib/db.php';
require __DIR__ . '/../lib/helpers.php';

require_admin_auth($config);

// Hard gate: only system admins
if (($_SESSION['user']['role'] ?? '') !== 'admin') {
    http_response_code(403);
    echo 'Admins only.';
    exit;
}

if ($pdo instanceof PDO) {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

$userId = (int)($_GET['id'] ?? 0);

$errorMessage = null;
$notices      = [];
$saved        = false;

/** CSRF **/
function user_edit_csrf_token(): string {
    if (empty($_SESSION['user_edit_csrf'])) {
        $_SESSION['user_edit_csrf'] = bin2hex(random_bytes(16));
    }
    return $_SESSION['user_edit_csrf'];
}
function user_edit_csrf_ok(): bool {
    return !empty($_POST['csrf'])
        && !empty($_SESSION['user_edit_csrf'])
        && hash_equals($_SESSION['user_edit_csrf'], $_POST['csrf']);
}

// Load user
$user = null;
if ($userId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
} else {
    $errorMessage = 'User not found.';
}

if (!$user && !$errorMessage) {
    $errorMessage = 'User not found.';
}

// Load companies for dropdown (with org names)
$companies = [];
if (!$errorMessage) {
    try {
        $cStmt = $pdo->query("
            SELECT c.id,
                   c.name,
                   c.slug,
                   c.organisation_id,
                   o.name AS org_name
              FROM companies c
         LEFT JOIN organisations o ON o.id = c.organisation_id
          ORDER BY o.name, c.name
        ");
        $companies = $cStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        // If companies table missing etc., just leave empty
        $companies = [];
    }
}

// Allowed roles + providers
$roleOptions = [
    'admin'          => 'Admin',
    'org_admin'      => 'Organisation Admin',
    'company_admin'  => 'Company Admin',
    'staff'          => 'Staff',
];
$providerOptions = [
    'local' => 'Local password',
    'entra' => 'Entra ID (SSO)',
];

$errors = [];

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $user && !$errorMessage) {
    if (!user_edit_csrf_ok()) {
        $errors[] = 'Your session expired. Please reload the window.';
    } else {
        $email        = trim($_POST['email'] ?? '');
        $display_name = trim($_POST['display_name'] ?? '');
        $rolePost     = trim($_POST['role'] ?? '');
        $providerPost = trim($_POST['provider'] ?? '');
        $is_active    = isset($_POST['is_active']) ? 1 : 0;
        $companyIdPost = isset($_POST['company_id']) && $_POST['company_id'] !== ''
            ? (int)$_POST['company_id']
            : null;

        $organisationIdPost = null;

        if ($email === '') {
            $errors[] = 'Email is required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Email is not valid.';
        }

        if ($display_name === '') {
            $errors[] = 'Display name is required.';
        }

        if (!array_key_exists($rolePost, $roleOptions)) {
            $rolePost = $user['role'] ?: 'staff';
        }
        if (!array_key_exists($providerPost, $providerOptions)) {
            $providerPost = $user['provider'] ?: 'local';
        }

        // If a company is selected, validate and fetch organisation_id from companies table
        if ($companyIdPost !== null) {
            $orgStmt = $pdo->prepare("SELECT organisation_id FROM companies WHERE id = ? LIMIT 1");
            $orgStmt->execute([$companyIdPost]);
            $organisationIdPost = $orgStmt->fetchColumn();
            if (!$organisationIdPost) {
                $errors[] = 'Selected company not found.';
            } else {
                $organisationIdPost = (int)$organisationIdPost;
            }
        } else {
            // Allow user to be system-level with no company/org
            $companyIdPost      = null;
            $organisationIdPost = null;
        }

        // Optional: simple uniqueness check for email
        if (!$errors) {
            $chk = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id <> ?");
            $chk->execute([$email, $userId]);
            if ((int)$chk->fetchColumn() > 0) {
                $errors[] = 'Another user already uses this email address.';
            }
        }

        if (!$errors) {
            $stmt = $pdo->prepare("
                UPDATE users
                   SET email           = :email,
                       display_name    = :display_name,
                       role            = :role,
                       provider        = :provider,
                       is_active       = :is_active,
                       organisation_id = :organisation_id,
                       company_id      = :company_id
                 WHERE id = :id
                 LIMIT 1
            ");
            $stmt->execute([
                ':email'           => $email,
                ':display_name'    => $display_name,
                ':role'            => $rolePost,
                ':provider'        => $providerPost,
                ':is_active'       => $is_active,
                ':organisation_id' => $organisationIdPost,
                ':company_id'      => $companyIdPost,
                ':id'              => $userId,
            ]);

            $saved = true;
            $notices[] = 'User details updated.';

            // Reload the user row
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
            $stmt->execute([$userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: $user;
        } else {
            // Keep selected company in memory if there were errors
            $user['company_id']      = $companyIdPost;
            $user['organisation_id'] = $organisationIdPost;
        }
    }
}

$csrf = user_edit_csrf_token();
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>
    Edit User – <?php echo $user ? esc($user['email']) : 'TowLens Admin'; ?>
  </title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>
  :root{
    --bg:#e5ecf5; --win:#ffffff; --ink:#111827; --muted:#6b7280; --line:#cfd6de;
    --brand:#2f6db2; --brand-dark:#255a95;
    --radius:4px; --shadow:0 1px 0 rgba(0,0,0,.04),0 2px 4px rgba(0,0,0,.10);
    --hdr-grad:linear-gradient(#f8fafc,#e4ecf6);
    --btn-grad:linear-gradient(#f8fafc,#e6ecf2);
    --btn-grad-active:linear-gradient(#e6ecf2,#d9e1e9);
  }
  *{box-sizing:border-box}
  body{
    margin:0;
    font:13px/1.45 Segoe UI,Tahoma,Arial,Helvetica,sans-serif;
    color:var(--ink);
    background:var(--bg);
    -webkit-user-select:none;
    user-select:none;
  }
  .shell{
    max-width:640px;
    margin:10px auto 16px;
    padding:0 10px;
  }
  .popup{
    background:#ffffff;
    border-radius:var(--radius);
    border:1px solid var(--line);
    box-shadow:var(--shadow);
    overflow:hidden;
  }
  .popup-header{
    background:var(--hdr-grad);
    border-bottom:1px solid var(--line);
    padding:8px 10px;
    display:flex;
    justify-content:space-between;
    align-items:center;
  }
  .popup-title{
    font-size:14px;
    font-weight:600;
  }
  .popup-sub{
    font-size:11px;
    color:var(--muted);
  }
  .popup-body{
    padding:10px 10px 8px;
  }
  .popup-footer{
    padding:8px 10px;
    border-top:1px solid #e5e7eb;
    display:flex;
    justify-content:flex-end;
    gap:8px;
    background:#f9fafb;
  }

  .field-row{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:8px;
  }
  .field{
    flex:1;
    min-width:210px;
  }
  label{
    display:block;
    font-size:10px;
    text-transform:uppercase;
    letter-spacing:.09em;
    color:var(--muted);
    margin-bottom:2px;
  }
  input[type="text"],
  input[type="email"],
  select{
    width:100%;
    padding:6px 7px;
    border-radius:3px;
    border:1px solid #cfd6de;
    font-size:12px;
    outline:none;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.9);
    background:#f9fafb;
  }
  input[type="text"]:focus,
  input[type="email"]:focus,
  select:focus{
    border-color:#99b4d6;
    background:#ffffff;
  }
  .help-text{
    font-size:10px;
    color:#9ca3af;
    margin-top:1px;
  }

  .alerts{margin:4px 0 8px;}
  .alert{
    padding:6px 8px;
    border-radius:3px;
    margin-bottom:4px;
    font-size:11px;
  }
  .alert.error{
    background:#fae7e7;
    border:1px solid #e3b1b1;
    color:#7f2020;
  }
  .alert.ok{
    background:#eaf2fd;
    border:1px solid #b9d0f5;
    color:#163a6c;
  }

  .btn{
    appearance:none;
    border:1px solid #bfc8d2;
    background:var(--btn-grad);
    color:#123;
    font-weight:600;
    padding:6px 10px;
    border-radius:var(--radius);
    cursor:pointer;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.85),0 1px 0 rgba(255,255,255,.5);
    font-size:12px;
    transition:background .15s ease, transform .05s ease;
  }
  .btn:hover{background:var(--btn-grad-active);}
  .btn:active{transform:translateY(1px);}
  .btn.primary{
    border-color:#2a5f9c;
    color:#fff;
    background:linear-gradient(#3b79c1,#2b67ab);
  }
  .btn.secondary{
    background:var(--btn-grad);
    color:#223;
  }
  .checkbox-row{
    display:flex;
    align-items:center;
    gap:6px;
    margin-top:4px;
  }
  .checkbox-row input[type="checkbox"]{
    width:auto;
  }
  </style>
</head>
<body>

<div class="shell">
  <div class="popup">
    <div class="popup-header">
      <div>
        <div class="popup-title">Edit User</div>
        <div class="popup-sub">
          <?php echo $user ? esc($user['email']) : 'User not found'; ?>
        </div>
      </div>
      <button type="button" class="btn secondary" onclick="window.close();">✕</button>
    </div>

    <div class="popup-body">

      <?php if ($errorMessage): ?>
        <div class="alerts">
          <div class="alert error"><?php echo esc($errorMessage); ?></div>
        </div>
      <?php else: ?>

        <div class="alerts">
          <?php foreach ($errors as $e): ?>
            <div class="alert error"><?php echo esc($e); ?></div>
          <?php endforeach; ?>
          <?php foreach ($notices as $n): ?>
            <div class="alert ok"><?php echo esc($n); ?></div>
          <?php endforeach; ?>
        </div>

        <form method="post">
          <input type="hidden" name="csrf" value="<?php echo esc($csrf); ?>">

          <div class="field-row">
            <div class="field">
              <label>Email</label>
              <input type="email" name="email" value="<?php echo esc($user['email']); ?>">
              <div class="help-text">Changing this will affect how the user signs in.</div>
            </div>
          </div>

          <div class="field-row">
            <div class="field">
              <label>Display name</label>
              <input type="text" name="display_name" value="<?php echo esc($user['display_name']); ?>">
            </div>
          </div>

          <div class="field-row">
            <div class="field">
              <label>Role</label>
              <select name="role">
                <?php
                  $currentRole = $user['role'] ?: 'staff';
                  foreach ($roleOptions as $val => $label):
                ?>
                  <option value="<?php echo esc($val); ?>"
                    <?php if ($currentRole === $val) echo 'selected'; ?>>
                    <?php echo esc($label); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="help-text">Higher roles grant more access across the system.</div>
            </div>
            <div class="field">
              <label>Provider</label>
              <select name="provider">
                <?php
                  $currentProvider = $user['provider'] ?: 'local';
                  foreach ($providerOptions as $val => $label):
                ?>
                  <option value="<?php echo esc($val); ?>"
                    <?php if ($currentProvider === $val) echo 'selected'; ?>>
                    <?php echo esc($label); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="help-text">Switch between local password or Entra SSO.</div>
            </div>
          </div>

          <div class="field-row">
            <div class="field">
              <label>Company</label>
              <select name="company_id">
                <option value="">— No company / system-level —</option>
                <?php
                  $currentCompanyId = isset($user['company_id']) ? (int)$user['company_id'] : 0;
                  foreach ($companies as $c):
                    $label = ($c['org_name'] ? $c['org_name'] . ' — ' : '') . $c['name'];
                ?>
                  <option value="<?php echo (int)$c['id']; ?>"
                    <?php if ($currentCompanyId === (int)$c['id']) echo 'selected'; ?>>
                    <?php echo esc($label); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="help-text">
                Changing this moves the user to another client company and updates their organisation automatically.
              </div>
            </div>
          </div>

          <div class="field-row">
            <div class="field">
              <label>Status</label>
              <div class="checkbox-row">
                <input type="checkbox" id="is_active" name="is_active"
                  <?php if ((int)$user['is_active'] === 1) echo 'checked'; ?>>
                <label for="is_active" style="text-transform:none;letter-spacing:0;font-size:12px;">
                  User is active
                </label>
              </div>
              <div class="help-text">Untick to disable login for this user.</div>
            </div>
          </div>

          <div class="popup-footer">
            <button type="button" class="btn secondary" onclick="window.close();">Close</button>
            <button type="submit" class="btn primary">Save changes</button>
          </div>
        </form>

      <?php endif; ?>

    </div>
  </div>
</div>

<script>
  // Right-click off
  window.addEventListener('contextmenu', e => e.preventDefault(), {passive:false});

  // If saved, gently refresh opener so company/user lists update
  (function () {
    var saved = <?php echo $saved ? 'true' : 'false'; ?>;
    if (saved && window.opener && !window.opener.closed) {
      try { window.opener.location.reload(); } catch (e) {}
    }
  })();
</script>

</body>
</html>
