<?php
// admin/companies.php

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'] ?? '', '/');

$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']);

if (!$isAdmin && !$isOrgAdmin) {
    http_response_code(403);
    echo 'Admins / Org admins only.';
    exit;
}

$statusFilter = $_GET['status'] ?? 'active';
$q            = trim($_GET['q'] ?? '');
$orgFilter    = isset($_GET['org']) ? (int)$_GET['org'] : 0;

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

// Build query
$where  = [];
$params = [];

// Org scoping
if ($isAdmin) {
    if ($orgFilter > 0) {
        $where[]  = "c.organisation_id = ?";
        $params[] = $orgFilter;
    }
} else {
    $where[]  = "c.organisation_id = ?";
    $params[] = $orgId;
}

// Status filter
if ($statusFilter === 'active') {
    $where[] = "c.status = 'active'";
} elseif ($statusFilter === 'disabled') {
    $where[] = "c.status <> 'active'";
}

// Search filter
if ($q !== '') {
    $like = '%' . $q . '%';
    $where[] = "(c.name LIKE ? OR c.brand_name LIKE ? OR c.slug LIKE ? OR c.support_email LIKE ?)";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

$sql = "
  SELECT
    c.id,
    c.organisation_id,
    c.name,
    c.brand_name,
    c.brand_subtitle,
    c.brand_color,
    c.logo_url,
    c.support_email,
    c.slug,
    c.status,
    c.created_at,
    o.name AS organisation_name
  FROM companies c
  LEFT JOIN organisations o ON o.id = c.organisation_id
";

if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= " ORDER BY c.created_at DESC, c.id DESC LIMIT 500";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

function esc_status_badge($status)
{
    $s = strtolower((string)$status);
    if ($s === 'active' || $s === '') {
        return '<span class="pill pill-ok">Active</span>';
    }
    return '<span class="pill pill-warn">' . esc(strtoupper($status)) . '</span>';
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TowLens Admin – Companies</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>
  /* Scrollbar */
  ::-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; }

  /* Classic theme */
  :root{
    --bg:#eceff3; --win:#ffffff; --ink:#1f2933; --muted:#5d6b78; --line:#cfd6de;
    --brand:#2f6db2; --brand-dark:#255a95; --ok:#2f7d3d; --warn:#b28a2f; --danger:#b22f2f;
    --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:1100px;
    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);}

  .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);
    transition:background .15s ease, transform .05s ease;
    font-size:12px;
  }
  .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.small{padding:4px 8px;font-size:11px;}

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

  .strip{
    background:#f6f8fb;
    border:1px solid var(--line);
    border-radius:var(--radius);
    padding:8px 10px;
    box-shadow:var(--shadow);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    margin-bottom:10px;
  }
  .meta{font-size:12px;color:var(--muted);}

  .filters{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
    align-items:flex-end;
  }
  .filters label{
    font-size:10px;
    text-transform:uppercase;
    letter-spacing:.09em;
    color:var(--muted);
    display:block;
    margin-bottom:1px;
  }
  .filters input[type="text"],
  .filters select{
    padding:5px 7px;
    border-radius:3px;
    border:1px solid #cfd6de;
    font-size:12px;
    background:#f9fafb;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.9);
    outline:none;
  }
  .filters input[type="text"]:focus,
  .filters select:focus{
    border-color:#99b4d6;
    background:#ffffff;
  }

  table{
    width:100%;
    border-collapse:separate;
    border-spacing:0;
    background:#fff;
    border:1px solid var(--line);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
  }
  th,td{
    padding:7px 9px;
    border-bottom:1px solid #e7ecf1;
    text-align:left;
    font-size:12px;
  }
  thead th{
    background:linear-gradient(#eef3f8,#e2e9f1);
    color:#2a3b4b;
    font-weight:600;
  }
  tbody tr:nth-child(even){background:#fafbfd;}
  tbody tr:hover{background:#fffde7;}

  .pill{
    display:inline-block;
    padding:2px 7px;
    border-radius:999px;
    border:1px solid #cfd6de;
    font-size:10px;
    background:#f1f3f6;
    color:#374151;
  }
  .pill-ok{
    border-color:#16a34a;
    color:#166534;
    background:#dcfce7;
  }
  .pill-warn{
    border-color:#b45309;
    color:#7c2d12;
    background:#fffbeb;
  }
  .slug{
    font-family:Consolas,Monaco,monospace;
    font-size:10px;
    color:#4b5563;
  }
  .aslink-btn{
    appearance:none;
    border:0;
    padding:0;
    margin:0;
    background:none;
    color:#2f6db2;
    text-decoration:underline;
    font-size:11px;
    cursor:pointer;
  }
  .aslink-btn:hover{text-decoration:none;}
  .logo-thumb{
    max-height:22px;
    max-width:80px;
    display:block;
  }
  .top-buttons{
    display:flex;
    gap:6px;
  }
  </style>
</head>
<body>

<div class="app">

  <!-- Ribbon with Settings + Wizard buttons (no URL preview) -->
  <div class="ribbon">
    <div class="ribbon-inner">
      <div class="title-wrap">
        <div class="wiz-icon"></div>
        <div>
          <h1>Companies</h1>
          <div class="sub">Manage TowLens client companies across your organisations.</div>
        </div>
      </div>
      <div class="top-buttons">
        <button type="button"
                class="btn small"
                data-nav="settings">
          ⬅ Back to Settings
        </button>
        <button type="button"
                class="btn primary small"
                data-nav="company_user_wizard.php">
          🧙‍♂️ New Company Wizard
        </button>
      </div>
    </div>
  </div>

  <div class="window">

    <div class="strip">
      <div class="meta">
        Showing <?php echo count($rows); ?> companies
        <?php if ($statusFilter === 'active'): ?>
          (active only)
        <?php elseif ($statusFilter === 'disabled'): ?>
          (non-active only)
        <?php else: ?>
          (all)
        <?php endif; ?>
      </div>
      <form method="get" class="filters">
        <?php if ($isAdmin): ?>
          <div>
            <label>Organisation</label>
            <select name="org">
              <option value="0">All</option>
              <?php foreach ($orgs as $o): ?>
                <option value="<?php echo (int)$o['id']; ?>"
                  <?php if ($orgFilter === (int)$o['id']) echo 'selected'; ?>>
                  <?php echo esc($o['name']); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        <?php endif; ?>

        <div>
          <label>Status</label>
          <select name="status">
            <option value="active"   <?php if ($statusFilter==='active')   echo 'selected'; ?>>Active</option>
            <option value="disabled" <?php if ($statusFilter==='disabled') echo 'selected'; ?>>Disabled</option>
            <option value="all"      <?php if ($statusFilter==='all')      echo 'selected'; ?>>All</option>
          </select>
        </div>

        <div>
          <label>Search</label>
          <input type="text" name="q"
                 value="<?php echo esc($q); ?>"
                 placeholder="Name, slug, email…">
        </div>

        <div>
          <button type="submit" class="btn small">Filter</button>
        </div>
      </form>
    </div>

    <?php if (empty($rows)): ?>
      <p class="meta">No companies found with the current filters.</p>
    <?php else: ?>
      <table>
        <thead>
          <tr>
            <th style="width:40px;">ID</th>
            <th>Company</th>
            <th>Brand</th>
            <th>Organisation</th>
            <th>Support email</th>
            <th>Slug</th>
            <th>Status</th>
            <th>Created</th>
            <th>Logo</th>
            <th style="width:70px;">Edit</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?php echo (int)$r['id']; ?></td>
            <td><?php echo esc($r['name']); ?></td>
            <td>
              <?php echo esc($r['brand_name']); ?>
              <?php if (!empty($r['brand_subtitle'])): ?>
                <div class="meta"><?php echo esc($r['brand_subtitle']); ?></div>
              <?php endif; ?>
            </td>
            <td><?php echo esc($r['organisation_name'] ?: '—'); ?></td>
            <td class="meta"><?php echo esc($r['support_email'] ?: '—'); ?></td>
            <td class="slug"><?php echo esc($r['slug']); ?></td>
            <td><?php echo esc_status_badge($r['status']); ?></td>
            <td class="meta"><?php echo esc($r['created_at']); ?></td>
            <td>
              <?php if (!empty($r['logo_url'])): ?>
                <img src="<?php echo esc($r['logo_url']); ?>" alt="" class="logo-thumb"
                     onerror="this.style.display='none'">
              <?php else: ?>
                <span class="meta">—</span>
              <?php endif; ?>
            </td>
            <td>
              <button type="button"
                      class="aslink-btn"
                      data-nav="company_edit.php?id=<?php echo (int)$r['id']; ?>">
                Edit
              </button>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>

  </div>
</div>

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

  // Data-nav buttons: navigate without showing URL on hover
  document.addEventListener('click', function (e) {
    const btn = e.target.closest('[data-nav]');
    if (!btn) return;
    const target = btn.getAttribute('data-nav');
    if (!target) return;
    e.preventDefault();
    window.location.href = target;
  }, { passive: false });
</script>

</body>
</html>
