<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Store_theme_scaffolder
 *
 * Generates a SIMPLE, fully-functional SSR starter theme (Store API v1).
 * Philosophy: pure PHP + Bootstrap 5, zero AJAX, zero Mustache — it just works.
 * Developers who want advanced behaviour (AJAX, infinite scroll, etc.) can
 * upgrade individual view files using the full API contract.
 *
 * Views generated:
 *   layout.php, home.php, category.php, product.php, cart.php,
 *   checkout.php, checkout_onepage.php, checkout_confirm.php,
 *   checkout_cart.php, checkout_shipping.php, checkout_thankyou.php,
 *   checkount-without-pyament.php, login.php, profile.php, order_list.php,
 *   view_order.php, track_order.php, shipping.php, my_courses.php,
 *   wishlist.php, about.php, contact.php, policy.php, cookies_consent.php,
 *   mini_cart.php, payment_methods.php, product_list.php, custom_page.php,
 *   vendor_store.php, _account_header.php, lms/template-1.php,
 *   thanks.php, view_order_details.php
 *   + assets/store/{id}/css/theme.css, assets/store/{id}/js/theme.js
 */
class Store_theme_scaffolder {

	public function scaffold($id, $name, $desc, $author, $gradient = '')
	{
		$ph  = ['{THEME_ID}', '{THEME_NAME}', '{THEME_DESC}', '{THEME_AUTHOR}', '{YEAR}'];
		$val = [$id, addslashes($name), addslashes($desc), addslashes($author), date('Y')];
		$r   = function($tpl) use ($ph, $val) { return str_replace($ph, $val, $tpl); };
		$f   = [];

		$safe_gradient = !empty($gradient) ? $gradient : 'linear-gradient(135deg,#1e293b 0%,#3b82f6 100%)';

		/* ── theme.json ─────────────────────────────────────────────────── */
		$f['theme.json'] = json_encode([
			'_readme'     => 'Auto-generated by Store Theme Scaffolder. Safe to edit.',
			'id'          => $id,
			'name'        => $name,
			'description' => $desc,
			'author'      => $author,
			'mode'        => 'cart',
			'api_version' => 'v1',
			'sort'        => 10,
			'tags'        => ['Bootstrap 5', 'Simple', 'SSR', 'API v1'],
			'preview'     => [
				'gradient' => $safe_gradient,
				'emoji'    => '🛍',
				'label'    => $name,
			],
		], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

		/* ── layout.php ─────────────────────────────────────────────────── */
		$f['layout.php'] = $r(<<<'PHP'
<?php
/**
 * {THEME_NAME} — Main Layout
 * GLOBALS (injected by Storeapp::view()):
 *   $store_setting, $client, $home_link, $base_url, $store_currency,
 *   $category_tree, $LanguageHtml, $CurrencyHtml, $googlerecaptcha
 */
$_logo         = $store_setting['store_logo_upload'] ?? '';
$_name         = $store_setting['store_name'] ?? '{THEME_NAME}';
$_rtl          = ($store_setting['store_lang_direction'] ?? 'ltr') === 'rtl';
$_cats         = $category_tree ?? [];
$currency_sign = $store_currency ?? ($store_setting['currency_sign'] ?? '$');
$_logged       = !empty($client['id']);
$_cart_count   = isset($cart_count) ? (int)$cart_count : 0;
?><!DOCTYPE html>
<html lang="<?= $store_setting['store_lang'] ?? 'en' ?>" dir="<?= $_rtl ? 'rtl' : 'ltr' ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars($meta_title ?? $_name) ?></title>
<?php if (!empty($canonical_url)): ?><link rel="canonical" href="<?= $canonical_url ?>"><?php endif; ?>
<link rel="stylesheet" href="<?= base_url('assets/template/css/bootstrap.min.css') ?>?v=<?= av() ?>">
<link rel="stylesheet" href="<?= base_url('assets/template/css/bootstrap-icons.css') ?>">
<script src="<?= base_url('assets/store/shared/js/jquery.min.js') ?>"></script>
<script>
/* Bootstrap 3/4 $.fn.btn("loading"|"reset") polyfill — required by payment gateway views */
(function($){
  $.fn.btn = function(state){
    return this.each(function(){
      var $el = $(this);
      if(state === 'loading'){
        $el.data('btn-original', $el.html())
           .prop('disabled', true)
           .html('<span class="spinner-border spinner-border-sm me-1" role="status"></span>');
      } else if(state === 'reset'){
        $el.prop('disabled', false)
           .html($el.data('btn-original') || $el.html());
      }
    });
  };
})(jQuery);
</script>
<style>
:root{--theme-primary:#3b82f6;--theme-dark:#1e293b;}
html,body{height:100%;}
body{display:flex;flex-direction:column;min-height:100vh;}
main{flex:1 0 auto;}
footer{flex-shrink:0;background:var(--theme-dark);color:#cbd5e1;}
.navbar{background:var(--theme-dark)!important;}
.btn-primary{background:var(--theme-primary);border-color:var(--theme-primary);}
.card:hover{box-shadow:0 4px 16px rgba(0,0,0,.12);transition:.2s;}
.product-img{height:200px;object-fit:cover;width:100%;}
/* ── Language / Currency switcher (js-link / js-dropdown-list) ── */
.tss-sw-wrap{display:inline-flex;align-items:center;}
.tss-sw-wrap .js-link,
.tss-sw-wrap .js-link1{color:#fff!important;display:flex;align-items:center;gap:4px;cursor:pointer;padding:4px 6px;border-radius:4px;font-size:.8rem;white-space:nowrap;}
.tss-sw-wrap .js-link:hover,
.tss-sw-wrap .js-link1:hover{background:rgba(255,255,255,.15);}
.tss-sw-wrap .js-dropdown-list,
.tss-sw-wrap .js-dropdown-list1{display:none;position:absolute;top:calc(100% + 4px);right:0;background:#fff;border:1px solid #dee2e6;border-radius:6px;box-shadow:0 4px 16px rgba(0,0,0,.12);list-style:none;padding:4px 0;margin:0;min-width:140px;z-index:9999;}
.tss-sw-wrap .js-dropdown-list li,
.tss-sw-wrap .js-dropdown-list1 li{display:block;}
.tss-sw-wrap .js-dropdown-list a,
.tss-sw-wrap .js-dropdown-list1 a{display:flex;align-items:center;gap:8px;padding:7px 14px;color:#212529;font-size:.85rem;white-space:nowrap;text-decoration:none;}
.tss-sw-wrap .js-dropdown-list a:hover,
.tss-sw-wrap .js-dropdown-list1 a:hover{background:#f8f9fa;}
.tss-sw-wrap.open .js-dropdown-list,
.tss-sw-wrap.open .js-dropdown-list1{display:block;}
/* currency: nav-link variant */
.tss-sw-wrap a.nav-link{color:#fff!important;padding:2px 4px;}
.tss-sw-wrap #language-dropdown,
.tss-sw-wrap #currency-dropdown{position:absolute!important;top:calc(100% + 4px)!important;right:0!important;left:auto!important;display:none!important;z-index:9999;}
.tss-sw-wrap.open #language-dropdown,
.tss-sw-wrap.open #currency-dropdown{display:block!important;}
</style>
</head>
<body class="bg-light">

<!-- NAVBAR -->
<nav class="navbar navbar-expand-lg navbar-dark sticky-top shadow-sm">
  <div class="container">
    <a class="navbar-brand fw-bold text-white" href="<?= $home_link ?>">
      <?php if (!empty($_logo)): ?>
        <img src="<?= base_url('assets/images/site/' . $_logo) ?>" height="36" alt="<?= htmlspecialchars($_name) ?>">
      <?php else: ?>
        <?= htmlspecialchars($_name) ?>
      <?php endif; ?>
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navMain">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navMain">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item"><a class="nav-link text-white" href="<?= base_url('store/category') ?>"><?= __('store.products') ?></a></li>
        <?php if (!empty($_cats)): ?>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle text-white" href="#" data-bs-toggle="dropdown"><?= __('store.categories') ?></a>
          <ul class="dropdown-menu">
            <?php foreach ($_cats as $_c): ?>
            <li><a class="dropdown-item" href="<?= base_url('store/category/' . ($_c['slug'] ?? '')) ?>"><?= htmlspecialchars($_c['name'] ?? '') ?></a></li>
            <?php endforeach; ?>
          </ul>
        </li>
        <?php endif; ?>
        <li class="nav-item"><a class="nav-link text-white" href="<?= base_url('store/about') ?>"><?= __('store.about') ?></a></li>
        <li class="nav-item"><a class="nav-link text-white" href="<?= base_url('store/contact') ?>"><?= __('store.contact_us') ?></a></li>
      </ul>
      <div class="d-flex align-items-center gap-2">
        <?php if (!empty($LanguageHtml)): ?>
          <div class="tss-sw-wrap position-relative"><?= $LanguageHtml ?></div>
        <?php endif; ?>
        <?php if (!empty($CurrencyHtml)): ?>
          <div class="tss-sw-wrap position-relative"><?= $CurrencyHtml ?></div>
        <?php endif; ?>
        <a href="<?= base_url('store/cart') ?>" class="btn btn-outline-light btn-sm position-relative">
          <i class="bi bi-cart3"></i>
          <?php if ($_cart_count > 0): ?>
            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"><?= $_cart_count ?></span>
          <?php endif; ?>
        </a>
        <?php if ($_logged): ?>
          <div class="dropdown">
            <button class="btn btn-outline-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
              <i class="bi bi-person-circle"></i> <?= htmlspecialchars(($client['firstname'] ?? '') . ' ' . ($client['lastname'] ?? '')) ?>
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item" href="<?= base_url('store/profile') ?>"><i class="bi bi-person me-2"></i><?= __('store.my_profile') ?></a></li>
              <li><a class="dropdown-item" href="<?= base_url('store/order') ?>"><i class="bi bi-bag me-2"></i><?= __('store.my_orders') ?></a></li>
              <li><a class="dropdown-item" href="<?= base_url('store/wishlist') ?>"><i class="bi bi-heart me-2"></i><?= __('store.wishlist') ?></a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item text-danger" href="<?= base_url('store/logout') ?>"><i class="bi bi-box-arrow-right me-2"></i><?= __('store.logout') ?></a></li>
            </ul>
          </div>
        <?php else: ?>
          <a href="<?= base_url('store/login') ?>" class="btn btn-primary btn-sm"><?= __('store.login') ?></a>
        <?php endif; ?>
      </div>
    </div>
  </div>
</nav>

<!-- PAGE CONTENT -->
<main class="py-4">
  <div class="container">
    <?= $content ?>
  </div>
</main>

<!-- FOOTER -->
<footer class="py-4 mt-4">
  <div class="container text-center">
    <p class="mb-1 small">&copy; {YEAR} <?= htmlspecialchars($_name) ?>. <?= __('store.all_rights_reserved') ?></p>
    <div class="small">
      <a href="<?= base_url('store/about') ?>" class="text-secondary me-3"><?= __('store.about') ?></a>
      <a href="<?= base_url('store/contact') ?>" class="text-secondary me-3"><?= __('store.contact_us') ?></a>
      <a href="<?= base_url('store/policy') ?>" class="text-secondary"><?= __('store.policy') ?></a>
    </div>
  </div>
</footer>

<script src="<?= base_url('assets/template/js/bootstrap.bundle.min.js') ?>?v=<?= av() ?>"></script>
<script>
/* Global JS config — used by theme.js */
var tssBase     = '<?= rtrim(base_url(), '/') . '/' ?>';
var tssRedirect = '<?= addslashes($redirect_url ?? '') ?>';
</script>
<script src="<?= base_url('assets/store/{THEME_ID}/js/theme.js') ?>?v=<?= av() ?>"></script>
</body>
</html>
PHP);

		/* ── home.php ────────────────────────────────────────────────────── */
		$f['home.php'] = $r(<<<'PHP'
<?php
/**
 * Home page — Store API v1 :: page_home()
 * VARIABLES: $new_products, $best_sellers, $category (root categories),
 *            $product_ratings, $store_setting
 */
$_sliders = [];
if (!empty($store_setting['homepage_slider'])) {
    $_raw = json_decode($store_setting['homepage_slider'], true);
    if (is_array($_raw)) $_sliders = $_raw;
}
?>

<?php if (!empty($_sliders)): ?>
<div id="heroCarousel" class="carousel slide mb-5" data-bs-ride="carousel">
  <div class="carousel-inner rounded-3 overflow-hidden shadow">
    <?php foreach ($_sliders as $_i => $_sl):
      $_sl = (array)$_sl;
      $_bg = !empty($_sl['slider_background_image']) ? base_url('assets/images/site/' . $_sl['slider_background_image']) : '';
    ?>
    <div class="carousel-item <?= $_i === 0 ? 'active' : '' ?>">
      <div class="d-flex align-items-center justify-content-center text-center text-white py-5"
           style="min-height:340px;background:var(--theme-dark,#1e293b);<?= $_bg ? "background-image:url('{$_bg}');background-size:cover;background-position:center;" : '' ?>">
        <div>
          <?php if (!empty($_sl['title'])): ?><h1 class="fw-bold display-5 mb-2"><?= htmlspecialchars($_sl['title']) ?></h1><?php endif; ?>
          <?php if (!empty($_sl['sub_title'])): ?><p class="lead mb-4"><?= htmlspecialchars($_sl['sub_title']) ?></p><?php endif; ?>
          <a href="<?= !empty($_sl['button_link']) ? htmlspecialchars($_sl['button_link']) : base_url('store/category') ?>" class="btn btn-primary btn-lg px-4">
            <?= !empty($_sl['button_text']) ? htmlspecialchars($_sl['button_text']) : __('store.browse_products') ?>
          </a>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <button class="carousel-control-prev" type="button" data-bs-target="#heroCarousel" data-bs-slide="prev"><span class="carousel-control-prev-icon"></span></button>
  <button class="carousel-control-next" type="button" data-bs-target="#heroCarousel" data-bs-slide="next"><span class="carousel-control-next-icon"></span></button>
</div>
<?php else: ?>
<div class="rounded-3 text-white text-center p-5 mb-5" style="background:var(--theme-dark,#1e293b);">
  <h1 class="fw-bold display-5 mb-3"><?= htmlspecialchars($store_setting['store_name'] ?? '') ?></h1>
  <?php if (!empty($store_setting['store_description'])): ?>
    <p class="lead mb-4 opacity-75"><?= htmlspecialchars($store_setting['store_description']) ?></p>
  <?php endif; ?>
  <a href="<?= base_url('store/category') ?>" class="btn btn-light btn-lg px-4"><?= __('store.browse_products') ?></a>
</div>
<?php endif; ?>

<?php if (!empty($category)): ?>
<h4 class="fw-bold mb-3"><?= __('store.categories') ?></h4>
<div class="row g-3 mb-5">
  <?php foreach ($category as $_cat): ?>
  <div class="col-6 col-md-3">
    <a href="<?= base_url('store/category/' . ($_cat['slug'] ?? '')) ?>" class="text-decoration-none">
      <div class="card border-0 shadow-sm text-center p-3 h-100">
        <?php if (!empty($_cat['image'])): ?>
          <img src="<?= base_url('assets/images/product/upload/thumb/' . $_cat['image']) ?>" class="rounded-circle mx-auto mb-2" style="width:60px;height:60px;object-fit:cover;" alt="">
        <?php else: ?>
          <div class="rounded-circle bg-primary bg-opacity-10 mx-auto mb-2 d-flex align-items-center justify-content-center" style="width:60px;height:60px;">
            <i class="bi bi-grid text-primary fs-4"></i>
          </div>
        <?php endif; ?>
        <div class="fw-semibold small"><?= htmlspecialchars($_cat['name']) ?></div>
      </div>
    </a>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<?php if (!empty($new_products)): ?>
<h4 class="fw-bold mb-3"><?= __('store.new_arrivals') ?></h4>
<div class="row g-3 mb-5">
  <?php foreach ($new_products as $_p):
    $_img  = !empty($_p['product_featured_image']) ? base_url('assets/images/product/upload/thumb/' . $_p['product_featured_image']) : base_url('assets/images/no_image_available.png');
    $_url  = base_url('store/product/' . $_p['product_slug']);
    $_rat  = $product_ratings[$_p['product_id']]['avg_star'] ?? 0;
  ?>
  <div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm h-100">
      <a href="<?= $_url ?>"><img src="<?= $_img ?>" class="product-img card-img-top" alt="<?= htmlspecialchars($_p['product_name']) ?>" onerror="this.src='<?= base_url('assets/images/no_image_available.png') ?>'"></a>
      <div class="card-body d-flex flex-column">
        <a href="<?= $_url ?>" class="text-dark fw-semibold small text-decoration-none flex-grow-1"><?= htmlspecialchars($_p['product_name']) ?></a>
        <?php if ($_rat > 0): ?>
          <div class="text-warning small my-1"><?= str_repeat('★', round($_rat)) ?><?= str_repeat('☆', 5 - round($_rat)) ?></div>
        <?php endif; ?>
        <div class="fw-bold text-primary"><?= $currency_sign ?><?= number_format($_p['product_price'], 2) ?></div>
      </div>
      <div class="card-footer border-0 bg-transparent pt-0">
        <a href="<?= $_url ?>" class="btn btn-primary btn-sm w-100"><?= __('store.view') ?></a>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<?php if (!empty($best_sellers)): ?>
<h4 class="fw-bold mb-3"><?= __('store.best_sellers') ?></h4>
<div class="row g-3 mb-4">
  <?php foreach ($best_sellers as $_p):
    $_img = !empty($_p['product_featured_image']) ? base_url('assets/images/product/upload/thumb/' . $_p['product_featured_image']) : base_url('assets/images/no_image_available.png');
    $_url = base_url('store/product/' . $_p['product_slug']);
  ?>
  <div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #f59e0b!important;">
      <a href="<?= $_url ?>"><img src="<?= $_img ?>" class="product-img card-img-top" alt="<?= htmlspecialchars($_p['product_name']) ?>" onerror="this.src='<?= base_url('assets/images/no_image_available.png') ?>'"></a>
      <div class="card-body d-flex flex-column">
        <a href="<?= $_url ?>" class="text-dark fw-semibold small text-decoration-none flex-grow-1"><?= htmlspecialchars($_p['product_name']) ?></a>
        <div class="fw-bold text-primary"><?= $currency_sign ?><?= number_format($_p['product_price'], 2) ?></div>
      </div>
      <div class="card-footer border-0 bg-transparent pt-0">
        <a href="<?= $_url ?>" class="btn btn-warning btn-sm w-100 text-dark"><?= __('store.view') ?></a>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>
PHP);

		/* ── category.php ────────────────────────────────────────────────── */
		// Pure SSR — uses $products, $products_total, $products_page from page_category()
		$f['category.php'] = $r(<<<'PHP'
<?php
/**
 * Category / Product listing — Store API v1 :: page_category()
 * SSR variables: $products, $products_total, $products_page, $products_per_page,
 *                $products_search, $products_sort, $category, $category_tree
 * Pagination via GET: ?p=2&search=...&sort=newest
 */
$_cat_name    = !empty($category['name']) ? $category['name'] : __('store.all_products');
$_cat_slug    = $category['slug'] ?? '';
$_total       = (int)($products_total ?? 0);
$_page        = (int)($products_page ?? 1);
$_per_page    = (int)($products_per_page ?? 12);
$_pages       = $_per_page > 0 ? max(1, (int)ceil($_total / $_per_page)) : 1;
$_search      = htmlspecialchars($products_search ?? '');
$_sort        = $products_sort ?? 'newest';
$_base_url    = base_url('store/category' . (!empty($_cat_slug) ? '/' . $_cat_slug : ''));
?>

<nav aria-label="breadcrumb" class="mb-3">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="<?= $home_link ?>"><?= __('store.home') ?></a></li>
    <li class="breadcrumb-item"><a href="<?= base_url('store/category') ?>"><?= __('store.categories') ?></a></li>
    <?php if (!empty($_cat_slug)): ?>
      <li class="breadcrumb-item active"><?= htmlspecialchars($_cat_name) ?></li>
    <?php endif; ?>
  </ol>
</nav>

<div class="row g-4">

  <!-- Sidebar -->
  <div class="col-lg-3">

    <!-- Filter form -->
    <form method="get" action="<?= $_base_url ?>">
      <div class="card border-0 shadow-sm mb-3">
        <div class="card-header fw-semibold small"><?= __('store.categories') ?></div>
        <div class="list-group list-group-flush">
          <a href="<?= base_url('store/category') ?>" class="list-group-item list-group-item-action small <?= empty($_cat_slug) ? 'active' : '' ?>"><?= __('store.all_products') ?></a>
          <?php foreach ($category_tree as $_tc): ?>
          <a href="<?= base_url('store/category/' . ($_tc['slug'] ?? '')) ?>" class="list-group-item list-group-item-action small <?= $_cat_slug === ($_tc['slug'] ?? '') ? 'active' : '' ?>"><?= htmlspecialchars($_tc['name']) ?></a>
          <?php if (!empty($_tc['children'])): ?>
            <?php foreach ($_tc['children'] as $_ch): ?>
            <a href="<?= base_url('store/category/' . ($_ch['slug'] ?? '')) ?>" class="list-group-item list-group-item-action small ps-4 text-muted"><?= htmlspecialchars($_ch['name']) ?></a>
            <?php endforeach; ?>
          <?php endif; ?>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="card border-0 shadow-sm mb-3 p-3">
        <label class="form-label small fw-semibold"><?= __('store.search') ?></label>
        <input type="text" name="search" class="form-control form-control-sm" value="<?= $_search ?>" placeholder="<?= __('store.search') ?>…">
        <label class="form-label small fw-semibold mt-2"><?= __('store.sort_by') ?></label>
        <select name="sort" class="form-select form-select-sm">
          <option value="newest" <?= $_sort === 'newest' ? 'selected' : '' ?>><?= __('store.newest') ?></option>
          <option value="popular" <?= $_sort === 'popular' ? 'selected' : '' ?>><?= __('store.popular') ?></option>
          <option value="price_asc" <?= $_sort === 'price_asc' ? 'selected' : '' ?>><?= __('store.low_to_high') ?></option>
          <option value="price_desc" <?= $_sort === 'price_desc' ? 'selected' : '' ?>><?= __('store.high_to_low') ?></option>
        </select>
        <button type="submit" class="btn btn-primary btn-sm mt-2 w-100"><?= __('store.filter') ?></button>
        <?php if (!empty($_search) || $_sort !== 'newest'): ?>
          <a href="<?= $_base_url ?>" class="btn btn-outline-secondary btn-sm mt-1 w-100"><?= __('store.clear') ?></a>
        <?php endif; ?>
      </div>
    </form>

  </div><!-- /sidebar -->

  <!-- Product grid -->
  <div class="col-lg-9">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h5 class="fw-bold mb-0"><?= htmlspecialchars($_cat_name) ?></h5>
      <small class="text-muted"><?= __('store.showing') ?> <?= $_total ?> <?= __('store.results') ?></small>
    </div>

    <?php if (!empty($products)): ?>
    <div class="row g-3">
      <?php foreach ($products as $_p):
        $_img = !empty($_p['product_featured_image']) ? base_url('assets/images/product/upload/thumb/' . $_p['product_featured_image']) : base_url('assets/images/no_image_available.png');
        $_url = base_url('store/product/' . $_p['product_slug']);
      ?>
      <div class="col-6 col-md-4 col-lg-4">
        <div class="card border-0 shadow-sm h-100">
          <a href="<?= $_url ?>"><img src="<?= $_img ?>" class="product-img card-img-top" alt="<?= htmlspecialchars($_p['product_name']) ?>" onerror="this.src='<?= base_url('assets/images/no_image_available.png') ?>'"></a>
          <div class="card-body d-flex flex-column">
            <a href="<?= $_url ?>" class="text-dark fw-semibold small text-decoration-none flex-grow-1"><?= htmlspecialchars($_p['product_name']) ?></a>
            <div class="fw-bold text-primary mt-1"><?= $currency_sign ?><?= number_format($_p['product_price'], 2) ?></div>
          </div>
          <div class="card-footer border-0 bg-transparent pt-0">
            <a href="<?= $_url ?>" class="btn btn-primary btn-sm w-100"><?= __('store.view') ?></a>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

    <?php if ($_pages > 1): ?>
    <nav class="mt-4">
      <ul class="pagination justify-content-center">
        <?php if ($_page > 1): ?>
          <li class="page-item"><a class="page-link" href="<?= $_base_url ?>?p=<?= $_page - 1 ?>&search=<?= urlencode($products_search ?? '') ?>&sort=<?= $_sort ?>">&laquo;</a></li>
        <?php endif; ?>
        <?php for ($_pg = 1; $_pg <= $_pages; $_pg++): ?>
          <li class="page-item <?= $_pg === $_page ? 'active' : '' ?>">
            <a class="page-link" href="<?= $_base_url ?>?p=<?= $_pg ?>&search=<?= urlencode($products_search ?? '') ?>&sort=<?= $_sort ?>"><?= $_pg ?></a>
          </li>
        <?php endfor; ?>
        <?php if ($_page < $_pages): ?>
          <li class="page-item"><a class="page-link" href="<?= $_base_url ?>?p=<?= $_page + 1 ?>&search=<?= urlencode($products_search ?? '') ?>&sort=<?= $_sort ?>">&raquo;</a></li>
        <?php endif; ?>
      </ul>
    </nav>
    <?php endif; ?>

    <?php else: ?>
    <div class="text-center py-5 text-muted">
      <i class="bi bi-search display-4 d-block mb-3"></i>
      <p><?= __('store.no_products_desc') ?></p>
      <a href="<?= $_base_url ?>" class="btn btn-outline-primary btn-sm"><?= __('store.clear') ?></a>
    </div>
    <?php endif; ?>

  </div><!-- /product grid -->
</div>
PHP);

		/* ── product.php ─────────────────────────────────────────────────── */
		$f['product.php'] = $r(<<<'PHP'
<?php
/**
 * Product detail page — Store API v1 :: page_product_summary()
 * VARIABLES: $product (array), $all_images (array), $review_list (array),
 *            $related_products (array), $add_tocart_url, $is_wishlisted_class,
 *            $is_logged, $store_setting, $client
 *
 * Wishlist: AJAX POST store/toggle_wishlist — field: product_id — returns plain "1"
 *   $is_wishlisted_class = 'w-listed' if in wishlist, '' otherwise
 */
$_p        = $product ?? [];
$_name     = htmlspecialchars($_p['product_name'] ?? '');
$_price    = number_format($_p['product_price'] ?? 0, 2);
$_msrp     = !empty($_p['product_msrp']) ? number_format($_p['product_msrp'], 2) : '';
$_desc     = $_p['product_description'] ?? '';
$_short    = htmlspecialchars($_p['product_short_description'] ?? '');
$_qty      = (int)($_p['product_quantity'] ?? 0);
$_in_stock = ($_p['product_type'] ?? '') === 'digital' || $_qty > 0 || $_qty === -1;
$_slug     = $_p['product_slug'] ?? '';
$_imgs     = $all_images ?? [];
$_reviews  = $review_list ?? [];
$_related  = $related_products ?? [];
$_pid      = (int)($_p['product_id'] ?? 0);
$_wished   = ($is_wishlisted_class ?? '') === 'w-listed';
$_wl_url   = base_url('store/toggle_wishlist');
$_logged   = !empty($client['id']);
?>

<nav aria-label="breadcrumb" class="mb-3">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="<?= $home_link ?>"><?= __('store.home') ?></a></li>
    <li class="breadcrumb-item"><a href="<?= base_url('store/category') ?>"><?= __('store.products') ?></a></li>
    <li class="breadcrumb-item active"><?= $_name ?></li>
  </ol>
</nav>

<div class="row g-4 mb-5">
  <!-- Images -->
  <div class="col-md-5">
    <?php if (!empty($_imgs)): ?>
    <div id="productCarousel" class="carousel slide shadow-sm rounded overflow-hidden" data-bs-ride="false">
      <div class="carousel-inner">
        <?php foreach ($_imgs as $_i => $_img):
          $_src = !empty($_img['product_media_upload_path']) ? base_url('assets/images/product/upload/' . $_img['product_media_upload_path']) : base_url('assets/images/no_image_available.png');
        ?>
        <div class="carousel-item <?= $_i === 0 ? 'active' : '' ?>">
          <img src="<?= $_src ?>" class="d-block w-100" style="height:380px;object-fit:contain;background:#fff;" alt="<?= $_name ?>">
        </div>
        <?php endforeach; ?>
      </div>
      <?php if (count($_imgs) > 1): ?>
        <button class="carousel-control-prev" type="button" data-bs-target="#productCarousel" data-bs-slide="prev"><span class="carousel-control-prev-icon" style="filter:invert(1)"></span></button>
        <button class="carousel-control-next" type="button" data-bs-target="#productCarousel" data-bs-slide="next"><span class="carousel-control-next-icon" style="filter:invert(1)"></span></button>
      <?php endif; ?>
    </div>
    <?php else: ?>
    <div class="bg-white rounded shadow-sm d-flex align-items-center justify-content-center" style="height:380px;">
      <i class="bi bi-image text-muted" style="font-size:4rem;"></i>
    </div>
    <?php endif; ?>
  </div>

  <!-- Info -->
  <div class="col-md-7">
    <h1 class="h3 fw-bold"><?= $_name ?></h1>
    <?php if ($_short): ?><p class="text-muted"><?= $_short ?></p><?php endif; ?>

    <div class="d-flex align-items-baseline gap-3 mb-3">
      <span class="fs-4 fw-bold text-primary"><?= $currency_sign ?><?= $_price ?></span>
      <?php if ($_msrp): ?><s class="text-muted"><?= $currency_sign ?><?= $_msrp ?></s><?php endif; ?>
    </div>

    <?php if ($_in_stock): ?>
      <span class="badge bg-success mb-3"><i class="bi bi-check-circle me-1"></i><?= __('store.in_stock') ?></span>
    <?php else: ?>
      <span class="badge bg-danger mb-3"><?= __('store.out_of_stock') ?></span>
    <?php endif; ?>

    <?php if ($_in_stock): ?>
    <div class="mb-3">
      <div class="d-flex gap-2 align-items-center mb-3">
        <label class="form-label mb-0 fw-semibold small"><?= __('store.quantity') ?></label>
        <input type="number" id="tss-qty" value="1" min="1" <?= $_qty > 0 ? 'max="' . $_qty . '"' : '' ?> class="form-control form-control-sm" style="width:80px;">
      </div>
      <div class="d-flex gap-2">
        <button type="button" class="btn btn-primary tss-add-to-cart"
                data-product-id="<?= $_pid ?>"
                data-cart-url="<?= $add_tocart_url ?>">
          <i class="bi bi-cart-plus me-1"></i><?= __('store.add_to_cart') ?>
        </button>
        <?php if ($_logged): ?>
        <button type="button" id="tss-wishlist-btn"
                class="btn <?= $_wished ? 'btn-danger' : 'btn-outline-secondary' ?>"
                title="<?= $_wished ? __('store.remove_from_wishlist') : __('store.add_to_wishlist') ?>"
                data-product-id="<?= $_pid ?>"
                data-wishlist-url="<?= $_wl_url ?>">
          <i class="bi <?= $_wished ? 'bi-heart-fill' : 'bi-heart' ?>"></i>
        </button>
        <?php else: ?>
        <a href="<?= base_url('store/login') ?>" class="btn btn-outline-secondary" title="<?= __('store.add_to_wishlist') ?>">
          <i class="bi bi-heart"></i>
        </a>
        <?php endif; ?>
      </div>
      <div id="tss-cart-msg" class="mt-2" style="display:none;"></div>
    </div>
    <?php endif; ?>

    <?php if (!empty($_desc)): ?>
    <hr>
    <h6 class="fw-semibold"><?= __('store.description') ?></h6>
    <div class="text-muted small"><?= $_desc ?></div>
    <?php endif; ?>
  </div>
</div>

<!-- Wishlist toggle -->
<?php if ($_logged): ?>
<script>
(function($){
  $('#tss-wishlist-btn').on('click', function(){
    var $btn = $(this);
    $btn.prop('disabled', true);
    $.post($btn.data('wishlist-url'), { product_id: $btn.data('product-id') }, function(){
      var on = $btn.hasClass('btn-danger');
      $btn.toggleClass('btn-danger', !on).toggleClass('btn-outline-secondary', on)
          .attr('title', on ? '<?= __("store.add_to_wishlist") ?>' : '<?= __("store.remove_from_wishlist") ?>')
          .find('i').toggleClass('bi-heart-fill', !on).toggleClass('bi-heart', on);
    }).fail(function(){ alert('<?= __("store.error") ?>'); })
      .always(function(){ $btn.prop('disabled', false); });
  });
})(jQuery);
</script>
<?php endif; ?>

<!-- Reviews -->
<?php if (!empty($_reviews)): ?>
<h5 class="fw-bold mb-3"><?= __('store.reviews') ?></h5>
<div class="row g-3 mb-5">
  <?php foreach ($_reviews as $_rv): ?>
  <div class="col-12">
    <div class="card border-0 shadow-sm p-3">
      <div class="d-flex justify-content-between mb-1">
        <strong class="small"><?= htmlspecialchars($_rv['rating_name'] ?? '') ?></strong>
        <div class="text-warning small"><?= str_repeat('★', (int)($_rv['rating_number'] ?? 0)) ?></div>
      </div>
      <p class="mb-0 small text-muted"><?= htmlspecialchars($_rv['rating_review'] ?? '') ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Related products -->
<?php if (!empty($_related)): ?>
<h5 class="fw-bold mb-3"><?= __('store.related_products') ?></h5>
<div class="row g-3">
  <?php foreach ($_related as $_rp):
    $_ri  = !empty($_rp['product_featured_image']) ? base_url('assets/images/product/upload/thumb/' . $_rp['product_featured_image']) : base_url('assets/images/no_image_available.png');
    $_ru  = base_url('store/product/' . $_rp['product_slug']);
  ?>
  <div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm h-100">
      <a href="<?= $_ru ?>"><img src="<?= $_ri ?>" class="product-img card-img-top" alt=""></a>
      <div class="card-body">
        <a href="<?= $_ru ?>" class="text-dark fw-semibold small text-decoration-none"><?= htmlspecialchars($_rp['product_name']) ?></a>
        <div class="text-primary fw-bold small mt-1"><?= $currency_sign ?><?= number_format($_rp['product_price'], 2) ?></div>
      </div>
      <div class="card-footer border-0 bg-transparent pt-0">
        <a href="<?= $_ru ?>" class="btn btn-outline-primary btn-sm w-100"><?= __('store.view') ?></a>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>
PHP);

		/* ── cart.php ────────────────────────────────────────────────────── */
		$f['cart.php'] = $r(<<<'PHP'
<?php
/**
 * Cart — Store API v1 :: page_cart()
 * VARIABLES (from page_cart()):
 *   $products   array   Cart items — each row: product_id, product_name, product_price,
 *                       product_featured_image (full URL), cart_id, quantity, total (row total)
 *   $sub_total  mixed   Cart subtotal (scalar)
 *   $total      mixed   Cart grand total (scalar)
 *   $cart_url   string  URL of the cart page
 *   $settings   array   Store settings
 * Update: POST to cart page with quantity[{cart_id}] = new_qty
 * Remove: GET  ?remove={cart_id}
 */
$_items = $products ?? [];
?>

<h4 class="fw-bold mb-4"><?= __('store.shopping_cart') ?></h4>

<?php if (!empty($_items)): ?>
<?php /* NOTE: cart update POSTs to the cart endpoint which always returns JSON {success,html}.
         So we use AJAX (handled in theme.js #tss-cart-form) and redirect on success. */ ?>
<div id="tss-cart-msg-top"></div>
<form id="tss-cart-form" method="post" action="<?= $cart_url ?>">
<div class="row g-4">
  <div class="col-lg-8">
    <div class="card border-0 shadow-sm">
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table align-middle mb-0">
            <thead class="table-light"><tr>
              <th><?= __('store.product') ?></th>
              <th><?= __('store.price') ?></th>
              <th><?= __('store.quantity') ?></th>
              <th><?= __('store.total') ?></th>
              <th></th>
            </tr></thead>
            <tbody>
            <?php foreach ($_items as $_item): ?>
            <tr>
              <td>
                <div class="d-flex align-items-center gap-2">
                  <?php if (!empty($_item['product_featured_image'])): ?>
                    <img src="<?= $_item['product_featured_image'] ?>" style="width:50px;height:50px;object-fit:cover;" class="rounded" alt="" onerror="this.src='<?= base_url('assets/images/no_image_available.png') ?>'">
                  <?php endif; ?>
                  <div>
                    <div class="small fw-semibold"><?= htmlspecialchars($_item['product_name'] ?? '') ?></div>
                    <?php if (!empty($_item['cart_variation'])): ?>
                      <div class="text-muted" style="font-size:.7rem;"><?= htmlspecialchars($_item['cart_variation']) ?></div>
                    <?php endif; ?>
                  </div>
                </div>
              </td>
              <td class="small"><?= $currency_sign ?><?= number_format($_item['product_price'] ?? 0, 2) ?></td>
              <td>
                <input type="number" name="quantity[<?= $_item['cart_id'] ?>]"
                       value="<?= (int)($_item['quantity'] ?? 1) ?>" min="1"
                       class="form-control form-control-sm" style="width:65px;">
              </td>
              <td class="fw-bold small"><?= $currency_sign ?><?= number_format($_item['total'] ?? (($_item['product_price'] ?? 0) * ($_item['quantity'] ?? 1)), 2) ?></td>
              <td>
                <a href="<?= $cart_url ?>?remove=<?= $_item['cart_id'] ?? '' ?>"
                   class="btn btn-outline-danger btn-sm"
                   onclick="return confirm('<?= addslashes(__('store.confirm_remove')) ?>')"
                ><i class="bi bi-trash"></i></a>
              </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <button type="submit" class="btn btn-outline-secondary btn-sm mt-2">
      <span class="tss-update-txt"><?= __('store.update') ?></span>
      <span class="tss-update-spin d-none"><span class="spinner-border spinner-border-sm"></span></span>
    </button>
  </div>
  <div class="col-lg-4">
    <div class="card border-0 shadow-sm p-3 mb-3">
      <h6 class="fw-bold mb-3"><?= __('store.order_summary') ?></h6>
      <div class="d-flex justify-content-between small mb-1">
        <span><?= __('store.subtotal') ?></span>
        <strong><?= $currency_sign ?><?= number_format($sub_total ?? 0, 2) ?></strong>
      </div>
      <div class="d-flex justify-content-between small mb-2 fw-bold">
        <span><?= __('store.total') ?></span>
        <strong><?= $currency_sign ?><?= number_format($total ?? 0, 2) ?></strong>
      </div>
      <a href="<?= base_url('store/checkout') ?>" class="btn btn-primary w-100"><?= __('store.checkout') ?></a>
    </div>
  </div>
</div>
</form>
<?php else: ?>
<div class="text-center py-5">
  <i class="bi bi-cart3 display-4 text-muted d-block mb-3"></i>
  <p class="text-muted"><?= __('store.empty_cart') ?></p>
  <a href="<?= base_url('store/category') ?>" class="btn btn-primary"><?= __('store.browse_products') ?></a>
</div>
<?php endif; ?>
PHP);

		/* ── login.php ───────────────────────────────────────────────────── */
		$f['login.php'] = $r(<<<'PHP'
<?php
/**
 * Login / Register — Store API
 * ENDPOINT login:    POST store/ajax_login    → JSON {success:true} | {errors:{}}
 * ENDPOINT register: POST store/ajax_register → JSON {success:true} | {errors:{}}
 * GLOBALS: $redirect_url (string), $googlerecaptcha (array), $store_setting (array)
 *
 * NOTE: login/register are AJAX-only endpoints (both return JSON).
 *       Field names: username, password for login;
 *       f_name, l_name, username, email, phone, PhoneNumberInput, password, c_password for register.
 */
$_recaptcha_key = $googlerecaptcha['sitekey'] ?? $googlerecaptcha['recaptcha_site_key'] ?? '';
$_recaptcha_v   = $googlerecaptcha['version'] ?? $googlerecaptcha['recaptcha_version'] ?? 'v2';
$_client_login  = !empty($googlerecaptcha['client_login']) && !empty($_recaptcha_key);
$_client_reg    = !empty($googlerecaptcha['client_register']) && !empty($_recaptcha_key);
$_redirect      = $redirect_url ?? base_url('store/category');
?>
<div class="row g-4 justify-content-center">

  <!-- ── Login ──────────────────────────────────────────────────────── -->
  <div class="col-md-5">
    <div class="card border-0 shadow-sm p-4">
      <h4 class="fw-bold text-center mb-4"><i class="bi bi-box-arrow-in-right me-2"></i><?= __('store.login') ?></h4>
      <div id="tss-login-msg"></div>
      <form id="tss-login-form">
        <div class="mb-3">
          <label class="form-label small fw-semibold"><?= __('store.username') ?></label>
          <input type="text" name="username" class="form-control" required autocomplete="username">
        </div>
        <div class="mb-3">
          <label class="form-label small fw-semibold"><?= __('store.password') ?></label>
          <input type="password" name="password" class="form-control" required autocomplete="current-password">
        </div>
        <?php if ($_client_login): ?>
          <?php if ($_recaptcha_v === 'v3'): ?>
            <input type="hidden" name="g-recaptcha-response" id="gRecaptchaLogin">
            <script src="https://www.google.com/recaptcha/api.js?render=<?= $_recaptcha_key ?>"></script>
            <script>grecaptcha.ready(function(){grecaptcha.execute('<?= $_recaptcha_key ?>',{action:'client_login'}).then(function(t){document.getElementById('gRecaptchaLogin').value=t;});});</script>
          <?php else: ?>
            <div class="g-recaptcha mb-3" data-sitekey="<?= $_recaptcha_key ?>"></div>
            <script src="https://www.google.com/recaptcha/api.js"></script>
          <?php endif; ?>
        <?php endif; ?>
        <button type="submit" class="btn btn-primary w-100"><?= __('store.login') ?></button>
      </form>
      <hr>
      <p class="text-center small mb-0"><a href="#" data-bs-toggle="modal" data-bs-target="#tssLoginForgotModal"><?= __('store.forgot_password') ?></a></p>
    </div>
  </div>

  <!-- ── Register ───────────────────────────────────────────────────── -->
  <div class="col-md-5">
    <div class="card border-0 shadow-sm p-4">
      <h4 class="fw-bold text-center mb-4"><i class="bi bi-person-plus me-2"></i><?= __('store.register') ?></h4>
      <div id="tss-reg-msg"></div>
      <form id="tss-reg-form">
        <div class="row g-2 mb-2">
          <div class="col-6">
            <label class="form-label small fw-semibold"><?= __('store.first_name') ?></label>
            <input type="text" name="f_name" class="form-control" required>
          </div>
          <div class="col-6">
            <label class="form-label small fw-semibold"><?= __('store.last_name') ?></label>
            <input type="text" name="l_name" class="form-control" required>
          </div>
        </div>
        <div class="mb-2">
          <label class="form-label small fw-semibold"><?= __('store.username') ?></label>
          <input type="text" name="username" class="form-control" required autocomplete="username">
        </div>
        <div class="mb-2">
          <label class="form-label small fw-semibold"><?= __('store.email') ?></label>
          <input type="email" name="email" class="form-control" required>
        </div>
        <div class="mb-2">
          <label class="form-label small fw-semibold"><?= __('store.phone_number') ?></label>
          <input type="text" name="phone" id="tssRegPhone" class="form-control" required>
          <input type="hidden" name="PhoneNumberInput" id="tssRegPhoneHidden">
        </div>
        <div class="mb-2">
          <label class="form-label small fw-semibold"><?= __('store.password') ?></label>
          <input type="password" name="password" class="form-control" required autocomplete="new-password">
        </div>
        <div class="mb-3">
          <label class="form-label small fw-semibold"><?= __('store.confirm_password') ?></label>
          <input type="password" name="c_password" class="form-control" required autocomplete="new-password">
        </div>
        <?php if ($_client_reg): ?>
          <?php if ($_recaptcha_v === 'v3'): ?>
            <input type="hidden" name="g-recaptcha-response" id="gRecaptchaReg">
            <script src="https://www.google.com/recaptcha/api.js?render=<?= $_recaptcha_key ?>"></script>
            <script>grecaptcha.ready(function(){grecaptcha.execute('<?= $_recaptcha_key ?>',{action:'client_register'}).then(function(t){document.getElementById('gRecaptchaReg').value=t;});});</script>
          <?php else: ?>
            <div class="g-recaptcha mb-3" data-sitekey="<?= $_recaptcha_key ?>"></div>
          <?php endif; ?>
        <?php endif; ?>
        <button type="submit" class="btn btn-success w-100"><?= __('store.register') ?></button>
      </form>
    </div>
  </div>
</div>

<!-- Forgot Password Modal -->
<div class="modal fade" id="tssLoginForgotModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header border-0">
        <h6 class="modal-title fw-bold"><?= __('store.forgot_password') ?></h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="tss-forgot-msg"></div>
        <form id="tss-forgot-form">
          <div class="mb-3">
            <label class="form-label small"><?= __('store.email') ?></label>
            <input type="email" name="forgot_email" class="form-control form-control-sm" required>
          </div>
          <button type="submit" class="btn btn-primary btn-sm w-100"><?= __('store.send') ?></button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
/* Sync phone to hidden field (PhoneNumberInput) on change */
document.getElementById('tssRegPhone') && document.getElementById('tssRegPhone').addEventListener('input', function(){
  document.getElementById('tssRegPhoneHidden').value = this.value;
});
</script>
PHP);

		/* ── about.php ───────────────────────────────────────────────────── */
		$f['about.php'] = $r(<<<'PHP'
<?php
/**
 * About — Store API v1 :: page_about()
 * VARIABLES: $content (array — all store settings keyed by setting_key, language-aware),
 *            $store_setting (global store settings array)
 * Key: $content['about_content'] holds the CMS body HTML for About Us
 */
$_body = !empty($content['about_content'])
    ? $content['about_content']
    : (!empty($store_setting['store_description'])
        ? '<p>' . htmlspecialchars($store_setting['store_description']) . '</p>'
        : '<p>' . __('store.about_us_if_not_exist') . '</p>');
?>
<div class="row justify-content-center">
  <div class="col-lg-8">
    <nav aria-label="breadcrumb" class="mb-4">
      <ol class="breadcrumb"><li class="breadcrumb-item"><a href="<?= $home_link ?>"><?= __('store.home') ?></a></li><li class="breadcrumb-item active"><?= __('store.about_us') ?></li></ol>
    </nav>

    <?php if (!empty($store_setting['aboutimage'])): ?>
    <img src="<?= base_url('assets/images/site/' . $store_setting['aboutimage']) ?>" class="img-fluid rounded shadow-sm mb-4 w-100" style="max-height:300px;object-fit:cover;" alt="">
    <?php endif; ?>

    <h2 class="fw-bold mb-3"><?= __('store.about_us') ?></h2>
    <div class="mb-4"><?= $_body ?></div>

    <?php if (!empty($store_setting['email']) || !empty($store_setting['contact_number']) || !empty($store_setting['address'])): ?>
    <div class="card border-0 shadow-sm p-4 mt-3">
      <h6 class="fw-semibold mb-3"><i class="bi bi-info-circle me-2 text-primary"></i><?= __('store.contact_information') ?></h6>
      <?php if (!empty($store_setting['email'])): ?>
        <p class="mb-2 small"><i class="bi bi-envelope me-2 text-primary"></i><a href="mailto:<?= htmlspecialchars($store_setting['email']) ?>"><?= htmlspecialchars($store_setting['email']) ?></a></p>
      <?php endif; ?>
      <?php if (!empty($store_setting['contact_number'])): ?>
        <p class="mb-2 small"><i class="bi bi-telephone me-2 text-primary"></i><?= htmlspecialchars($store_setting['contact_number']) ?></p>
      <?php endif; ?>
      <?php if (!empty($store_setting['address'])): ?>
        <p class="mb-0 small"><i class="bi bi-geo-alt me-2 text-primary"></i><?= htmlspecialchars($store_setting['address']) ?></p>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php if (!empty($store_setting['contact_us_map'])): ?>
    <div class="mt-4 rounded overflow-hidden shadow-sm"><?= $store_setting['contact_us_map'] ?></div>
    <?php endif; ?>
  </div>
</div>
PHP);

		/* ── contact.php ─────────────────────────────────────────────────── */
		$f['contact.php'] = $r(<<<'PHP'
<?php
/**
 * Contact — POST to store/contact (standard form, NOT AJAX)
 * VARIABLES (from Store::contact()):
 *   $content (array — language-aware settings, key: contact_content)
 *   $storesettings / $settings / $store_setting  — store settings
 *   $googlerecaptcha  — recaptcha config
 *
 * Validation (server-side, CI form_validation):
 *   required: name, email, phone, message, terms
 * On failure: re-renders this view; use form_error() / validation_errors()
 * On success: redirects to HTTP_REFERER (no flash message by default)
 */
$_desc  = !empty($content['contact_content']) ? $content['contact_content'] : '';
$_rckey = $googlerecaptcha['sitekey'] ?? $googlerecaptcha['recaptcha_site_key'] ?? '';
$_rcv   = $googlerecaptcha['version'] ?? $googlerecaptcha['recaptcha_version'] ?? 'v2';
$_ve    = function_exists('validation_errors') ? validation_errors('<div class="alert alert-danger small">','</div>') : '';
?>
<div class="row justify-content-center">
  <div class="col-lg-7">
    <h2 class="fw-bold mb-2"><?= __('store.contact_us') ?></h2>
    <?php if ($_desc): ?><div class="text-muted mb-4"><?= $_desc ?></div><?php endif; ?>

    <?= $_ve ?>

    <form method="post" action="<?= base_url('store/contact') ?>">
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label small fw-semibold"><?= __('store.name') ?> *</label>
          <input type="text" name="name" class="form-control <?= form_error('name') ? 'is-invalid' : '' ?>" value="<?= set_value('name') ?>" required>
          <?php if (form_error('name')): ?><div class="invalid-feedback small"><?= form_error('name') ?></div><?php endif; ?>
        </div>
        <div class="col-md-6">
          <label class="form-label small fw-semibold"><?= __('store.email') ?> *</label>
          <input type="email" name="email" class="form-control <?= form_error('email') ? 'is-invalid' : '' ?>" value="<?= set_value('email') ?>" required>
          <?php if (form_error('email')): ?><div class="invalid-feedback small"><?= form_error('email') ?></div><?php endif; ?>
        </div>
        <div class="col-md-6">
          <label class="form-label small fw-semibold"><?= __('store.phone_number') ?> *</label>
          <input type="tel" name="phone" class="form-control <?= form_error('phone') ? 'is-invalid' : '' ?>" value="<?= set_value('phone') ?>" required>
          <?php if (form_error('phone')): ?><div class="invalid-feedback small"><?= form_error('phone') ?></div><?php endif; ?>
        </div>
        <div class="col-md-6">
          <label class="form-label small fw-semibold"><?= __('store.subject') ?></label>
          <input type="text" name="subject" class="form-control" value="<?= set_value('subject') ?>">
        </div>
        <div class="col-12">
          <label class="form-label small fw-semibold"><?= __('store.message') ?> *</label>
          <textarea name="message" class="form-control <?= form_error('message') ? 'is-invalid' : '' ?>" rows="5" required><?= set_value('message') ?></textarea>
          <?php if (form_error('message')): ?><div class="invalid-feedback small"><?= form_error('message') ?></div><?php endif; ?>
        </div>
        <?php if (!empty($_rckey)): ?>
          <?php if ($_rcv === 'v3'): ?>
            <div class="col-12">
              <input type="hidden" name="g-recaptcha-response" id="gRecaptchaContact">
              <script src="https://www.google.com/recaptcha/api.js?render=<?= $_rckey ?>"></script>
              <script>grecaptcha.ready(function(){grecaptcha.execute('<?= $_rckey ?>',{action:'contact'}).then(function(t){document.getElementById('gRecaptchaContact').value=t;});});</script>
            </div>
          <?php else: ?>
            <div class="col-12">
              <div class="g-recaptcha" data-sitekey="<?= $_rckey ?>"></div>
              <script src="https://www.google.com/recaptcha/api.js"></script>
            </div>
          <?php endif; ?>
        <?php endif; ?>
        <div class="col-12">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="terms" id="tssContactTerms" value="1" required>
            <label class="form-check-label small" for="tssContactTerms">
              <?= __('store.agree_terms') ?>
            </label>
            <?php if (form_error('terms')): ?><div class="text-danger small"><?= form_error('terms') ?></div><?php endif; ?>
          </div>
        </div>
        <div class="col-12">
          <button type="submit" class="btn btn-primary"><?= __('store.send_message') ?></button>
        </div>
      </div>
    </form>

    <?php if (!empty($store_setting['contact_us_map'])): ?>
    <div class="mt-4 rounded overflow-hidden shadow-sm"><?= $store_setting['contact_us_map'] ?></div>
    <?php endif; ?>
  </div>
</div>
PHP);

		/* ── policy.php ──────────────────────────────────────────────────── */
		$f['policy.php'] = $r(<<<'PHP'
<?php
/**
 * Policy — Store API v1 :: page_policy()
 * VARIABLES: $content (array — all store settings keyed by setting_key, language-aware)
 * Key: $content['policy_content'] holds the CMS body HTML for the Privacy Policy
 */
?>
<div class="row justify-content-center">
  <div class="col-lg-8">
    <nav aria-label="breadcrumb" class="mb-4">
      <ol class="breadcrumb"><li class="breadcrumb-item"><a href="<?= $home_link ?>"><?= __('store.home') ?></a></li><li class="breadcrumb-item active"><?= __('store.policy') ?></li></ol>
    </nav>
    <h2 class="fw-bold mb-4"><?= __('store.policy') ?></h2>
    <?php if (!empty($content['policy_content'])): ?>
      <div><?= $content['policy_content'] ?></div>
    <?php else: ?>
      <div class="alert alert-info"><i class="bi bi-info-circle me-2"></i><?= __('store.no_content') ?></div>
    <?php endif; ?>
  </div>
</div>
PHP);

		/* ── _account_header.php ─────────────────────────────────────────── */
		$f['_account_header.php'] = $r(<<<'PHP'
<?php
/**
 * Account sidebar nav — available on all account pages
 * VARIABLES: $client (session array with firstname/lastname/email)
 */
$_active = function($seg) { return strpos(current_url(), $seg) !== false ? 'active fw-semibold' : ''; };
?>
<div class="card border-0 shadow-sm mb-4">
  <div class="card-body text-center py-3">
    <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center mx-auto mb-2" style="width:54px;height:54px;font-size:1.4rem;">
      <?= strtoupper(substr($client['firstname'] ?? 'U', 0, 1)) ?>
    </div>
    <div class="fw-semibold small"><?= htmlspecialchars(($client['firstname'] ?? '') . ' ' . ($client['lastname'] ?? '')) ?></div>
    <div class="text-muted" style="font-size:.75rem;"><?= htmlspecialchars($client['email'] ?? '') ?></div>
  </div>
  <div class="list-group list-group-flush">
    <a href="<?= base_url('store/profile') ?>" class="list-group-item list-group-item-action <?= $_active('profile') ?>"><i class="bi bi-person me-2"></i><?= __('store.my_profile') ?></a>
    <a href="<?= base_url('store/order') ?>" class="list-group-item list-group-item-action <?= $_active('/order') ?>"><i class="bi bi-bag me-2"></i><?= __('store.my_orders') ?></a>
    <a href="<?= base_url('store/wishlist') ?>" class="list-group-item list-group-item-action <?= $_active('wishlist') ?>"><i class="bi bi-heart me-2"></i><?= __('store.wishlist') ?></a>
    <a href="<?= base_url('store/my_courses') ?>" class="list-group-item list-group-item-action <?= $_active('my_courses') ?>"><i class="bi bi-play-circle me-2"></i><?= __('store.my_courses') ?></a>
    <a href="<?= base_url('store/logout') ?>" class="list-group-item list-group-item-action text-danger"><i class="bi bi-box-arrow-right me-2"></i><?= __('store.logout') ?></a>
  </div>
</div>
PHP);

		/* ── profile.php ─────────────────────────────────────────────────── */
		$f['profile.php'] = $r(<<<'PHP'
<?php
/**
 * Profile — Store API v1 :: page_profile()
 *
 * VARIABLES (from page_profile()):
 *   $userDetails  array  User row: firstname, lastname, email, username,
 *                         phone, PhoneNumber, ucountry, state, ucity, uzip,
 *                         twaddress, avatar, type
 *   $country      array  Country objects (->id, ->name)
 *   $return_to    string Optional redirect URL after save
 *
 * POST target: store/profile (same page — saves then redirects)
 * Required fields: firstname, lastname, email, PhoneNumber, ucity, uzip, twaddress
 * Optional fields: PhoneNumberInput (synced to PhoneNumber), ucountry, state,
 *                  new_password, c_password, avatar (file)
 * NOTE: Controller saves $_POST['PhoneNumberInput'] to DB — keep it in sync with PhoneNumber.
 */
$_u  = $userDetails ?? [];
$_rt = $return_to ?? '';
$_err = $this->session->flashdata('error');
$_ok  = $this->session->flashdata('success');
?>
<div class="row g-4">
  <div class="col-md-3"><?php include(APPPATH.'views/store/{THEME_ID}/_account_header.php'); ?></div>
  <div class="col-md-9">
    <div class="card border-0 shadow-sm p-4">
      <h5 class="fw-bold mb-4"><?= __('store.my_profile') ?></h5>
      <?php if ($_err): ?><div class="alert alert-danger"><?= htmlspecialchars($_err) ?></div><?php endif; ?>
      <?php if ($_ok):  ?><div class="alert alert-success"><?= htmlspecialchars($_ok) ?></div><?php endif; ?>

      <form method="post" action="<?= base_url('store/profile') . ($_rt ? '?return_to='.urlencode($_rt) : '') ?>" enctype="multipart/form-data">

        <h6 class="fw-semibold mb-3 border-bottom pb-2"><?= __('store.personal_info') ?></h6>
        <div class="row g-3 mb-4">
          <div class="col-md-6">
            <label class="form-label small fw-semibold"><?= __('store.first_name') ?> <span class="text-danger">*</span></label>
            <input type="text" name="firstname" class="form-control" value="<?= htmlspecialchars($_u['firstname'] ?? '') ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label small fw-semibold"><?= __('store.last_name') ?> <span class="text-danger">*</span></label>
            <input type="text" name="lastname" class="form-control" value="<?= htmlspecialchars($_u['lastname'] ?? '') ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label small fw-semibold"><?= __('store.email') ?> <span class="text-danger">*</span></label>
            <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($_u['email'] ?? '') ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label small fw-semibold"><?= __('store.phone') ?> <span class="text-danger">*</span></label>
            <input type="tel" name="PhoneNumber" id="tss-phone" class="form-control"
                   value="<?= htmlspecialchars($_u['PhoneNumber'] ?? $_u['phone'] ?? '') ?>" required>
            <input type="hidden" name="PhoneNumberInput" id="tss-phone-input"
                   value="<?= htmlspecialchars($_u['PhoneNumber'] ?? $_u['phone'] ?? '') ?>">
          </div>
        </div>

        <h6 class="fw-semibold mb-3 border-bottom pb-2"><?= __('store.shipping_address') ?></h6>
        <div class="row g-3 mb-4">
          <div class="col-12">
            <label class="form-label small fw-semibold"><?= __('store.address') ?> <span class="text-danger">*</span></label>
            <input type="text" name="twaddress" class="form-control" value="<?= htmlspecialchars($_u['twaddress'] ?? '') ?>" required>
          </div>
          <div class="col-md-4">
            <label class="form-label small fw-semibold"><?= __('store.city') ?> <span class="text-danger">*</span></label>
            <input type="text" name="ucity" class="form-control" value="<?= htmlspecialchars($_u['ucity'] ?? '') ?>" required>
          </div>
          <div class="col-md-4">
            <label class="form-label small fw-semibold"><?= __('store.zip') ?> <span class="text-danger">*</span></label>
            <input type="text" name="uzip" class="form-control" value="<?= htmlspecialchars($_u['uzip'] ?? '') ?>" required>
          </div>
          <div class="col-md-4">
            <label class="form-label small fw-semibold"><?= __('store.state') ?></label>
            <input type="text" name="state" class="form-control" value="<?= htmlspecialchars($_u['state'] ?? '') ?>">
          </div>
          <?php if (!empty($country)): ?>
          <div class="col-12">
            <label class="form-label small fw-semibold"><?= __('store.country') ?></label>
            <select name="ucountry" class="form-select">
              <option value=""><?= __('store.select_country') ?></option>
              <?php foreach ($country as $_c): ?>
                <option value="<?= $_c->id ?>" <?= ($_u['ucountry'] ?? '') == $_c->id ? 'selected' : '' ?>><?= htmlspecialchars($_c->name) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <?php endif; ?>
        </div>

        <h6 class="fw-semibold mb-3 border-bottom pb-2"><?= __('store.change_password') ?></h6>
        <div class="row g-3 mb-4">
          <div class="col-md-6">
            <label class="form-label small fw-semibold"><?= __('store.new_password') ?></label>
            <input type="password" name="new_password" class="form-control" autocomplete="new-password" placeholder="<?= __('store.leave_blank_to_keep') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label small fw-semibold"><?= __('store.confirm_password') ?></label>
            <input type="password" name="c_password" class="form-control" autocomplete="new-password">
          </div>
        </div>

        <button type="submit" class="btn btn-primary px-4">
          <i class="bi bi-check-circle me-2"></i><?= __('store.save_changes') ?>
        </button>
      </form>
    </div>
  </div>
</div>
<script>
document.getElementById('tss-phone').addEventListener('input', function(){
  document.getElementById('tss-phone-input').value = this.value;
});
</script>
PHP);

		/* ── order_list.php ──────────────────────────────────────────────── */
		$f['order_list.php'] = $r(<<<'PHP'
<?php
/**
 * Order list — Store API v1 :: page_orders()
 * VARIABLES: $buyproductlist (array), $status (array id=>name map), $client
 */
$_orders = $buyproductlist ?? [];
$_status_map = $status ?? [];
?>
<div class="row g-4">
  <div class="col-md-3"><?php include(APPPATH.'views/store/{THEME_ID}/_account_header.php'); ?></div>
  <div class="col-md-9">
    <div class="card border-0 shadow-sm">
      <div class="card-header fw-bold"><?= __('store.my_orders') ?></div>
      <div class="card-body p-0">
        <?php if (!empty($_orders)): ?>
        <div class="table-responsive">
          <table class="table mb-0 align-middle">
            <thead class="table-light"><tr>
              <th>#</th>
              <th><?= __('store.date') ?></th>
              <th><?= __('store.status') ?></th>
              <th><?= __('store.total') ?></th>
              <th></th>
            </tr></thead>
            <tbody>
            <?php foreach ($_orders as $_o): ?>
            <tr>
              <td class="small"><?= htmlspecialchars($_o['id'] ?? '') ?></td>
              <td class="small"><?= htmlspecialchars($_o['created_at'] ?? '') ?></td>
              <td><span class="badge bg-primary"><?= htmlspecialchars($_status_map[(string)($_o['status'] ?? '')] ?? __('store.pending')) ?></span></td>
              <td class="small"><?= $currency_sign ?><?= number_format($_o['total_sum'] ?? $_o['total'] ?? 0, 2) ?></td>
              <td><a href="<?= base_url('store/vieworder/' . ($_o['id'] ?? '')) ?>" class="btn btn-outline-primary btn-sm"><?= __('store.view') ?></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php else: ?>
        <div class="text-center py-5 text-muted">
          <i class="bi bi-bag display-4 d-block mb-2"></i>
          <p><?= __('store.no_orders') ?></p>
          <a href="<?= base_url('store/category') ?>" class="btn btn-primary btn-sm"><?= __('store.browse_products') ?></a>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
PHP);

		/* ── view_order.php ──────────────────────────────────────────────── */
		$f['view_order.php'] = $r(<<<'PHP'
<?php
/**
 * View order — Store API v1 :: page_view_order()
 * VARIABLES: $order (array), $products (array of items), $totals (array),
 *            $order_history (array), $client
 */
$_order   = $order ?? [];
$_items   = $products ?? [];
$_totals  = $totals ?? [];
$_history = $order_history ?? [];
?>
<div class="row g-4">
  <div class="col-md-3"><?php include(APPPATH.'views/store/{THEME_ID}/_account_header.php'); ?></div>
  <div class="col-md-9">
    <h5 class="fw-bold mb-3"><?= __('store.order_details') ?> #<?= htmlspecialchars($_order['id'] ?? '') ?></h5>
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table mb-0 align-middle">
            <thead class="table-light"><tr>
              <th><?= __('store.product') ?></th>
              <th><?= __('store.quantity') ?></th>
              <th><?= __('store.price') ?></th>
            </tr></thead>
            <tbody>
            <?php foreach ($_items as $_item): ?>
            <tr>
              <td class="small"><?= htmlspecialchars($_item['product_name'] ?? '') ?></td>
              <td class="small"><?= (int)($_item['quantity'] ?? 1) ?></td>
              <td class="small"><?= $currency_sign ?><?= number_format($_item['price'] ?? 0, 2) ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div class="card border-0 shadow-sm p-3 mb-3">
      <?php foreach ($_totals as $_t): ?>
        <div class="d-flex justify-content-between small mb-1">
          <span><?= htmlspecialchars($_t['text'] ?? '') ?></span>
          <strong><?= $currency_sign ?><?= number_format($_t['value'] ?? 0, 2) ?></strong>
        </div>
      <?php endforeach; ?>
    </div>
    <?php if (!empty($_history)): ?>
    <div class="card border-0 shadow-sm p-3">
      <h6 class="fw-semibold mb-2"><?= __('store.order_history') ?></h6>
      <?php foreach ($_history as $_h): ?>
        <div class="d-flex gap-3 mb-2 pb-2 border-bottom">
          <span class="text-muted small"><?= htmlspecialchars($_h['created_at'] ?? '') ?></span>
          <span class="small"><?= htmlspecialchars($_h['comment'] ?? '') ?></span>
        </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
    <a href="<?= base_url('store/order') ?>" class="btn btn-outline-secondary btn-sm mt-3">
      <i class="bi bi-arrow-left me-1"></i><?= __('store.back') ?>
    </a>
  </div>
</div>
PHP);

		/* ── track_order.php ─────────────────────────────────────────────── */
		$f['track_order.php'] = $r(<<<'PHP'
<?php
/**
 * Track order — Store API v1 :: page_track_order()
 * VARIABLES (from Store::track_order()):
 *   $track_form_values (array — order_number, email submitted values)
 *   $error (string — error message on lookup failure)
 *   $order (array|null — order row on success, has: id, status(int), created_at)
 * Note: on success controller renders checkout_thankyou, not this view.
 */
$_v = $track_form_values ?? [];
?>
<div class="row justify-content-center">
  <div class="col-md-6">
    <div class="card border-0 shadow-sm p-4">
      <h5 class="fw-bold mb-4"><?= __('store.track_order') ?></h5>

      <?php if (!empty($error)): ?>
        <div class="alert alert-danger small"><?= htmlspecialchars($error) ?></div>
      <?php endif; ?>

      <form method="post" action="<?= base_url('store/track_order') ?>">
        <div class="mb-3">
          <label class="form-label small fw-semibold"><?= __('store.order_number') ?></label>
          <input type="text" name="order_number" class="form-control" value="<?= htmlspecialchars($_v['order_number'] ?? '') ?>" required>
        </div>
        <div class="mb-3">
          <label class="form-label small fw-semibold"><?= __('store.email') ?></label>
          <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($_v['email'] ?? '') ?>" required>
        </div>
        <button type="submit" class="btn btn-primary w-100"><?= __('store.track') ?></button>
      </form>

      <?php if (!empty($order)): ?>
      <hr>
      <div class="small">
        <div class="d-flex justify-content-between mb-1">
          <span><?= __('store.order_number') ?></span>
          <strong>#<?= htmlspecialchars($order['id'] ?? '') ?></strong>
        </div>
        <div class="d-flex justify-content-between mb-1">
          <span><?= __('store.status') ?></span>
          <strong><?= htmlspecialchars($order['order_status'] ?? $order['status'] ?? '') ?></strong>
        </div>
        <div class="d-flex justify-content-between mb-1">
          <span><?= __('store.date') ?></span>
          <strong><?= htmlspecialchars($order['created_at'] ?? '') ?></strong>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>
PHP);

		/* ── wishlist.php ────────────────────────────────────────────────── */
		$f['wishlist.php'] = $r(<<<'PHP'
<?php
/**
 * Wishlist — Store API v1 :: page_wishlist()
 * VARIABLES (from page_wishlist()):
 *   $products (array — wishlist items, each row: product_featured_image (filename),
 *              product_slug, product_name, product_price, product_id)
 *   $user_id  (int)
 */
$_items = $products ?? [];
?>
<div class="row g-4">
  <div class="col-md-3"><?php include(APPPATH.'views/store/{THEME_ID}/_account_header.php'); ?></div>
  <div class="col-md-9">
    <h5 class="fw-bold mb-3"><?= __('store.wishlist') ?></h5>
    <?php if (!empty($_items)): ?>
    <div class="row g-3">
      <?php foreach ($_items as $_item):
        $_img = !empty($_item['product_featured_image']) ? base_url('assets/images/product/upload/thumb/' . $_item['product_featured_image']) : base_url('assets/images/no_image_available.png');
        $_url = base_url('store/product/' . ($_item['product_slug'] ?? ''));
      ?>
      <div class="col-6 col-md-4">
        <div class="card border-0 shadow-sm h-100">
          <a href="<?= $_url ?>"><img src="<?= $_img ?>" class="product-img card-img-top" alt=""></a>
          <div class="card-body">
            <a href="<?= $_url ?>" class="text-dark fw-semibold small text-decoration-none"><?= htmlspecialchars($_item['product_name'] ?? '') ?></a>
            <div class="text-primary fw-bold small mt-1"><?= $currency_sign ?><?= number_format($_item['product_price'] ?? 0, 2) ?></div>
          </div>
          <div class="card-footer border-0 bg-transparent pt-0 d-flex gap-2">
            <a href="<?= $_url ?>" class="btn btn-primary btn-sm flex-grow-1"><?= __('store.view') ?></a>
            <button type="button" class="btn btn-outline-danger btn-sm tss-remove-wishlist"
                    data-product-id="<?= (int)($_item['product_id'] ?? 0) ?>"
                    title="<?= __('store.remove_from_wishlist') ?>">
              <i class="bi bi-trash"></i>
            </button>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div class="text-center py-5 text-muted">
      <i class="bi bi-heart display-4 d-block mb-2"></i>
      <p><?= __('store.empty_wishlist') ?></p>
    </div>
    <?php endif; ?>
  </div>
</div>
PHP);

		/* ── checkout_thankyou.php ─────────────────────────────────────────────
		 * NOTE: Store::thankyou() calls storeapp->view(..., true) — skip_layout=true.
		 * This view MUST be a fully self-contained HTML document (no layout wrapper).
		 * Globals like $store_setting, $client, $home_link, $store_currency are still
		 * injected by Storeapp even in skip_layout mode.
		 * Variables: $order, $products, $totals (text/value), $order_history, $status
		 * ─────────────────────────────────────────────────────────────────────────── */
		$f['checkout_thankyou.php'] = $r(<<<'PHP'
<?php
/**
 * Checkout Thank You — self-contained HTML (skip_layout = true)
 * Store API v1 :: Store::thankyou() — same variable set as page_checkout_thankyou()
 * GLOBALS: $store_setting, $client, $home_link, $store_currency
 * PAGE VARS: $order, $products, $totals (text/value), $order_history, $status
 */
$_name         = $store_setting['store_name'] ?? '{THEME_NAME}';
$_logo         = $store_setting['store_logo_upload'] ?? '';
$currency_sign = $store_currency ?? ($store_setting['currency_sign'] ?? '$');
$_order        = $order ?? [];
$_items        = $products ?? [];
$_totals       = $totals ?? [];
$_history      = $order_history ?? [];
$_order_id     = $_order['id'] ?? '';
?><!DOCTYPE html>
<html lang="<?= $store_setting['store_lang'] ?? 'en' ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= __('store.order_placed') ?> — <?= htmlspecialchars($_name) ?></title>
<?php if (!empty($store_setting['favicon'])): ?>
<link rel="icon" href="<?= base_url('assets/images/site/'.$store_setting['favicon']) ?>" type="image/*">
<?php endif; ?>
<link rel="stylesheet" href="<?= base_url('assets/template/css/bootstrap.min.css') ?>?v=<?= av() ?>">
<link rel="stylesheet" href="<?= base_url('assets/template/css/bootstrap-icons.css') ?>">
<script src="<?= base_url('assets/store/shared/js/jquery.min.js') ?>"></script>
<script>
/* Bootstrap 3/4 $.fn.btn polyfill */
(function($){ $.fn.btn=function(s){return this.each(function(){var $e=$(this);if(s==='loading'){$e.data('o',$e.html()).prop('disabled',true).html('<span class="spinner-border spinner-border-sm me-1"></span>');}else if(s==='reset'){$e.prop('disabled',false).html($e.data('o')||$e.html());}});}; })(jQuery);
</script>
<style>
:root{--theme-primary:#3b82f6;--theme-dark:#1e293b;}
body{background:#f8f9fa;font-family:system-ui,-apple-system,sans-serif;}
.navbar{background:var(--theme-dark)!important;}
</style>
</head>
<body>

<!-- Minimal navbar -->
<nav class="navbar navbar-dark shadow-sm mb-4">
  <div class="container">
    <a class="navbar-brand fw-bold text-white" href="<?= $home_link ?>">
      <?php if (!empty($_logo)): ?>
        <img src="<?= base_url('assets/images/site/'.$_logo) ?>" height="34" alt="<?= htmlspecialchars($_name) ?>">
      <?php else: ?>
        <?= htmlspecialchars($_name) ?>
      <?php endif; ?>
    </a>
    <div class="d-flex gap-2">
      <a href="<?= base_url('store/order') ?>" class="btn btn-outline-light btn-sm"><?= __('store.my_orders') ?></a>
      <a href="<?= base_url('store/category') ?>" class="btn btn-primary btn-sm"><?= __('store.continue_shopping') ?></a>
    </div>
  </div>
</nav>

<div class="container pb-5" style="max-width:720px;">

  <!-- Success banner -->
  <div class="card border-0 shadow-sm rounded-3 p-4 text-center mb-4">
    <div class="text-success mb-3" style="font-size:3.5rem;"><i class="bi bi-check-circle-fill"></i></div>
    <h3 class="fw-bold mb-1"><?= __('store.order_placed') ?></h3>
    <p class="text-muted mb-2"><?= __('store.thank_you_order') ?></p>
    <?php if ($_order_id): ?>
      <p class="mb-3"><?= __('store.order_number') ?>: <strong class="text-primary">#<?= htmlspecialchars($_order_id) ?></strong></p>
    <?php endif; ?>
    <div class="d-flex gap-2 justify-content-center">
      <a href="<?= base_url('store/order') ?>" class="btn btn-primary btn-sm px-4"><?= __('store.my_orders') ?></a>
      <a href="<?= base_url('store/category') ?>" class="btn btn-outline-secondary btn-sm px-4"><?= __('store.continue_shopping') ?></a>
    </div>
  </div>

  <!-- Order items -->
  <?php if (!empty($_items)): ?>
  <div class="card border-0 shadow-sm rounded-3 mb-4">
    <div class="card-header bg-light border-0 fw-semibold small py-3">
      <i class="bi bi-bag me-2 text-primary"></i><?= __('store.order_summary') ?>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table mb-0 align-middle">
          <thead class="table-light"><tr>
            <th class="small"><?= __('store.product') ?></th>
            <th class="small text-center"><?= __('store.quantity') ?></th>
            <th class="small text-end"><?= __('store.price') ?></th>
          </tr></thead>
          <tbody>
          <?php foreach ($_items as $_item): ?>
          <tr>
            <td class="small fw-semibold"><?= htmlspecialchars($_item['product_name'] ?? '') ?></td>
            <td class="small text-center"><?= (int)($_item['quantity'] ?? 1) ?></td>
            <td class="small text-end"><?= $currency_sign ?><?= number_format($_item['price'] ?? 0, 2) ?></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <div class="card-footer bg-white border-top pt-2 pb-3">
      <?php foreach ($_totals as $_t): ?>
      <div class="d-flex justify-content-between small text-muted mb-1">
        <span><?= htmlspecialchars($_t['text'] ?? '') ?></span>
        <span class="fw-semibold text-dark"><?= $currency_sign ?><?= number_format($_t['value'] ?? 0, 2) ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Order history -->
  <?php if (!empty($_history)): ?>
  <div class="card border-0 shadow-sm rounded-3">
    <div class="card-header bg-light border-0 fw-semibold small py-3">
      <i class="bi bi-clock-history me-2 text-primary"></i><?= __('store.order_history') ?>
    </div>
    <div class="card-body pb-2">
      <?php foreach ($_history as $_h): ?>
      <div class="d-flex gap-3 mb-2 pb-2 border-bottom">
        <span class="text-muted small text-nowrap"><?= htmlspecialchars($_h['created_at'] ?? '') ?></span>
        <span class="small"><?= htmlspecialchars($_h['comment'] ?? '') ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

</div>

<script src="<?= base_url('assets/template/js/bootstrap.bundle.min.js') ?>?v=<?= av() ?>"></script>
</body>
</html>
PHP);

		/* ── mini_cart.php ───────────────────────────────────────────────── */
		$f['mini_cart.php'] = $r(<<<'PHP'
<?php
/**
 * Mini-cart — uses same $products variable as page_cart()
 * product_featured_image is a full URL (resolved by Cart::getProducts)
 * quantity is the correct key (not qty)
 */
?>
<?php if (!empty($products)): ?>
<?php foreach ($products as $_item): ?>
<div class="d-flex gap-2 align-items-center mb-2">
  <img src="<?= !empty($_item['product_featured_image']) ? $_item['product_featured_image'] : base_url('assets/images/no_image_available.png') ?>" style="width:40px;height:40px;object-fit:cover;" class="rounded" alt="" onerror="this.src='<?= base_url('assets/images/no_image_available.png') ?>'">
  <div class="flex-grow-1 small">
    <div class="fw-semibold"><?= htmlspecialchars($_item['product_name'] ?? '') ?></div>
    <div class="text-muted"><?= (int)($_item['quantity'] ?? 1) ?> × <?= $currency_sign ?><?= number_format($_item['product_price'] ?? 0, 2) ?></div>
  </div>
</div>
<?php endforeach; ?>
<a href="<?= base_url('store/cart') ?>" class="btn btn-primary btn-sm w-100 mt-2"><?= __('store.view_cart') ?></a>
<?php else: ?>
<p class="small text-muted text-center mb-2"><?= __('store.empty_cart') ?></p>
<?php endif; ?>
PHP);

		/* ── product_list.php (SSR fallback) ─────────────────────────────── */
		$f['product_list.php'] = $r(<<<'PHP'
<?php
/**
 * Product list partial — rendered when load_Product is called WITHOUT request_page.
 * VARIABLES: $products_list (array), $product_ratings (array, keyed by product_id)
 */
?>
<div class="row g-3">
<?php foreach ($products_list ?? [] as $_p):
  $_img = !empty($_p['product_featured_image']) ? base_url('assets/images/product/upload/thumb/' . $_p['product_featured_image']) : base_url('assets/images/no_image_available.png');
  $_url = base_url('store/product/' . $_p['product_slug']);
?>
<div class="col-6 col-md-3">
  <div class="card border-0 shadow-sm h-100">
    <a href="<?= $_url ?>"><img src="<?= $_img ?>" class="product-img card-img-top" alt="<?= htmlspecialchars($_p['product_name']) ?>" onerror="this.src='<?= base_url('assets/images/no_image_available.png') ?>'"></a>
    <div class="card-body d-flex flex-column">
      <a href="<?= $_url ?>" class="text-dark fw-semibold small text-decoration-none flex-grow-1"><?= htmlspecialchars($_p['product_name']) ?></a>
      <div class="fw-bold text-primary small mt-1"><?= $currency_sign ?><?= number_format($_p['product_price'] ?? 0, 2) ?></div>
    </div>
    <div class="card-footer border-0 bg-transparent pt-0">
      <a href="<?= $_url ?>" class="btn btn-primary btn-sm w-100"><?= __('store.view') ?></a>
    </div>
  </div>
</div>
<?php endforeach; ?>
</div>
PHP);

		/* ── cookies_consent.php ─────────────────────────────────────────── */
		$f['cookies_consent.php'] = $r(<<<'PHP'
<?php if (!empty($SiteSetting['cookie_consent_status']) && !isset($_COOKIE['cookies_accepted'])): ?>
<div class="position-fixed bottom-0 start-0 end-0 bg-dark text-white p-3 shadow-lg" style="z-index:9999;" id="cookieBanner">
  <div class="container d-flex flex-wrap align-items-center justify-content-between gap-2">
    <p class="mb-0 small"><?= htmlspecialchars($SiteSetting['cookie_consent_text'] ?? __('store.cookie_message')) ?></p>
    <button class="btn btn-primary btn-sm" onclick="document.getElementById('cookieBanner').remove();document.cookie='cookies_accepted=1;path=/;max-age=31536000';"><?= __('store.accept') ?></button>
  </div>
</div>
<?php endif; ?>
PHP);

		/* ── custom_page.php ─────────────────────────────────────────────── */
		$f['custom_page.php'] = $r(<<<'PHP'
<?php
/**
 * Custom CMS page — Store API v1
 * VARIABLE: $data (object with ->title, ->content)
 */
$_title   = isset($data->title)   ? $data->title   : '';
$_content = isset($data->content) ? $data->content : '';
?>
<div class="row justify-content-center">
  <div class="col-lg-8">
    <?php if ($_title): ?><h2 class="fw-bold mb-4"><?= htmlspecialchars($_title) ?></h2><?php endif; ?>
    <?php if ($_content): ?><div><?= $_content ?></div><?php else: ?><p class="text-muted"><?= __('store.no_content') ?></p><?php endif; ?>
  </div>
</div>
PHP);

		/* ── checkout.php (redirect wrapper — routes to store/checkout controller) ── */
		$f['checkout.php'] = $r(<<<'PHP'
<?php /* The checkout() controller renders checkout_onepage or multi-step based on settings */ ?>
<?php redirect(base_url('store/checkout')); ?>
PHP);

		/* ── checkout_onepage.php ─────────────────────────────────────────── */
		$f['checkout_onepage.php'] = $r(<<<'PHP'
<?php
/**
 * One-page checkout — Store API v1 :: page_checkout()
 *
 * AJAX FLOW (matches confirm_order contract):
 *   1. Page load → POST store/get_payment_mothods  — loads available payment methods
 *   2. Page load → if allow_shipping: GET store/checkout_shipping  — loads shipping address form
 *   3. Submit  → AJAX POST store/confirm_order
 *      Required POST: agree=1, payment_gateway
 *      If shipping: address, country, state, city, zip_code, phone
 *      If guest (no shipping + not logged): classified_checkout=1, firstname, lastname, email
 *   4. confirm_order response:
 *      { confirm:"html" [,redirect:"url"] } → show payment step
 *      { redirect:"url" }                   → free order / skip payment
 *      { error:"msg" }                      → show alert
 *      { errors:{field:msg} }               → show field errors
 *
 * PAGE VARIABLES (from page_checkout()):
 *   $products       array  Cart items (product_name, product_price, quantity, total, product_featured_image)
 *   $totals         array  Keyed rows: ['title'=>string, 'amount'=>float]
 *   $is_logged      array|false
 *   $allow_shipping bool
 *   $confirm_html   string  Pre-built confirm HTML (page refresh recovery)
 *   $is_guest_flow  bool
 */
$_items      = $products ?? [];
$_tots       = $totals ?? [];
$_allow_ship = !empty($allow_shipping);
$_is_guest   = empty($is_logged);
$_confirm_pre = $confirm_html ?? '';
$_confirm_url = rtrim(base_url('store/'), '/') . '/confirm_order';
$_ship_url    = base_url('store/checkout_shipping');
$_pay_url     = base_url('store/get_payment_mothods');
?>
<h4 class="fw-bold mb-4"><i class="bi bi-bag-check me-2 text-primary"></i><?= __('store.checkout') ?></h4>

<div id="tss-checkout-main">
<div class="row g-4">

  <!-- ── LEFT ── -->
  <div class="col-lg-7">

    <?php if (!$_allow_ship && $_is_guest): ?>
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-light border-0"><h6 class="mb-0 fw-semibold"><i class="bi bi-person me-2"></i><?= __('store.customer_info') ?></h6></div>
      <div class="card-body">
        <input type="hidden" name="classified_checkout" value="1" form="tss-checkout-form">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label small"><?= __('store.first_name') ?> <span class="text-danger">*</span></label>
            <input type="text" name="firstname" class="form-control" form="tss-checkout-form" required>
          </div>
          <div class="col-md-6">
            <label class="form-label small"><?= __('store.last_name') ?> <span class="text-danger">*</span></label>
            <input type="text" name="lastname" class="form-control" form="tss-checkout-form" required>
          </div>
          <div class="col-12">
            <label class="form-label small"><?= __('store.email') ?> <span class="text-danger">*</span></label>
            <input type="email" name="email" class="form-control" form="tss-checkout-form" required>
          </div>
        </div>
        <div class="mt-3 small text-muted">
          <?= __('store.already_have_account') ?> <a href="<?= base_url('store/login') ?>"><?= __('store.login') ?></a>
        </div>
      </div>
    </div>
    <?php elseif ($_is_guest): ?>
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body py-2 small text-muted">
        <?= __('store.already_have_account') ?> <a href="<?= base_url('store/login') ?>"><?= __('store.login') ?></a>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($_allow_ship): ?>
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-light border-0"><h6 class="mb-0 fw-semibold"><i class="bi bi-geo-alt me-2"></i><?= __('store.shipping_address') ?></h6></div>
      <div class="card-body" id="tss-shipping-form">
        <div class="text-center py-3 text-muted">
          <div class="spinner-border spinner-border-sm me-2" role="status"></div><?= __('store.loading') ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-light border-0"><h6 class="mb-0 fw-semibold"><i class="bi bi-credit-card me-2"></i><?= __('store.payment_method') ?></h6></div>
      <div class="card-body" id="tss-payment-methods">
        <div class="text-center py-3 text-muted">
          <div class="spinner-border spinner-border-sm me-2" role="status"></div><?= __('store.loading') ?>
        </div>
      </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
      <div class="card-body">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" name="agree" value="1" id="tss-agree" form="tss-checkout-form" required>
          <label class="form-check-label small" for="tss-agree"><?= __('store.agree_text') ?></label>
        </div>
      </div>
    </div>
  </div>

  <!-- ── RIGHT: Order Summary ── -->
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm sticky-top" style="top:80px">
      <div class="card-header bg-light border-0"><h6 class="mb-0 fw-semibold"><i class="bi bi-receipt me-2"></i><?= __('store.order_summary') ?></h6></div>
      <div class="card-body">
        <?php if (empty($_items)): ?>
          <p class="text-muted small text-center"><?= __('store.empty_cart') ?></p>
        <?php endif; ?>
        <?php foreach ($_items as $_p): ?>
        <div class="d-flex align-items-center gap-3 mb-3 pb-3 border-bottom">
          <?php if (!empty($_p['product_featured_image'])): ?>
            <img src="<?= htmlspecialchars($_p['product_featured_image']) ?>" width="50" height="50" style="object-fit:cover;border-radius:6px;flex-shrink:0" alt="">
          <?php else: ?>
            <div style="width:50px;height:50px;background:#e2e8f0;border-radius:6px;flex-shrink:0;display:flex;align-items:center;justify-content:center;"><i class="bi bi-image text-muted"></i></div>
          <?php endif; ?>
          <div class="flex-grow-1 overflow-hidden">
            <p class="mb-0 small fw-semibold text-truncate"><?= htmlspecialchars($_p['product_name'] ?? '') ?></p>
            <small class="text-muted"><?= __('store.qty') ?>: <?= (int)($_p['quantity'] ?? 1) ?></small>
          </div>
          <span class="fw-semibold text-nowrap"><?= $currency_sign ?><?= number_format($_p['total'] ?? (($_p['product_price'] ?? 0) * ($_p['quantity'] ?? 1)), 2) ?></span>
        </div>
        <?php endforeach; ?>
        <div class="mt-1">
          <?php foreach ($_tots as $_t): ?>
          <div class="d-flex justify-content-between small mb-1 <?= array_key_last($_tots) === key($_tots) ? 'fw-bold border-top pt-2 mt-1' : '' ?>">
            <span><?= htmlspecialchars($_t['title'] ?? '') ?></span>
            <strong><?= $currency_sign ?><?= number_format($_t['amount'] ?? 0, 2) ?></strong>
          </div>
          <?php endforeach; ?>
        </div>
        <div id="tss-order-warning" class="mt-3"></div>
        <form id="tss-checkout-form" method="post" action="<?= $_confirm_url ?>">
          <button type="submit" id="tss-place-order" class="btn btn-primary w-100 mt-3 py-3 fw-bold">
            <i class="bi bi-lock me-2"></i><?= __('store.place_order') ?>
          </button>
        </form>
        <div class="text-center mt-2">
          <small class="text-muted"><i class="bi bi-shield-check me-1"></i> <?= __('store.secure_checkout') ?></small>
        </div>
      </div>
    </div>
  </div>
</div>
</div><!-- #tss-checkout-main -->

<!-- Confirmation / Payment gateway area -->
<div id="tss-confirm-area" class="d-none">
  <div class="row g-4">
    <div class="col-lg-8"><div id="tss-confirm-content"></div></div>
    <div class="col-lg-4">
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-light border-0"><h6 class="mb-0 fw-semibold"><?= __('store.order_summary') ?></h6></div>
        <div class="card-body small">
          <?php foreach ($_items as $_p): ?>
          <div class="d-flex justify-content-between mb-1 pb-1 border-bottom">
            <span class="text-truncate me-2"><?= htmlspecialchars($_p['product_name'] ?? '') ?> ×<?= (int)($_p['quantity'] ?? 1) ?></span>
            <strong class="text-nowrap"><?= $currency_sign ?><?= number_format($_p['total'] ?? (($_p['product_price'] ?? 0) * ($_p['quantity'] ?? 1)), 2) ?></strong>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
(function($){
  var $form    = $('#tss-checkout-form');
  var $warning = $('#tss-order-warning');
  var $btn     = $('#tss-place-order');

  /* Load shipping form */
  <?php if ($_allow_ship): ?>
  $.get('<?= addslashes($_ship_url) ?>', function(html){ $('#tss-shipping-form').html(html); })
   .fail(function(){ $('#tss-shipping-form').html('<p class="text-danger small"><?= __("store.error_loading_shipping") ?></p>'); });
  <?php endif; ?>

  /* Load payment methods */
  $.ajax({ url: '<?= addslashes($_pay_url) ?>', type: 'POST', dataType: 'json', data: { data: $form.serialize() },
    success: function(r){ $('#tss-payment-methods').html(r && r.html ? r.html : '<p class="text-muted small"><?= __("store.no_payment_methods") ?></p>'); },
    error:   function(){ $('#tss-payment-methods').html('<p class="text-danger small"><?= __("store.error_loading_payment") ?></p>'); }
  });

  /* bank_transfer toggle */
  $(document).on('change', '[name="payment_gateway"]', function(){
    $('.bank-transfer-instruction').toggle($(this).val() === 'bank_transfer');
  });

  /* Submit */
  $form.on('submit', function(e){
    e.preventDefault();
    $warning.html('');
    $form.find('.tss-field-error').remove();
    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span><?= __("store.loading") ?>');
    var fd = new FormData(this);
    var pg = $('[name="payment_gateway"]:checked').val();
    if (pg) fd.set('payment_gateway', pg);
    <?php if ($_allow_ship): ?>
    $('#tss-shipping-form [name]').each(function(){ if (this.name && !fd.has(this.name)) fd.append(this.name, $(this).val()); });
    <?php endif; ?>
    $.ajax({ url: '<?= addslashes($_confirm_url) ?>', type: 'POST', cache: false, contentType: false, processData: false, data: fd, dataType: 'text',
      success: function(raw){
        $btn.prop('disabled', false).html('<i class="bi bi-lock me-2"></i><?= __("store.place_order") ?>');
        var res; try { res = JSON.parse(raw); } catch(x){ res = null; }
        if (!res) { $warning.html('<div class="alert alert-danger small"><?= __("store.invalid_response") ?></div>'); return; }
        if (res.error) { $warning.html('<div class="alert alert-danger small">'+res.error+'</div>'); $('html,body').animate({scrollTop:$warning.offset().top-80},300); return; }
        if (res.errors) {
          var msgs=[];
          $.each(res.errors,function(f,m){ var $el=$form.find('[name="'+f+'"]'); if($el.length){$el.after('<span class="tss-field-error text-danger d-block small">'+m+'</span>');}else{msgs.push(m);} });
          if(msgs.length) $warning.html('<div class="alert alert-danger small">'+msgs.join('<br>')+'</div>');
          $('html,body').animate({scrollTop:$warning.offset().top-80},300); return;
        }
        if (res.confirm) {
          $('#tss-confirm-content').html(res.confirm);
          $('#tss-checkout-main').addClass('d-none');
          $('#tss-confirm-area').removeClass('d-none');
          $('html,body').animate({scrollTop:0},300);
          if (res.redirect) window.location.href = res.redirect;
          return;
        }
        if (res.redirect) window.location.href = res.redirect;
      },
      error: function(){
        $btn.prop('disabled', false).html('<i class="bi bi-lock me-2"></i><?= __("store.place_order") ?>');
        $warning.html('<div class="alert alert-danger small"><?= __("store.error_submitting_order") ?></div>');
      }
    });
  });

  /* Pre-built confirm recovery */
  <?php if (!empty($_confirm_pre)): ?>
  $('#tss-confirm-content').html(<?= json_encode($_confirm_pre) ?>);
  $('#tss-checkout-main').addClass('d-none');
  $('#tss-confirm-area').removeClass('d-none');
  <?php endif; ?>
})(jQuery);
</script>
PHP);

		/* ── Stub pages (kept minimal but valid) ─────────────────────────── */
		$_stub = function($title_key) use ($r) {
			return $r("<?php /* {$title_key} — stub. Customise as needed using Store API v1 contract. */ ?>\n<p class=\"text-muted text-center py-4\"><?= __('" . $title_key . "') ?></p>");
		};
		$f['checkout_confirm.php']          = $_stub('store.checkout_confirm');
		$f['checkout_cart.php']             = $_stub('store.cart');
		$f['checkout_shipping.php']         = $_stub('store.shipping');
		$f['checkount-without-pyament.php'] = $_stub('store.checkout');
		$f['shipping.php']                  = $_stub('store.shipping');

		/* ── payment_methods.php ─────────────────────────────────────────── */
		/* Rendered by AJAX GET/POST store/get_payment_mothods
		 * VARIABLES: $payment_gateways — assoc array keyed by gateway name,
		 *             each row: name, title, icon  +  gateway-specific settings
		 * First gateway is auto-checked so payment_gateway is always pre-selected.
		 */
		$f['payment_methods.php'] = $r(<<<'PHP'
<?php
/**
 * Payment methods selector — rendered via AJAX and injected into checkout_onepage.php
 * VARIABLES: $payment_gateways  array  Active gateways [ name => [name, title, icon, ...] ]
 */
$_gws  = $payment_gateways ?? [];
$_i    = 0;
?>
<?php if (empty($_gws)): ?>
  <div class="alert alert-info small py-2 mb-0"><i class="bi bi-info-circle me-2"></i><?= __('store.no_payment_methods') ?></div>
<?php else: ?>
  <div class="tss-payment-list d-flex flex-column gap-2">
  <?php foreach ($_gws as $_gw_key => $_gw): ?>
    <?php
      $_gw_name     = $_gw['name']  ?? $_gw_key;
      $_gw_title    = $_gw['title'] ?? ucfirst($_gw_name);
      $_gw_icon     = !empty($_gw['icon']) ? base_url($_gw['icon']) : '';
      $_is_default  = $_i === 0;
      $_is_bank     = $_gw_name === 'bank_transfer';
      $_bank_desc   = $_is_bank ? ($_gw['bank_transfer_description'] ?? $_gw['description'] ?? '') : '';
    ?>
    <label class="d-flex align-items-center gap-3 p-3 border rounded cursor-pointer tss-gw-label <?= $_is_default ? 'border-primary bg-light' : '' ?>"
           style="cursor:pointer;" for="tss_gw_<?= htmlspecialchars($_gw_name) ?>">
      <input type="radio" id="tss_gw_<?= htmlspecialchars($_gw_name) ?>"
             name="payment_gateway" value="<?= htmlspecialchars($_gw_name) ?>"
             class="form-check-input tss-gw-radio mt-0 flex-shrink-0"
             <?= $_is_default ? 'checked' : '' ?>>
      <?php if ($_gw_icon): ?>
        <img src="<?= $_gw_icon ?>" alt="<?= htmlspecialchars($_gw_title) ?>" style="height:28px;max-width:70px;object-fit:contain;">
      <?php else: ?>
        <i class="bi bi-credit-card fs-5 text-primary"></i>
      <?php endif; ?>
      <span class="fw-semibold small"><?= htmlspecialchars($_gw_title) ?></span>
    </label>
    <?php if ($_is_bank && !empty($_bank_desc)): ?>
    <div class="bank-transfer-instruction alert alert-secondary small py-2 mb-0 <?= $_is_default ? '' : 'd-none' ?>">
      <?= $_bank_desc ?>
    </div>
    <?php endif; ?>
  <?php $_i++; endforeach; ?>
  </div>
<?php endif; ?>

<script>
(function(){
  /* Highlight selected payment label */
  document.querySelectorAll('.tss-gw-radio').forEach(function(radio){
    radio.addEventListener('change', function(){
      document.querySelectorAll('.tss-gw-label').forEach(function(lbl){ lbl.classList.remove('border-primary','bg-light'); });
      if(this.checked){ this.closest('.tss-gw-label').classList.add('border-primary','bg-light'); }
    });
  });
})();
</script>
PHP);
		$f['my_courses.php'] = $r(<<<'PHP'
<?php
/**
 * My Courses (LMS) — Store API v1 :: page_my_courses()
 * @auth  required (redirects to login if not logged in)
 * VARIABLES: $courses (array), $user (array), $settings (array)
 * Each course: order_id, product_id, product_name, product_image,
 *              progress_total, progress_completed, order_status
 */
$_courses = $courses ?? [];
?>
<div class="row g-4">
  <div class="col-md-3"><?php include(APPPATH.'views/store/{THEME_ID}/_account_header.php'); ?></div>
  <div class="col-md-9">
    <h5 class="fw-bold mb-4"><?= __('store.my_courses') ?></h5>
    <?php if (!empty($_courses)): ?>
    <div class="row g-3">
      <?php foreach ($_courses as $_c):
        $_img  = !empty($_c['product_image']) ? base_url('assets/images/product/upload/thumb/' . $_c['product_image']) : base_url('assets/images/no_image_available.png');
        $_active = ((int)($_c['order_status'] ?? 0)) === 1;
        $_prog_total = (int)($_c['progress_total'] ?? 0);
        $_prog_done  = (int)($_c['progress_completed'] ?? 0);
        $_pct = $_prog_total > 0 ? min(100, round($_prog_done / $_prog_total * 100)) : 0;
        $_url = $_active ? base_url('store/vieworderdetails/' . $_c['order_id'] . '?referance=' . $_c['product_id']) : '#';
      ?>
      <div class="col-sm-6">
        <div class="card border-0 shadow-sm h-100">
          <img src="<?= $_img ?>" class="card-img-top" style="height:160px;object-fit:cover;" alt="" onerror="this.src='<?= base_url('assets/images/no_image_available.png') ?>'">
          <div class="card-body d-flex flex-column">
            <h6 class="fw-semibold mb-2"><?= htmlspecialchars($_c['product_name'] ?? '') ?></h6>
            <?php if ($_active && $_prog_total > 0): ?>
              <div class="progress mb-2" style="height:6px;">
                <div class="progress-bar bg-primary" style="width:<?= $_pct ?>%"></div>
              </div>
              <small class="text-muted mb-2"><?= $_pct ?>% <?= __('store.completed') ?></small>
            <?php elseif (!$_active): ?>
              <span class="badge bg-warning text-dark mb-2"><?= __('store.pending_payment') ?></span>
            <?php endif; ?>
            <a href="<?= $_url ?>" class="btn btn-<?= $_active ? 'primary' : 'secondary' ?> btn-sm mt-auto <?= !$_active ? 'disabled' : '' ?>">
              <i class="bi bi-play-circle me-1"></i><?= $_pct > 0 ? __('store.continue') : __('store.start_course') ?>
            </a>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div class="text-center py-5 text-muted">
      <i class="bi bi-play-circle display-4 d-block mb-3"></i>
      <p><?= __('store.no_courses') ?></p>
      <a href="<?= base_url('store/category') ?>" class="btn btn-primary btn-sm"><?= __('store.browse_products') ?></a>
    </div>
    <?php endif; ?>
  </div>
</div>
PHP);
		$f['thanks.php']                    = $_stub('store.thank_you');
		$f['vendor_store.php']              = $_stub('store.vendor_store');
		$f['user-proudcts.php']             = $_stub('store.products'); // vendor's own store products (note: typo preserved from core)
		$f['view_order_details.php']        = $_stub('store.order_details');
		$f['lms/template-1.php']            = $_stub('store.my_courses');

		/* ── assets/store/{id}/css/theme.css ─────────────────────────────── */
		$f['@css/theme.css'] = $r(<<<'CSS'
/* {THEME_NAME} — generated by Store Theme Scaffolder */
:root{--theme-primary:#3b82f6;--theme-dark:#1e293b;}
.product-img{height:200px;object-fit:cover;width:100%;}
.card:hover{box-shadow:0 4px 16px rgba(0,0,0,.12);transition:.2s;}
.navbar{background:var(--theme-dark)!important;}
footer{background:var(--theme-dark);color:#cbd5e1;}
footer a{color:#94a3b8;}
footer a:hover{color:#fff;}
CSS);

		/* ── assets/store/{id}/js/theme.js ───────────────────────────────── */
		$f['@js/theme.js'] = $r(<<<'JS'
/* {THEME_NAME} — generated by Store Theme Scaffolder */
$(function () {

  /* ── Helper: show message in a container ── */
  function tssMsg($el, type, html) {
    $el.html('<div class="alert alert-' + type + ' small py-2">' + html + '</div>').show();
  }

  /* ── Language / Currency switcher toggle ── */
  $(document).on('click', '.tss-sw-wrap .js-link, .tss-sw-wrap .js-link1, .tss-sw-wrap a.nav-link[data-bs-toggle!="dropdown"]', function (e) {
    var $wrap = $(this).closest('.tss-sw-wrap');
    var $drop = $wrap.find('.js-dropdown-list, .js-dropdown-list1, #language-dropdown, #currency-dropdown');
    if ($drop.length === 0) return; /* no dropdown items — single language/currency */
    e.preventDefault();
    e.stopPropagation();
    $wrap.toggleClass('open');
  });
  /* Close switcher on outside click */
  $(document).on('click', function (e) {
    if (!$(e.target).closest('.tss-sw-wrap').length) {
      $('.tss-sw-wrap').removeClass('open');
    }
  });

  /* ── Auto-submit category filter form on sort change ── */
  $('select[name="sort"]').on('change', function () {
    $(this).closest('form').submit();
  });

  /* ── Cart Update — POST returns JSON {success,html}; reload on success ── */
  $('#tss-cart-form').on('submit', function (e) {
    e.preventDefault();
    var $form = $(this);
    var $msg  = $('#tss-cart-msg-top');
    $form.find('.tss-update-txt').addClass('d-none');
    $form.find('.tss-update-spin').removeClass('d-none');
    $.ajax({
      url:      $form.attr('action'),
      type:     'POST',
      dataType: 'json',
      data:     $form.serialize(),
      success:  function (res) {
        if (res.success) {
          window.location.reload();
        } else {
          tssMsg($msg, 'danger', res.message || 'Could not update cart.');
          $form.find('.tss-update-txt').removeClass('d-none');
          $form.find('.tss-update-spin').addClass('d-none');
        }
      },
      error: function () {
        tssMsg($msg, 'danger', 'Server error — please try again.');
        $form.find('.tss-update-txt').removeClass('d-none');
        $form.find('.tss-update-spin').addClass('d-none');
      }
    });
  });

  /* ── Add to Cart — AJAX POST → redirect to cart ── */
  /* NOTE: controller reads "quantity" (not "qty") */
  $(document).on('click', '.tss-add-to-cart', function () {
    var btn  = $(this);
    var url  = btn.data('cart-url');
    var pid  = btn.data('product-id');
    var qty  = parseInt($('#tss-qty').val()) || 1;
    var $msg = $('#tss-cart-msg');

    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>');
    $.ajax({
      url: url, type: 'POST', dataType: 'json', data: { product_id: pid, quantity: qty },
      success: function (res) {
        if (res.location) { window.location.href = res.location; }
        else { tssMsg($msg, 'danger', res.error || 'Could not add to cart'); btn.prop('disabled', false).html('<i class="bi bi-cart-plus me-1"></i>Add to cart'); }
      },
      error: function () {
        tssMsg($msg, 'danger', 'Error — please try again.');
        btn.prop('disabled', false).html('<i class="bi bi-cart-plus me-1"></i>Add to cart');
      }
    });
  });

  /* ── Login form — AJAX POST store/ajax_login ── */
  $('#tss-login-form').on('submit', function (e) {
    e.preventDefault();
    var $msg = $('#tss-login-msg');
    var $btn = $(this).find('[type=submit]');
    $btn.prop('disabled', true);
    $.ajax({
      url: tssBase + 'store/ajax_login', type: 'POST', dataType: 'json',
      data: $(this).serialize(),
      success: function (res) {
        if (res.success) {
          window.location.href = tssRedirect || tssBase + 'store/category';
        } else {
          var msgs = res.errors ? Object.values(res.errors).join('<br>') : 'Login failed.';
          tssMsg($msg, 'danger', msgs);
          $btn.prop('disabled', false);
        }
      },
      error: function () { tssMsg($msg, 'danger', 'Server error. Please try again.'); $btn.prop('disabled', false); }
    });
  });

  /* ── Register form — AJAX POST store/ajax_register ── */
  $('#tss-reg-form').on('submit', function (e) {
    e.preventDefault();
    var $msg = $('#tss-reg-msg');
    var $btn = $(this).find('[type=submit]');
    $btn.prop('disabled', true);
    /* sync PhoneNumberInput hidden field before submit */
    $('#tssRegPhoneHidden').val($('#tssRegPhone').val());
    $.ajax({
      url: tssBase + 'store/ajax_register', type: 'POST', dataType: 'json',
      data: $(this).serialize(),
      success: function (res) {
        if (res.success) {
          tssMsg($msg, 'success', res.message || 'Registered successfully! Please log in.');
          $('#tss-reg-form')[0].reset();
          $btn.prop('disabled', false);
        } else {
          var msgs = res.errors ? Object.values(res.errors).join('<br>') : 'Registration failed.';
          tssMsg($msg, 'danger', msgs);
          $btn.prop('disabled', false);
        }
      },
      error: function () { tssMsg($msg, 'danger', 'Server error. Please try again.'); $btn.prop('disabled', false); }
    });
  });

  /* ── Forgot password form — AJAX POST store/forgot ── */
  /* Response: {error:"msg"} on failure, {success:"msg"} on success */
  $('#tss-forgot-form').on('submit', function (e) {
    e.preventDefault();
    var $msg = $('#tss-forgot-msg');
    var $btn = $(this).find('[type=submit]');
    $btn.prop('disabled', true);
    $.ajax({
      url: tssBase + 'store/forgot', type: 'POST', dataType: 'json',
      data: $(this).serialize(),
      success: function (res) {
        if (res.error) { tssMsg($msg, 'danger', res.error); $btn.prop('disabled', false); }
        else { tssMsg($msg, 'success', res.success || res.message || 'Check your email for reset instructions.'); }
      },
      error: function () { tssMsg($msg, 'danger', 'Server error. Please try again.'); $btn.prop('disabled', false); }
    });
  });

  /* ── Wishlist remove — AJAX POST store/toggle_wishlist (from wishlist page) ── */
  /* No remove_wishlist route exists; toggle_wishlist handles add AND remove */
  $(document).on('click', '.tss-remove-wishlist', function (e) {
    e.preventDefault();
    var $btn = $(this);
    var pid  = $btn.data('product-id');
    $btn.prop('disabled', true);
    $.post(tssBase + 'store/toggle_wishlist', { product_id: pid }, function () {
      $btn.closest('.col-6, .col-md-4').fadeOut(300, function () { $(this).remove(); });
    }).fail(function () { $btn.prop('disabled', false); });
  });

});
JS);

		/* ════════════════════════════════════════════════════════════════════
		 *  Write all files to disk
		 * ════════════════════════════════════════════════════════════════════ */
		$views_dir  = APPPATH . 'views/store/' . $id . '/';
		$assets_dir = FCPATH . 'assets/store/' . $id . '/';

		$errors = [];

		foreach ($f as $rel => $content) {
			/* CSS / JS go under assets/, everything else under views/ */
			if (substr($rel, 0, 1) === '@') {
				$path = $assets_dir . substr($rel, 1);
			} else {
				$path = $views_dir . $rel;
			}

			$dir = dirname($path);
			if (!is_dir($dir)) {
				if (!mkdir($dir, 0755, true) && !is_dir($dir)) {
					$errors[] = 'Could not create directory: ' . $dir;
					continue;
				}
			}

			if (file_put_contents($path, $content) === false) {
				$errors[] = 'Could not write: ' . $path;
			}
		}

		return empty($errors) ? true : $errors;
	}
}
