<?php
// admin/company_edit.php
// Classic TowLens admin – Edit a single company (no URL hover for nav)

session_start();

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

require_admin_auth($config);

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

$base = rtrim($config['base_url'] ?? '', '/');

// User context
$me         = $_SESSION['user'] ?? [];
$orgId      = isset($me['organisation_id']) ? (int)$me['organisation_id'] : 0;
$role       = $me['role'] ?? '';
$isAdmin    = ($role === 'admin');
$isOrgAdmin = ($role === 'org_admin') || !empty($me['is_org_admin']);

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

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

// Load organisations for dropdown
$orgs = [];
try {
    $st   = $pdo->query("SELECT id, name FROM organisations ORDER BY name");
    $orgs = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // ignore if missing
}

// Load company with scoping
$company = null;
if ($id > 0) {
    if ($isAdmin) {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
    } else {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ? AND organisation_id = ? LIMIT 1");
        $stmt->execute([$id, $orgId]);
    }
    $company = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
} else {
    $errorMessage = 'Company not found.';
}

if (!$company && !$errorMessage) {
    $errorMessage = 'Company not found or not in your organisation.';
}

$errors  = [];
$notices = [];

// Handle POST update only if we have a valid company
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$errorMessage && $company) {
    if (!company_edit_csrf_ok()) {
        $errors[] = 'Your session expired. Please reload the page.';
    } else {
        $organisation_id = (int)($_POST['organisation_id'] ?? $company['organisation_id']);
        $name            = trim($_POST['name'] ?? '');
        $brand_name      = trim($_POST['brand_name'] ?? '');
        $brand_subtitle  = trim($_POST['brand_subtitle'] ?? '');
        $brand_color     = trim($_POST['brand_color'] ?? '');
        $logo_url        = trim($_POST['logo_url'] ?? '');
        $support_email   = trim($_POST['support_email'] ?? '');
        $slug            = trim($_POST['slug'] ?? '');
        $status          = trim($_POST['status'] ?? $company['status']);

        // Org admin cannot change organisation
        if (!$isAdmin) {
            $organisation_id = (int)$company['organisation_id'];
        }

        if ($organisation_id <= 0) {
            $errors[] = 'Please select an organisation.';
        }
        if ($name === '') {
            $errors[] = 'Company name is required.';
        }

        if ($support_email !== '' &&
            !filter_var($support_email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Support email is not valid.';
        }

        if ($slug === '') {
            $errors[] = 'Slug is required.';
        } else {
            $chk = $pdo->prepare("SELECT COUNT(*) FROM companies WHERE slug = ? AND id <> ?");
            $chk->execute([$slug, $id]);
            if ((int)$chk->fetchColumn() > 0) {
                $errors[] = 'Slug is already used by another company.';
            }
        }

        if (!$errors) {
            $stmt = $pdo->prepare("
                UPDATE companies
                   SET organisation_id = :org_id,
                       name            = :name,
                       brand_name      = :brand_name,
                       brand_subtitle  = :brand_subtitle,
                       brand_color     = :brand_color,
                       logo_url        = :logo_url,
                       support_email   = :support_email,
                       slug            = :slug,
                       status          = :status
                 WHERE id = :id
                 LIMIT 1
            ");
            $stmt->execute([
                ':org_id'         => $organisation_id,
                ':name'           => $name,
                ':brand_name'     => $brand_name,
                ':brand_subtitle' => $brand_subtitle,
                ':brand_color'    => $brand_color ?: null,
                ':logo_url'       => $logo_url ?: null,
                ':support_email'  => $support_email ?: null,
                ':slug'           => $slug,
                ':status'         => $status !== '' ? $status : 'active',
                ':id'             => $id,
            ]);

            $notices[] = 'Company details updated.';

            // Reload company
            if ($isAdmin) {
                $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ? LIMIT 1");
                $stmt->execute([$id]);
            } else {
                $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ? AND organisation_id = ? LIMIT 1");
                $stmt->execute([$id, $orgId]);
            }
            $company = $stmt->fetch(PDO::FETCH_ASSOC) ?: $company;
        }
    }
}

// Load users associated with this company
$companyUsers = [];
if ($company && !$errorMessage) {
    try {
        $uStmt = $pdo->prepare("
          SELECT id, email, display_name, role, is_active, provider
            FROM users
           WHERE company_id = ?
           ORDER BY email
        ");
        $uStmt->execute([$company['id']]);
        $companyUsers = $uStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $companyUsers = [];
    }
}

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

  <style>
  ::-webkit-scrollbar { width:10px; height:10px; }
  ::-webkit-scrollbar-track { background:#f1f4f8; border-left:1px solid var(--line); }
  ::-webkit-scrollbar-thumb {
    background:linear-gradient(var(--brand),var(--brand-dark));
    border-radius:5px;
    border:1px solid rgba(255,255,255,0.4);
  }
  ::-webkit-scrollbar-thumb:hover { background:linear-gradient(var(--brand-dark),#1e4c83); }
  * { scrollbar-width:thin; scrollbar-color:var(--brand) #f1f4f8; }

  :root{
    --bg:#eceff3; --win:#ffffff; --ink:#1f2933; --muted:#5d6b78; --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,.06);
    --hdr-grad:linear-gradient(#f8fafc,#e8edf3);
    --btn-grad:linear-gradient(#f8fafc,#e6ecf2);
    --btn-grad-active:linear-gradient(#e6ecf2,#d9e1e9);
  }
  *{box-sizing:border-box}
  html,body{height:100%}
  body{
    margin:0;
    font:13px/1.45 Segoe UI,Tahoma,Arial,Helvetica,sans-serif;
    color:var(--ink);
    background:var(--bg);
    -webkit-user-select:none;
    -ms-user-select:none;
    user-select:none;
  }
  .app{min-height:100%;display:flex;flex-direction:column}

  .ribbon{
    background:var(--hdr-grad);
    border-bottom:1px solid var(--line);
    box-shadow:var(--shadow);
  }
  .ribbon-inner{
    max-width:900px;
    margin:0 auto;
    padding:10px 14px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
  }
  .title-wrap{display:flex;align-items:center;gap:10px;}
  .wiz-icon{
    width:26px;height:26px;border-radius:4px;
    background:linear-gradient(#305c9c,#1f3564);
    box-shadow:inset 0 0 0 1px rgba(255,255,255,.4),0 2px 4px rgba(0,0,0,.15);
    position:relative;
  }
  .wiz-icon:before{
    content:"";
    position:absolute;
    left:6px;bottom:4px;
    border-left:7px solid transparent;
    border-right:7px solid transparent;
    border-bottom:12px solid #2f6db2;
  }
  .wiz-icon:after{
    content:"✦";
    position:absolute;
    right:4px;top:4px;
    font-size:8px;
    color:#ffe37a;
    text-shadow:0 0 2px #fff;
  }
  h1{font-size:16px;margin:0;}
  .sub{font-size:12px;color:var(--muted);}

  .nav-buttons{
    display:flex;
    gap:6px;
  }

  .window{
    max-width:900px;
    margin:16px auto 24px;
    padding:0 14px;
    width:100%;
  }

  .card{
    background:#ffffff;
    border-radius:var(--radius);
    border:1px solid var(--line);
    box-shadow:var(--shadow);
    padding:12px 12px 10px;
  }

  .field-row{
    display:flex;
    gap:10px;
    margin-bottom:8px;
    flex-wrap:wrap;
  }
  .field{
    flex:1;
    min-width:220px;
  }
  .field label{
    display:block;
    font-size:10px;
    text-transform:uppercase;
    letter-spacing:.09em;
    color:var(--muted);
    margin-bottom:2px;
  }
  .field input,
  .field 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;
  }
  .field input:focus,
  .field select:focus{
    border-color:#99b4d6;
    background:#ffffff;
  }
  .help-text{
    font-size:10px;
    color:#9ca3af;
    margin-top:1px;
  }

  .alerts{margin:6px 0 8px;}
  .alert{
    padding:7px 9px;
    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.small{padding:4px 8px;font-size:11px;}
  .btn.xsmall{padding:3px 6px;font-size:10px;}
  .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;
  }

  .actions{
    margin-top:10px;
    display:flex;
    justify-content:flex-end;
    gap:8px;
  }
  .slug-note{
    font-size:10px;
    color:#6b7280;
  }

  /* Users section */
  .section-title{
    margin:16px 2px 6px;
    font-size:11px;
    text-transform:uppercase;
    letter-spacing:.16em;
    color:var(--muted);
  }
  .card-users{
    margin-top:4px;
  }
  .card-header-row{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:6px;
  }
  .card-header-row .card-heading{
    font-size:13px;
    font-weight:600;
    color:#111827;
  }
  .card-header-row .card-sub{
    font-size:11px;
    color:#6b7280;
  }
  .card-header-row .right{
    display:flex;
    gap:6px;
  }

  .user-table{
    width:100%;
    border-collapse:collapse;
    font-size:12px;
  }
  .user-table th,
  .user-table td{
    padding:5px 6px;
    border-bottom:1px solid #e5e7eb;
    text-align:left;
  }
  .user-table th{
    font-size:11px;
    text-transform:uppercase;
    letter-spacing:.11em;
    color:#6b7280;
    background:#f9fafb;
  }
  .user-pill{
    display:inline-block;
    padding:2px 6px;
    border-radius:999px;
    font-size:10px;
    border:1px solid #cbd5e1;
    background:#eef2ff;
    color:#1e293b;
  }
  .user-pill.role{
    background:#e0f2fe;
  }
  .user-pill.status-active{
    background:#dcfce7;
    border-color:#bbf7d0;
    color:#166534;
  }
  .user-pill.status-disabled{
    background:#fee2e2;
    border-color:#fecaca;
    color:#991b1b;
  }
  .user-empty{
    font-size:12px;
    color:#6b7280;
    padding:4px 0;
  }
  </style>
</head>
<body>

<div class="app">

  <!-- Ribbon -->
  <div class="ribbon">
    <div class="ribbon-inner">
      <div class="title-wrap">
        <div class="wiz-icon"></div>
        <div>
          <h1>Edit Company</h1>
          <div class="sub">
            <?php echo $company ? esc($company['name']) : 'Company not found'; ?>
          </div>
        </div>
      </div>
      <div class="nav-buttons">
        <button type="button" class="btn small" data-nav="companies.php">
          ⬅ Back to Companies
        </button>
      </div>
    </div>
  </div>

  <div class="window">

    <?php if ($errorMessage): ?>
      <div class="alerts">
        <div class="alert error"><?php echo esc($errorMessage); ?></div>
      </div>
      <div class="actions" style="justify-content:flex-start;">
        <button type="button" class="btn secondary" data-nav="companies.php">
          ⬅ Back to Companies
        </button>
      </div>
    </div>
  </div>

  <script>
    window.addEventListener('contextmenu', e => e.preventDefault(), {passive:false});
    document.addEventListener('dragstart', e => {
      if (e.target && e.target.tagName === 'IMG') e.preventDefault();
    });
    document.addEventListener('click', function (e) {
      const btn = e.target.closest('[data-nav]');
      if (!btn) return;
      const href = btn.getAttribute('data-nav');
      if (!href) return;
      e.preventDefault();
      window.location.href = href;
    }, { passive: false });
  </script>

</body>
</html>
<?php exit; ?>
    <?php endif; ?>

    <div class="alerts">
      <?php foreach ($errors as $e): ?>
        <div class="alert error"><?php echo htmlspecialchars($e, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endforeach; ?>
      <?php foreach ($notices as $n): ?>
        <div class="alert ok"><?php echo htmlspecialchars($n, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endforeach; ?>
    </div>

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

      <div class="field-row">
        <div class="field">
          <label>Organisation</label>
          <select name="organisation_id" <?php if(!$isAdmin) echo 'disabled'; ?>>
            <?php foreach ($orgs as $o): ?>
              <option value="<?php echo (int)$o['id']; ?>"
                <?php if ((int)$company['organisation_id'] === (int)$o['id']) echo 'selected'; ?>>
                <?php echo esc($o['name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="help-text">
            <?php if ($isAdmin): ?>
              Changing this will move the company to another organisation.
            <?php else: ?>
              Only global admins can change organisation.
            <?php endif; ?>
          </div>
        </div>
        <div class="field">
          <label>Company name</label>
          <input type="text" name="name" value="<?php echo esc($company['name']); ?>" required>
        </div>
      </div>

      <div class="field-row">
        <div class="field">
          <label>Brand name</label>
          <input type="text" name="brand_name" value="<?php echo esc($company['brand_name']); ?>">
        </div>
        <div class="field">
          <label>Brand subtitle</label>
          <input type="text" name="brand_subtitle" value="<?php echo esc($company['brand_subtitle']); ?>">
        </div>
      </div>

      <div class="field-row">
        <div class="field">
          <label>Brand color (hex)</label>
          <input type="text" name="brand_color" value="<?php echo esc($company['brand_color']); ?>">
        </div>
        <div class="field">
          <label>Logo URL</label>
          <input type="text" name="logo_url" value="<?php echo esc($company['logo_url']); ?>">
        </div>
      </div>

      <div class="field-row">
        <div class="field">
          <label>Support email</label>
          <input type="email" name="support_email" value="<?php echo esc($company['support_email']); ?>">
        </div>
        <div class="field">
          <label>Slug</label>
          <input type="text" name="slug" value="<?php echo esc($company['slug']); ?>" required>
          <div class="slug-note">Must be unique. Changing this may affect routing/integration.</div>
        </div>
      </div>

      <div class="field-row">
        <div class="field">
          <label>Status</label>
          <input type="text" name="status" value="<?php echo esc($company['status']); ?>">
          <div class="help-text">Use <code>active</code> for live clients; another value for disabled/test.</div>
        </div>
      </div>

      <?php if (!empty($company['logo_url'])): ?>
        <div class="field-row">
          <div class="field">
            <label>Logo preview</label>
            <img src="<?php echo esc($company['logo_url']); ?>"
                 alt="Logo"
                 style="max-height:40px;max-width:160px;"
                 onerror="this.style.display='none'">
          </div>
        </div>
      <?php endif; ?>

      <div class="actions">
        <button type="button" class="btn secondary" data-nav="companies.php">Cancel</button>
        <button type="submit" class="btn primary">Save changes</button>
      </div>
    </form>

    <!-- Users in this company -->
    <div class="section-title">Users in this company</div>
    <div class="card card-users">
      <div class="card-header-row">
        <div>
          <div class="card-heading">
            Users linked to <?php echo esc($company['name']); ?>
          </div>
          <div class="card-sub">
            Manage staff accounts and SSO logins for this company.
          </div>
        </div>
        <div class="right">
          <button type="button"
                  class="btn small"
                  data-nav="users.php?company_id=<?php echo (int)$company['id']; ?>">
            Open Users Admin
          </button>
        </div>
      </div>

      <?php if (empty($companyUsers)): ?>
        <div class="user-empty">
          No users are currently linked to this company.
        </div>
      <?php else: ?>
        <table class="user-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Display name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Provider</th>
              <th>Status</th>
              <th style="width:1%;white-space:nowrap;">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($companyUsers as $u): ?>
            <tr>
              <td><?php echo (int)$u['id']; ?></td>
              <td><?php echo esc($u['display_name'] ?: ''); ?></td>
              <td><?php echo esc($u['email']); ?></td>
              <td>
                <?php if (!empty($u['role'])): ?>
                  <span class="user-pill role"><?php echo esc($u['role']); ?></span>
                <?php endif; ?>
              </td>
              <td>
                <?php if (!empty($u['provider'])): ?>
                  <span class="user-pill"><?php echo esc($u['provider']); ?></span>
                <?php endif; ?>
              </td>
              <td>
                <?php
                  $isActive = (int)($u['is_active'] ?? 0) === 1;
                  $statusClass = $isActive ? 'status-active' : 'status-disabled';
                  $statusLabel = $isActive ? 'Active' : 'Disabled';
                ?>
                <span class="user-pill <?php echo $statusClass; ?>">
                  <?php echo esc($statusLabel); ?>
                </span>
              </td>
              <td>
                <button type="button"
                        class="btn xsmall"
                        data-user-popup="user_edit.php?id=<?php echo (int)$u['id']; ?>">
                  Edit
                </button>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
    <?php endif; ?>

  </div>
</div>

<script>
  // Disable right-click & image drag
  window.addEventListener('contextmenu', e => e.preventDefault(), {passive:false});
  document.addEventListener('dragstart', e => {
    if (e.target && e.target.tagName === 'IMG') e.preventDefault();
  });

  // Handle nav buttons (no URL in status bar)
  document.addEventListener('click', function (e) {
    const btn = e.target.closest('[data-nav]');
    if (btn) {
      const href = btn.getAttribute('data-nav');
      if (!href) return;
      e.preventDefault();
      window.location.href = href;
      return;
    }

    const popupBtn = e.target.closest('[data-user-popup]');
    if (popupBtn) {
      const url = popupBtn.getAttribute('data-user-popup');
      if (!url) return;
      e.preventDefault();
      const w = 720, h = 540;
      const left = window.screenX + Math.max(0, (window.outerWidth - w) / 2);
      const top  = window.screenY + Math.max(0, (window.outerHeight - h) / 2);
      window.open(
        url,
        'TowLensUserEdit',
        'width=' + w + ',height=' + h +
        ',left=' + left + ',top=' + top +
        ',resizable=yes,scrollbars=yes'
      );
    }
  }, { passive: false });
</script>

</body>
</html>