<?php
// ═══════════════════════════════════════════════════════════════════════
//  Associate partners — CMS-managed list rendered into a drag/arrow slider.
//  Table self-creates. Public: drop <!--PARTNERS--> into a section body and
//  ea_markers() swaps in the slider. Admin: ?p=partners manages the rows.
// ═══════════════════════════════════════════════════════════════════════

/** Create the partners table once per request (memoized). Seeds the first two on creation. */
function partners_table(){
  static $ok = null;
  if ($ok !== null) return $ok;
  try {
    $existed = (bool) db()->query("SHOW TABLES LIKE 'partners'")->fetchColumn();
    db()->exec("CREATE TABLE IF NOT EXISTS partners (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(120) NOT NULL,
      logo VARCHAR(255) DEFAULT NULL,
      url VARCHAR(255) DEFAULT NULL,
      blurb VARCHAR(400) DEFAULT NULL,
      plate VARCHAR(8) NOT NULL DEFAULT 'light',
      sort INT NOT NULL DEFAULT 0,
      visible TINYINT(1) NOT NULL DEFAULT 1,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    if (!$existed) {
      $seed = db()->prepare("INSERT INTO partners(name,logo,url,blurb,plate,sort,visible) VALUES(?,?,?,?,?,?,1)");
      $seed->execute(['Zybosys','assets/brand/partner-zybosys-white.svg','https://zybosys.com',
        'Our web hosting partner. Fast, high-uptime servers with 24/7 support, plus domains and business email on Microsoft 365, Google Workspace and Zoho.','dark',1]);
      $seed->execute(['CodeCarrots','assets/brand/partner-codecarrots.png','https://codecarrots.com',
        'Our design and web engineering partner. A creative studio that shapes brand, interfaces and web products, brought in when a build needs strong design and extra hands.','dark',2]);
    }
    $ok = true;
  } catch (\Throwable $e) { $ok = false; }
  return $ok;
}

/** All partners (optionally only visible), ordered for display. */
function partners_all($visibleOnly = true){
  if (!partners_table()) return [];
  try {
    $sql = "SELECT * FROM partners" . ($visibleOnly ? " WHERE visible=1" : "") . " ORDER BY sort ASC, id ASC";
    return db()->query($sql)->fetchAll();
  } catch (\Throwable $e) { return []; }
}

/** One partner card. */
function partner_card_html($p){
  $url   = trim((string)($p['url'] ?? ''));
  $name  = e($p['name'] ?? '');
  $plate = ($p['plate'] ?? 'light') === 'dark' ? 'on-dark' : 'on-light';
  $logo  = trim((string)($p['logo'] ?? ''));
  $blurb = e($p['blurb'] ?? '');
  $href  = $url !== '' ? ' href="' . e($url) . '" target="_blank" rel="noopener"' : '';
  $tag   = $url !== '' ? 'a' : 'div';
  $mark  = $logo !== ''
    ? '<img class="p-logo ' . $plate . '" src="' . e($logo) . '" alt="' . $name . '" height="40">'
    : '<p class="co-word">' . $name . '</p>';
  $host  = $url !== '' ? preg_replace('~^https?://(www\.)?~i', '', rtrim($url, '/')) : '';
  $visit = $url !== '' ? '<span class="p-visit">Visit ' . e($host) . ' &#8594;</span>' : '';
  return "<$tag class=\"pcard\"$href>$mark<p style=\"font-size:14.5px;line-height:1.75;color:var(--ink2)\">$blurb</p>$visit</$tag>";
}

/** The full slider: a drag/arrow rail of partner cards (auto-wired by site.js .rail-wrap). */
function partners_slider_html(){
  $rows = partners_all(true);
  if (!$rows) return '';
  $cards = '';
  foreach ($rows as $p) $cards .= partner_card_html($p);
  $arrows = count($rows) > 2
    ? '<div class="rail-ui"><button class="rl-btn" data-rail="prev" type="button" aria-label="Previous partners">&#8592;</button><div class="rail-bar"><i></i></div><button class="rl-btn" data-rail="next" type="button" aria-label="More partners">&#8594;</button></div>'
    : '';
  return '<div class="rail-wrap prail rv"><div class="rail" aria-label="Associate partners">' . $cards . '</div>' . $arrows . '</div>';
}
