<?php
/** Shared header, sidebar and footer for the admin panel. */

function admin_head($title) {
    ?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= h($title) ?> - <?= h(PLATFORM_NAME) ?></title>
<link rel="stylesheet" href="../assets/admin.css">
<style>
.sitechecks{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px;margin-top:8px}
.sitechecks label{display:flex;align-items:center;gap:9px;padding:11px 13px;border:1.5px solid #e3e6ea;border-radius:8px;cursor:pointer;background:#fff;font-size:14px}
.sitechecks label:hover{border-color:#9db8ff;background:#fbfcff}
.sitechecks input:checked+span{font-weight:700}
.sitechecks .dom{display:block;font-size:12px;color:#7a7f88;font-weight:400}
.pillrow{display:flex;flex-wrap:wrap;gap:5px}
.pillrow .p{background:#eef2ff;color:#33408a;font-size:11.5px;font-weight:700;padding:3px 8px;border-radius:20px;white-space:nowrap}
.pillrow .none{background:#fdecea;color:#a5251f}
.filters{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:16px}
.filters select,.filters input{padding:9px 11px;border:1.5px solid #e3e6ea;border-radius:7px;font-size:14px;font-family:inherit}
.msgbox{white-space:pre-wrap;background:#fafbfc;border:1px solid #eef0f3;border-radius:7px;padding:11px 13px;margin-top:7px;font-size:13.5px}
.unread{font-weight:800}
.muted{color:#7a7f88;font-size:12.5px}
</style>
</head>
<body>
<div class="layout">
<?php include __DIR__ . '/_nav.php'; ?>
<div class="main">
<?php
}

function admin_topbar($h1, $rightHtml = '') {
    echo '<div class="topbar"><h1>' . h($h1) . '</h1>' . $rightHtml . '</div>';
    if ($m = flash('ok'))  echo '<div class="flash">' . h($m) . '</div>';
    if ($m = flash('err')) echo '<div class="flash error">' . h($m) . '</div>';
}

function admin_foot() {
    ?>
</div>
</div>
</body>
</html>
<?php
}

/** All sites, used for checkboxes and filters. */
function all_sites() {
    static $s = null;
    if ($s === null) $s = db()->query("SELECT id, domain, company_name, is_active FROM sites ORDER BY company_name")->fetchAll();
    return $s;
}

/** The sites a vehicle is published on. */
function vehicle_site_ids($vehicleId) {
    $st = db()->prepare("SELECT site_id FROM vehicle_sites WHERE vehicle_id = ?");
    $st->execute([$vehicleId]);
    return array_map('intval', $st->fetchAll(PDO::FETCH_COLUMN));
}

/** Replace a vehicle's site links with the ticked boxes. */
function set_vehicle_sites($vehicleId, array $siteIds) {
    $valid = array_column(all_sites(), 'id');
    $siteIds = array_values(array_unique(array_intersect(array_map('intval', $siteIds), array_map('intval', $valid))));

    db()->prepare("DELETE FROM vehicle_sites WHERE vehicle_id = ?")->execute([$vehicleId]);
    if (!$siteIds) return;
    $ins = db()->prepare("INSERT INTO vehicle_sites (vehicle_id, site_id) VALUES (?, ?)");
    foreach ($siteIds as $sid) $ins->execute([$vehicleId, $sid]);
}

/** The sites a review is published on. */
function review_site_ids($reviewId) {
    $st = db()->prepare("SELECT site_id FROM review_sites WHERE review_id = ?");
    $st->execute([$reviewId]);
    return array_map('intval', $st->fetchAll(PDO::FETCH_COLUMN));
}

/** Replace a review's site links with the ticked boxes. */
function set_review_sites($reviewId, array $siteIds) {
    $valid = array_map('intval', array_column(all_sites(), 'id'));
    $siteIds = array_values(array_unique(array_intersect(array_map('intval', $siteIds), $valid)));

    db()->prepare("DELETE FROM review_sites WHERE review_id = ?")->execute([$reviewId]);
    if (!$siteIds) return;
    $ins = db()->prepare("INSERT INTO review_sites (review_id, site_id) VALUES (?, ?)");
    foreach ($siteIds as $sid) $ins->execute([$reviewId, $sid]);
}

/** Renders the "which sites" checkbox grid. $checked is an array of site ids. */
function site_checkboxes(array $checked, $name = 'sites') {
    if (!all_sites()) {
        echo '<div class="flash error" style="margin-top:12px">There are no sites yet. <a href="site_form.php">Add the first site</a>.</div>';
        return;
    }
    ?>
    <div style="display:flex;gap:10px;margin:12px 0 4px">
      <button type="button" class="btn small secondary" onclick="document.querySelectorAll('.sitechecks input').forEach(c=>c.checked=true)">Tick all</button>
      <button type="button" class="btn small secondary" onclick="document.querySelectorAll('.sitechecks input').forEach(c=>c.checked=false)">Untick all</button>
    </div>
    <div class="sitechecks">
      <?php foreach (all_sites() as $s): ?>
      <label>
        <input type="checkbox" name="<?= h($name) ?>[]" value="<?= (int)$s['id'] ?>" <?= in_array((int)$s['id'], $checked, true) ? 'checked' : '' ?>>
        <span><?= h($s['company_name']) ?>
          <span class="dom"><?= h($s['domain']) ?><?= $s['is_active'] ? '' : ' (disabled)' ?></span>
        </span>
      </label>
      <?php endforeach; ?>
    </div>
    <?php
}

/** Platform-wide unique slug (a vehicle no longer belongs to a single site). */
function unique_slug($title, $ignoreId = null) {
    $base = slugify($title);
    $slug = $base;
    for ($i = 2; $i < 500; $i++) {
        $sql = "SELECT id FROM vehicles WHERE slug = ?" . ($ignoreId ? " AND id <> ?" : "") . " LIMIT 1";
        $st  = db()->prepare($sql);
        $st->execute($ignoreId ? [$slug, $ignoreId] : [$slug]);
        if (!$st->fetch()) return $slug;
        $slug = $base . '-' . $i;
    }
    return $base . '-' . uniqid();
}
