<?php
/* ============================================================================
   WBMCZ — ONE PAGE PER CATEGORY

   Every category in the catalogue gets its own file in admin/, so access can be
   handed out one shelf at a time: give somebody the Government Portals page and
   that is the only catalogue they can open. Each of those files is three lines
   long — it names its category and includes the product engine.

   This file works out what a category's page is called, and creates the ones
   that are missing. It is called from the category screen (so a new category
   gets its page the moment it is created), from the sidebar (so the menu links
   somewhere real) and from the migration.

   If the folder is read-only — some shared hosts are — nothing breaks: the
   sidebar falls back to admin/product_cat.php?cat=N, which shows the same
   screen but needs the broad catalogue permission rather than the narrow one.
   ============================================================================ */

if (!function_exists('pmp_slug')) {

/** The short name a category is known by in file names and permission keys. */
function pmp_slug($row)
{
    $key = (string)($row['category_key'] ?? '');
    if ($key === '') { $key = 'cat' . (int)($row['id'] ?? 0); }
    $slug = preg_replace('/^cat_/', '', strtolower($key));
    $slug = preg_replace('/[^a-z0-9_]+/', '_', $slug);
    $slug = trim((string)$slug, '_');
    return $slug !== '' ? $slug : ('cat' . (int)($row['id'] ?? 0));
}

/** The file name of a category's own catalogue page, e.g. product_gov_portals.php */
function pmp_file($row)
{
    return 'product_' . pmp_slug($row) . '.php';
}

/** The file name of a category's seller-submission queue, e.g. service_gov_portals.php */
function pmp_service_file($row)
{
    return 'service_' . pmp_slug($row) . '.php';
}

/** Where a menu should point for this category's submission queue. */
function pmp_service_url($row, $adminDir = null)
{
    $adminDir = $adminDir ?: (dirname(__DIR__) . '/admin');
    $file = pmp_service_file($row);
    return is_file($adminDir . '/' . $file) ? $file : ('pending_services.php?cat_id=' . (int)$row['id']);
}

/**
 * Where a menu should point for this category: its own page when the file is
 * there, and the shared ?cat= door when it is not.
 */
function pmp_url($row, $adminDir = null)
{
    $adminDir = $adminDir ?: (dirname(__DIR__) . '/admin');
    $file = pmp_file($row);
    return is_file($adminDir . '/' . $file) ? $file : ('product_cat.php?cat=' . (int)$row['id']);
}

/** The permission key that opens this category's page on its own. */
function pmp_perm($row)
{
    return ((int)($row['id'] ?? 0) === 1) ? 'gov_products.view' : ('products.view_' . pmp_slug($row));
}

/**
 * Write the missing per-category pages.
 *
 * Returns ['made' => [...], 'kept' => [...], 'failed' => [...]]. Existing files
 * are never overwritten — somebody may have added something to one by hand.
 */
function pmp_sync($db, $adminDir = null)
{
    $adminDir = $adminDir ?: (dirname(__DIR__) . '/admin');
    $out = ['made' => [], 'kept' => [], 'failed' => []];

    $cats = [];
    try { $cats = $db->select("SELECT * FROM service_categories ORDER BY display_order ASC, id ASC"); }
    catch (\Throwable $e) { return $out; }

    foreach ($cats as $c) {
        $file = pmp_file($c);
        $path = $adminDir . '/' . $file;
        if (is_file($path)) { $out['kept'][] = $file; continue; }

        $title = html_entity_decode((string)$c['title'], ENT_QUOTES, 'UTF-8');
        $body  = "<?php\n"
            . "/* ============================================================================\n"
            . "   WBMCZ ADMIN — " . strtoupper(str_replace('*/', '', $title)) . "\n"
            . "   ----------------------------------------------------------------------------\n"
            . "   This category's own page. Everything it does — the list, the tiles, adding\n"
            . "   one, the bulk upload and the sub categories — lives in the product engine,\n"
            . "   so this file only has to say which shelf it is.\n"
            . "\n"
            . "   Opened by:  products.view (the whole catalogue)\n"
            . "               " . pmp_perm($c) . " (this category alone)\n"
            . "\n"
            . "   Created automatically when the category was made. Deleting the category\n"
            . "   does not delete this file — the page will say so and stop.\n"
            . "   ============================================================================ */\n"
            . "\$WB_CAT = " . (int)$c['id'] . ";\n"
            . "require __DIR__ . '/includes/product_engine.php';\n";

        if (@file_put_contents($path, $body) !== false) { $out['made'][] = $file; }
        else { $out['failed'][] = $file; }
    }

    /* ...and the same again for the seller-submission queue */
    foreach ($cats as $c) {
        $file = pmp_service_file($c);
        $path = $adminDir . '/' . $file;
        if (is_file($path)) { $out['kept'][] = $file; continue; }

        $title = html_entity_decode((string)$c['title'], ENT_QUOTES, 'UTF-8');
        $body  = "<?php\n"
            . "/* ============================================================================\n"
            . "   WBMCZ ADMIN — " . strtoupper(str_replace('*/', '', $title)) . " · SUBMISSIONS\n"
            . "   ----------------------------------------------------------------------------\n"
            . "   What sellers have submitted under this category, waiting to be approved or\n"
            . "   rejected. The screen itself lives in the submission engine; this file only\n"
            . "   has to say which category it is.\n"
            . "\n"
            . "   Opened by:  services.view / products.view (the whole queue)\n"
            . "               " . pmp_perm($c) . " (this category alone)\n"
            . "   ============================================================================ */\n"
            . "\$WB_CAT = " . (int)$c['id'] . ";\n"
            . "require __DIR__ . '/includes/pending_services_engine.php';\n";

        if (@file_put_contents($path, $body) !== false) { $out['made'][] = $file; }
        else { $out['failed'][] = $file; }
    }

    return $out;
}

}
