<?php
// ═══════════════════════════════════════════════════════════════════════
//  Hosting — CMS-managed plans + handoff to the reseller platform.
//  The store/portal are the reseller's hosted SuperSite2/OrderBox (they can't
//  be iframed and handle logins+payments), so this page SELLS on-site and
//  HANDS OFF for search, checkout and account management.
//  Markers (drop into a section body):
//    <!--HOSTINGSEARCH-->  domain search bar -> store
//    <!--HOSTINGPLANS-->   plan grid from the DB
//  Handoff URLs are Settings so the client fills the exact reseller links.
// ═══════════════════════════════════════════════════════════════════════

function hosting_store_url(){ return trim((string) setting('hosting_store_url', 'https://info775018.supersite2.myorderbox.com')); }
function hosting_portal_url(){ return trim((string) setting('hosting_portal_url', '')); }
/** Is the on-site Hosting page turned on? Off = fall back to the old external link. */
function hosting_page_enabled(){ return (string) setting('hosting_page_enabled', '1') === '1'; }
/** The old external hosting destination (expertaims.xyz) used when the page is off. */
function hosting_external_url(){ return trim((string) setting('hosting_url', 'https://expertaims.xyz')); }

/** Self-creating plans table (seeds three example tiers on first creation). */
function hosting_plans_table(){
  static $ok = null;
  if ($ok !== null) return $ok;
  try {
    $existed = (bool) db()->query("SHOW TABLES LIKE 'hosting_plans'")->fetchColumn();
    db()->exec("CREATE TABLE IF NOT EXISTS hosting_plans (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(80) NOT NULL,
      tagline VARCHAR(160) DEFAULT NULL,
      price VARCHAR(40) DEFAULT NULL,
      period VARCHAR(40) DEFAULT '/mo',
      features TEXT DEFAULT NULL,
      cta_url VARCHAR(255) DEFAULT NULL,
      cta_label VARCHAR(60) DEFAULT 'Order now',
      featured TINYINT(1) NOT NULL DEFAULT 0,
      sort INT NOT NULL DEFAULT 0,
      visible TINYINT(1) NOT NULL DEFAULT 1
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    if (!$existed) {
      $s = db()->prepare("INSERT INTO hosting_plans(name,tagline,price,period,features,cta_url,cta_label,featured,sort,visible) VALUES(?,?,?,?,?,?,?,?,?,1)");
      $s->execute(['Starter','For a first site or a small business','KWD 2','/mo',
        "1 website\n10 GB SSD storage\nFree SSL certificate\nBusiness email\n99.9% uptime\n24/7 support",'','Order now',0,1]);
      $s->execute(['Business','Room to grow, and our most popular','KWD 5','/mo',
        "10 websites\n50 GB SSD storage\nFree SSL certificate\nBusiness email\nDaily backups\nPriority 24/7 support",'','Order now',1,2]);
      $s->execute(['Pro','For busy stores and heavier sites','KWD 9','/mo',
        "Unlimited websites\n150 GB SSD storage\nFree SSL certificate\nBusiness email\nDaily backups\nStaging + priority support",'','Order now',0,3]);
    }
    $ok = true;
  } catch (\Throwable $e) { $ok = false; }
  return $ok;
}

function hosting_plans_all($visibleOnly = true){
  if (!hosting_plans_table()) return [];
  try {
    $sql = "SELECT * FROM hosting_plans" . ($visibleOnly ? " WHERE visible=1" : "") . " ORDER BY sort ASC, id ASC";
    return db()->query($sql)->fetchAll();
  } catch (\Throwable $e) { return []; }
}

/** One plan card. */
function hosting_plan_card_html($p){
  $store = hosting_store_url();
  $cta   = trim((string)($p['cta_url'] ?? '')) ?: $store;
  $feat  = ($p['featured'] ?? 0) ? ' plan-hot' : '';
  $badge = ($p['featured'] ?? 0) ? '<span class="plan-badge">Most popular</span>' : '';
  $items = '';
  foreach (preg_split('/\r\n|\r|\n/', (string)($p['features'] ?? '')) as $f) {
    $f = trim($f); if ($f !== '') $items .= '<li>' . e($f) . '</li>';
  }
  $label = e($p['cta_label'] ?? 'Order now') ?: 'Order now';
  return '<div class="plan' . $feat . '">' . $badge
    . '<h3 class="plan-name">' . e($p['name']) . '</h3>'
    . '<p class="plan-tag">' . e($p['tagline'] ?? '') . '</p>'
    . '<p class="plan-price"><b>' . e($p['price'] ?? '') . '</b><span>' . e($p['period'] ?? '') . '</span></p>'
    . '<ul class="plan-feats">' . $items . '</ul>'
    . '<a class="btn ' . (($p['featured'] ?? 0) ? 'btn-acc' : 'btn-ln') . ' plan-cta" href="' . e($cta) . '" target="_blank" rel="noopener">' . $label . '</a>'
    . '</div>';
}

/** The plan grid (marker output). */
function hosting_plans_grid_html(){
  $rows = hosting_plans_all(true);
  if (!$rows) return '';
  $cards = '';
  foreach ($rows as $p) $cards .= hosting_plan_card_html($p);
  return '<div class="plans rv">' . $cards . '</div>';
}

/** Client-area buttons (marker output): login to the reseller portal + talk to us. */
function hosting_portal_html(){
  $portal = hosting_portal_url();
  $out = '';
  if ($portal !== '') {
    $out .= '<a class="btn btn-acc" href="' . e($portal) . '" target="_blank" rel="noopener">Client login &#8594;</a>';
    $out .= '<a class="btn btn-ln" href="' . base_url('contact') . '" style="color:#F0EDE8;box-shadow:inset 0 0 0 1.5px #3C3434">Talk to us</a>';
  } else {
    $out .= '<a class="btn btn-acc" href="' . base_url('contact') . '">Talk to us about hosting</a>';
  }
  return $out;
}

/** Homepage teaser band (marker output). Empty when the page is turned off. */
function hosting_teaser_html(){
  if (!hosting_page_enabled()) return '';
  return '<section class="sec"><div class="wrap"><div class="host-teaser rv">'
    . '<div class="ht-copy"><p class="stn">Web hosting <i>&#183;</i> by ExpertAims</p>'
    . '<h2 class="d2" style="margin-top:10px">Need somewhere reliable to host it?</h2>'
    . '<p class="lede" style="margin-top:12px;max-width:52ch">Fast, secure hosting with domains and business email, set up and looked after by the same team that builds your site.</p></div>'
    . '<a class="btn btn-acc" href="' . base_url('hosting') . '">See hosting plans &#8594;</a>'
    . '</div></div></section>';
}

/** Domain search bar that hands off to the store (marker output). */
function hosting_search_html(){
  $store = e(hosting_store_url());
  return '<form class="dsearch rv" action="' . $store . '" method="get" target="_blank" rel="noopener">'
    . '<input type="text" name="domain-name" placeholder="Find your domain name, e.g. yourbusiness.com" aria-label="Search for a domain">'
    . '<button class="btn btn-acc" type="submit">Search</button>'
    . '</form>';
}
