<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/shares.php';
require_once __DIR__ . '/../includes/kyc_fields.php';
require_once __DIR__ . '/../includes/rbac.php';

/* ---------------------------------------------------------------------------
   Version guard — if includes/shares.php on the server is still the OLD copy,
   show a clear instruction instead of a white "undefined function" fatal.
   --------------------------------------------------------------------------- */
if (!function_exists('shares_breakdown')) {
    $__need = ['shares_breakdown', 'shares_mode', 'shares_amount_for', 'shares_pct_for', 'shares_col', 'shares_editable_keys'];
    $__missing = array_values(array_filter($__need, function ($f) { return !function_exists($f); }));
    ?><!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Update needed</title><style>
      body{font-family:system-ui,-apple-system,sans-serif;max-width:720px;margin:50px auto;padding:0 22px;color:#0f172a;line-height:1.7}
      .card{border:1px solid #fecaca;background:#fef2f2;border-radius:14px;padding:22px 24px}
      h2{margin:0 0 6px;color:#991b1b;font-size:20px} code{background:#fff;border:1px solid #fecdd3;padding:2px 7px;border-radius:5px;font-size:13px}
      ol{padding-left:20px} li{margin:9px 0} .ok{background:#ecfdf5;border-color:#a7f3d0;color:#065f46;margin-top:18px}
    </style></head><body>
    <div class="card">
      <h2>One file is out of date</h2>
      <p><b>admin/product_management.php</b> has been updated on this server, but
         <b>includes/shares.php</b> is still the old version, so the new share functions do not exist yet.</p>
      <p style="font-size:13px;color:#7f1d1d">Missing: <code><?php echo implode('</code>, <code>', $__missing); ?></code></p>
    </div>
    <div class="card ok">
      <b>How to fix it — takes a minute</b>
      <ol>
        <li>Upload the new <code>includes/shares.php</code> to your server (the whole <code>includes/</code> folder is safest).</li>
        <li>Open <code>servercheck.php</code> and clear OPcache if it offers to.</li>
        <li>Hard-refresh this page with <b>Ctrl + Shift + R</b>.</li>
      </ol>
      <p style="font-size:13px;margin-bottom:0">Nothing is broken and no data is lost — the page simply needs the matching
         <code>includes/</code> file before it can render.</p>
    </div>
    </body></html><?php
    exit;
}
require_once __DIR__ . '/../includes/admin_list.php';

if (!isLoggedIn() || !isAdmin()) { redirect('../login.php'); }

/* The detailed access check happens a few lines down, once we know whether this
   page is running as the agency list or the government list — it shows a proper
   screen instead of a bare line of text. */
require_once __DIR__ . '/../includes/acl.php';

/* ---------------------------------------------------------------------------
   Which half of the catalogue is this page showing?

     product_management.php      Agency & Software products — the full sheet,
                                 with MRP, discount price, seller and every
                                 share column.
     product_management_gov.php  Government Portals — those columns are dropped,
                                 because a government portal is always free and
                                 has no share to split. The two pages share this
                                 one file, so a fix here fixes both.
   --------------------------------------------------------------------------- */
$PM_GROUP  = defined('PM_GROUP') ? PM_GROUP : 'agency';
$IS_GOV    = ($PM_GROUP === 'government');
$PM_SELF   = $IS_GOV ? 'product_management_gov.php' : 'product_management.php';
$PM_KEY    = $IS_GOV ? 'products_gov' : 'products';
$PM_CATSQL = $IS_GOV ? ' AND ss.category_id = 1' : ' AND ss.category_id <> 1';
$PM_TITLE  = $IS_GOV ? 'Government Portals' : 'Product Management';
$PM_SUB    = $IS_GOV
    ? 'Every government portal listed on the site — always free, so no price or share columns'
    : 'Agency & software products, with the full price and share breakdown';

/* ---------------------------------------------------------------------------
   Column level access. On top of the government / agency split above, a staff
   account only sees the columns its own access allows — so one person can be
   given the product list without ever seeing the share breakdown.
   --------------------------------------------------------------------------- */
require_once __DIR__ . '/../includes/acl.php';
acl_ensure_schema($db);
$PM_MOD = $IS_GOV ? 'gov_products' : 'products';
acl_guard($PM_MOD . '.view');
if (!function_exists('pm_col')) {
    function pm_col($c) {
        return !function_exists('acl_col') || acl_col($GLOBALS['PM_MOD'], $c);
    }
}
$PM_SPAN = 4; /* tick box + number + category + name */
foreach ($IS_GOV
    ? ['links','customer_data','update','notes','action']
    : ['mrp','discount','seller','seller_share','sub_share','referral_share','staff_share','company_share','quick','update','notes','action']
    as $__c) { if (pm_col($__c)) { $PM_SPAN++; } }

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$success_msg = ''; $error_msg = '';
if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }
if (isset($_SESSION['flash_error']))   { $error_msg   = $_SESSION['flash_error'];   unset($_SESSION['flash_error']); }

/* ============================================================
   AUTO-SCHEMA — creates what this page needs if migration wasn't run
   ============================================================ */
$__conn = $db->getConnection();
$__pcts = ['seller_share_pct','subscription_discount_pct','referral_share_pct','staff_share_pct','company_share_pct'];
foreach (['seller_services','agency_services'] as $__t) {
    foreach ($__pcts as $__c) {
        try {
            $__r = $__conn->query("SHOW COLUMNS FROM $__t LIKE '$__c'");
            if ($__r && $__r->num_rows === 0) { $__conn->query("ALTER TABLE $__t ADD COLUMN $__c DECIMAL(5,2) NOT NULL DEFAULT 0.00"); }
        } catch (\Throwable $e) { /* ignore */ }
    }
}
foreach ([
    "CREATE TABLE IF NOT EXISTS product_notes (
        id INT AUTO_INCREMENT PRIMARY KEY, service_id INT NOT NULL, service_type VARCHAR(20) NOT NULL DEFAULT 'seller',
        title VARCHAR(255) NOT NULL, description TEXT NULL, created_by INT NULL, created_by_name VARCHAR(120) NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
    "CREATE TABLE IF NOT EXISTS product_update_history (
        id INT AUTO_INCREMENT PRIMARY KEY, service_id INT NOT NULL, service_type VARCHAR(20) NOT NULL DEFAULT 'seller',
        field_label VARCHAR(120) NOT NULL, old_value TEXT NULL, new_value TEXT NULL, updated_by INT NULL,
        updated_by_name VARCHAR(120) NULL, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
] as $__q) { try { $__conn->query($__q); } catch (\Throwable $e) {} }
shares_ensure_schema($db); // product_share_ledger

$me_row = $db->select("SELECT id, name FROM users WHERE id = ?", [$user_id]);
$me = !empty($me_row) ? $me_row[0] : ['id' => $user_id, 'name' => 'Admin'];

/* ============================================================
   AJAX (JSON)
   ============================================================ */
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $sid = intval($_GET['sid'] ?? 0);
    if ($_GET['ajax'] === 'notes') {
        echo json_encode($db->select("SELECT * FROM product_notes WHERE service_id = ? AND service_type = 'seller' ORDER BY created_at DESC", [$sid]));
    } elseif ($_GET['ajax'] === 'history') {
        echo json_encode($db->select("SELECT * FROM product_update_history WHERE service_id = ? AND service_type = 'seller' ORDER BY updated_at DESC", [$sid]));
    } elseif ($_GET['ajax'] === 'product') {
        $r = $db->select("SELECT * FROM seller_services WHERE id = ?", [$sid]);
        echo json_encode(!empty($r) ? $r[0] : null);
    } elseif ($_GET['ajax'] === 'recruitment') {
        $r = $db->select("SELECT id, title, required_kyc, area_mode FROM seller_services WHERE id = ?", [$sid]);
        $row = !empty($r) ? $r[0] : null;
        if ($row) {
            try {
                $pins = $db->select("SELECT pincode FROM product_areas
                                     WHERE service_id = ? AND service_type = 'seller' AND pincode IS NOT NULL AND pincode <> ''
                                     ORDER BY pincode", [$sid]);
            } catch (\Throwable $e) { $pins = []; }
            $row['pincodes'] = array_map(function ($p) { return $p['pincode']; }, $pins);

            try {
                $sts = $db->select("SELECT state FROM product_areas
                                    WHERE service_id = ? AND service_type = 'seller' AND state IS NOT NULL AND state <> ''
                                    ORDER BY state", [$sid]);
            } catch (\Throwable $e) { $sts = []; }
            $row['states'] = array_map(function ($p) { return $p['state']; }, $sts);

            /* the exact boxes ticked, expanded so half-section settings show right */
            $row['kyc_list'] = kycf_expand($db, product_required_kyc($row));
        }
        echo json_encode($row);
    } else { echo json_encode(['error' => 'unknown']); }
    exit;
}

/* ============================================================
   POST HANDLERS
   ============================================================ */
if (isset($_POST['add_note'])) {
    $sid   = intval($_POST['service_id']);
    $title = sanitize($_POST['note_title'] ?? '');
    $desc  = sanitize($_POST['note_description'] ?? '');
    if ($sid > 0 && $title !== '') {
        $db->insert("INSERT INTO product_notes (service_id, service_type, title, description, created_by, created_by_name) VALUES (?, 'seller', ?, ?, ?, ?)",
            [$sid, $title, $desc, $me['id'], $me['name']]);
        $_SESSION['flash_success'] = "Note added successfully!";
    } else { $_SESSION['flash_error'] = "Note title is required."; }
    redirect($PM_SELF);
}

if (isset($_POST['update_product'])) {
    $sid = intval($_POST['service_id']);
    $old = $db->select("SELECT * FROM seller_services WHERE id = ?", [$sid]);
    if (!empty($old)) {
        $old = $old[0];

        /* Share mode: percent or fixed rupees */
        $__mode = (($_POST['share_mode'] ?? $old['share_mode'] ?? 'percent') === 'amount') ? 'amount' : 'percent';
        $__base = (float)($_POST['discount_price'] ?? $old['discount_price']);
        if ($__base <= 0) { $__base = (float)($_POST['price'] ?? $old['price']); }

        if ($__mode === 'amount') {
            $__used = 0.0;
            foreach (shares_editable_keys() as $__k) {
                $__used += (float)($_POST[shares_col($__k, 'amt')] ?? $old[shares_col($__k, 'amt')] ?? 0);
            }
            if ($__used > $__base + 0.001) {
                $_SESSION['flash_error'] = "Shares total ₹" . number_format($__used, 2) . " — that is more than the selling price of ₹" . number_format($__base, 2) . ". Nothing was saved.";
                redirect($PM_SELF);
            }
        } else {
            $__used = (float)($_POST['seller_share_pct'] ?? $old['seller_share_pct'])
                    + (float)($_POST['subscription_discount_pct'] ?? $old['subscription_discount_pct'])
                    + (float)($_POST['referral_share_pct'] ?? $old['referral_share_pct'])
                    + (float)($_POST['staff_share_pct'] ?? $old['staff_share_pct']);
            if ($__used > 100) {
                $_SESSION['flash_error'] = "Shares total " . rtrim(rtrim(number_format($__used, 2), '0'), '.') . "% — they cannot exceed 100%. Nothing was saved.";
                redirect($PM_SELF);
            }
        }

        $fields = [
            'title'                     => 'Product / Service Name',
            'price'                     => 'MRP',
            'discount_price'            => 'Discount Price',
            'seller_share_pct'          => 'Seller Share %',
            'subscription_discount_pct' => 'Discount Share (Subscription) %',
            'referral_share_pct'        => 'Referral Share %',
            'staff_share_pct'           => 'Staff Share %',
        ];
        $_POST['share_mode'] = $__mode;
        $fields['share_mode'] = 'Share Mode';

        if ($__mode === 'amount') {
            // Rupee mode: store the amounts, then mirror them into the % columns
            foreach (shares_editable_keys() as $__k) {
                $__ac = shares_col($__k, 'amt'); $__pc = shares_col($__k, 'pct');
                $__av = round((float)($_POST[$__ac] ?? $old[$__ac] ?? 0), 2);
                $_POST[$__ac] = $__av;
                $_POST[$__pc] = ($__base > 0) ? round(($__av / $__base) * 100, 2) : 0.00;
                $fields[$__ac] = ucfirst($__k) . ' Share ₹';
                $fields[$__pc] = ucfirst($__k) . ' Share %';
            }
            $__co = round(max(0, $__base - $__used), 2);
            $_POST['company_share_amt'] = $__co;
            $_POST['company_share_pct'] = ($__base > 0) ? round(($__co / $__base) * 100, 2) : 0.00;
            $fields['company_share_amt'] = 'Company Share ₹';
            $fields['company_share_pct'] = 'Company Share %';
        } else {
            // Percent mode: company share is the remainder, amounts mirrored
            $_POST['company_share_pct'] = shares_company_pct(
                $_POST['seller_share_pct'] ?? $old['seller_share_pct'],
                $_POST['subscription_discount_pct'] ?? $old['subscription_discount_pct'],
                $_POST['referral_share_pct'] ?? $old['referral_share_pct'],
                $_POST['staff_share_pct'] ?? $old['staff_share_pct']
            );
            $fields['company_share_pct'] = 'Company Share %';
            foreach (array_merge(shares_editable_keys(), ['company']) as $__k) {
                $__pc = shares_col($__k, 'pct'); $__ac = shares_col($__k, 'amt');
                $__pv = (float)($_POST[$__pc] ?? $old[$__pc] ?? 0);
                $_POST[$__ac] = round(($__base * $__pv) / 100, 2);
                $fields[$__ac] = ucfirst($__k) . ' Share ₹';
            }
        }
        $changed = 0;
        foreach ($fields as $col => $label) {
            if (!isset($_POST[$col])) continue;
            $newv = sanitize($_POST[$col]);
            $oldv = (string)($old[$col] ?? '');
            if (rtrim(rtrim($oldv, '0'), '.') !== rtrim(rtrim((string)$newv, '0'), '.') && $oldv !== (string)$newv) {
                $db->insert("UPDATE seller_services SET `$col` = ? WHERE id = ?", [$newv, $sid]); // whitelisted column
                $db->insert("INSERT INTO product_update_history (service_id, service_type, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'seller', ?, ?, ?, ?, ?)",
                    [$sid, $label, $oldv, $newv, $me['id'], $me['name']]);
                $changed++;
            }
        }
        $_SESSION['flash_success'] = $changed > 0 ? "Product updated ($changed field" . ($changed > 1 ? 's' : '') . " changed)." : "No changes were made.";
    }
    redirect($PM_SELF);
}

/* ---- Full service edit — the same fields a seller has on their own page,
        so an admin can correct any product without asking the seller ---- */
/* ---- Add a product / portal straight from this screen ------------------
        On the Government Portals page the category is fixed to 1 and the
        price is forced to zero, because a government portal is always free.
        The row is owned by the admin who adds it and goes live at once. ---- */
if (isset($_POST['add_service'])) {
    $title = sanitize($_POST['title'] ?? '');
    if ($title === '') {
        $_SESSION['flash_error'] = 'The product needs a name.';
        redirect($PM_SELF);
    }

    $cat = $IS_GOV ? 1 : (int)($_POST['category_id'] ?? 0);
    if (!$IS_GOV && $cat <= 0) {
        $_SESSION['flash_error'] = 'Please choose a category.';
        redirect($PM_SELF);
    }

    $icon   = sanitize($_POST['icon_class'] ?? '');
    $is_img = (strpos($icon, 'http') === 0 || strpos($icon, 'uploads/') === 0) ? 1 : 0;

    if (!empty($_FILES['image_upload']['name']) && is_uploaded_file($_FILES['image_upload']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['image_upload']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'], true)) {
            $dir = __DIR__ . '/../uploads/services/';
            if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
            $fn = 'srv_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            if (move_uploaded_file($_FILES['image_upload']['tmp_name'], $dir . $fn)) {
                $icon = 'uploads/services/' . $fn; $is_img = 1;
            }
        }
    }
    if ($icon === '') { $icon = $IS_GOV ? 'fa-landmark' : 'fa-cube'; $is_img = 0; }

    $price = $IS_GOV ? 0.0 : (float)($_POST['price'] ?? 0);
    $disc  = $IS_GOV ? 0.0 : (float)($_POST['discount_price'] ?? 0);

    $new_id = (int)$db->insert(
        "INSERT INTO seller_services
         (seller_id, category_id, sub_category_id, title, description, price, discount_price,
          is_img, icon_class, color_class, web_url, app_url, tutorial_url, status)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        [
            $me['id'], $cat, (int)($_POST['sub_category_id'] ?? 0),
            $title, sanitize($_POST['description'] ?? ''), $price, $disc,
            $is_img, $icon, sanitize($_POST['color_class'] ?? 'color-1'),
            sanitize($_POST['web_url'] ?? ''), sanitize($_POST['app_url'] ?? ''),
            sanitize($_POST['tutorial_url'] ?? ''),
            ((int)($_POST['status'] ?? 1) === 1) ? 1 : 0,
        ]
    );

    if ($new_id) {
        try {
            $db->insert("INSERT INTO product_update_history (service_id, service_type, field_label, old_value, new_value, updated_by, updated_by_name)
                         VALUES (?, 'seller', 'Created', '', ?, ?, ?)",
                        [$new_id, $title . ' added from the admin panel', $me['id'], $me['name']]);
        } catch (\Throwable $e) {}
        $_SESSION['flash_success'] = ($IS_GOV ? 'Portal' : 'Product') . ' "' . $title . '" added.';
    } else {
        $_SESSION['flash_error'] = 'It could not be saved. Please try again.';
    }
    redirect($PM_SELF);
}

if (isset($_POST['edit_service'])) {
    $sid = (int)($_POST['service_id'] ?? 0);
    $old = $db->select("SELECT * FROM seller_services WHERE id = ?", [$sid]);
    if (empty($old)) { $_SESSION['flash_error'] = 'That product no longer exists.'; redirect($PM_SELF); }
    $old = $old[0];

    $icon   = sanitize($_POST['icon_class'] ?? '');
    $is_img = (strpos($icon, 'http') === 0 || strpos($icon, 'uploads/') === 0) ? 1 : 0;

    /* optional new image */
    if (!empty($_FILES['image_upload']['name']) && is_uploaded_file($_FILES['image_upload']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['image_upload']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'], true)) {
            $dir = __DIR__ . '/../uploads/services/';
            if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
            $fn = 'srv_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            if (move_uploaded_file($_FILES['image_upload']['tmp_name'], $dir . $fn)) {
                $icon = 'uploads/services/' . $fn; $is_img = 1;
            }
        }
    }
    if ($icon === '') { $icon = (string)$old['icon_class']; $is_img = (int)$old['is_img']; }

    $cat = (int)($_POST['category_id'] ?? $old['category_id']);
    $price = (float)($_POST['price'] ?? 0);
    $disc  = (float)($_POST['discount_price'] ?? 0);
    if ($cat === 1) { $price = 0.0; $disc = 0.0; }          // Government Portals stay free

    $fields = [
        'title'          => ['Title',          sanitize($_POST['title'] ?? '')],
        'description'    => ['Description',    sanitize($_POST['description'] ?? '')],
        'category_id'    => ['Category',       $cat],
        'sub_category_id'=> ['Sub category',   (int)($_POST['sub_category_id'] ?? 0)],
        'price'          => ['MRP',            $price],
        'discount_price' => ['Discount price', $disc],
        'icon_class'     => ['Icon / image',   $icon],
        'is_img'         => ['Icon is image',  $is_img],
        'color_class'    => ['Colour',         sanitize($_POST['color_class'] ?? 'color-1')],
        'web_url'        => ['Website link',   sanitize($_POST['web_url'] ?? '')],
        'app_url'        => ['App link',       sanitize($_POST['app_url'] ?? '')],
        'tutorial_url'   => ['Tutorial link',  sanitize($_POST['tutorial_url'] ?? '')],
        'status'         => ['Status',         ((int)($_POST['status'] ?? 1) === 1) ? 1 : 0],
    ];

    $changed = 0;
    foreach ($fields as $col => $def) {
        list($label, $val) = $def;
        if ((string)($old[$col] ?? '') === (string)$val) continue;
        $db->insert("UPDATE seller_services SET `$col` = ? WHERE id = ?", [$val, $sid]);   // whitelisted column
        $db->insert("INSERT INTO product_update_history (service_id, service_type, field_label, old_value, new_value, updated_by, updated_by_name)
                     VALUES (?, 'seller', ?, ?, ?, ?, ?)",
                    [$sid, $label, (string)($old[$col] ?? ''), (string)$val, $me['id'], $me['name']]);
        $changed++;
    }

    $_SESSION['flash_success'] = $changed > 0
        ? "Product edited ($changed field" . ($changed > 1 ? 's' : '') . " changed)."
        : 'No changes were made.';
    redirect($PM_SELF);
}

/* ---- Customer Data Recruitment: required KYC + serviceable area ---- */
if (isset($_POST['save_recruitment'])) {
    $sid = intval($_POST['service_id']);
    if ($sid > 0) {
        /* 1) Required KYC — now down to the individual box, plus the admin's
              own questions. Anything that is not in the catalogue is dropped. */
        $catalog = kycf_flat_labels($db);
        $sel = (isset($_POST['required_kyc']) && is_array($_POST['required_kyc'])) ? $_POST['required_kyc'] : [];
        $clean = [];
        foreach ($sel as $k) {
            $k = trim((string)$k);
            if ($k !== '' && isset($catalog[$k])) { $clean[] = $k; }
        }
        $clean   = array_values(array_unique($clean));
        $kyc_csv = implode(',', $clean);
        if (strlen($kyc_csv) > 250) {
            /* the column holds 255 characters — collapse a fully ticked section
               back into its short section key so nothing is silently cut off */
            $short = [];
            foreach (kycf_builtin() as $sec => $def) {
                $all = true;
                foreach (array_keys($def['fields']) as $col) {
                    if (!in_array($sec . '.' . $col, $clean, true)) { $all = false; break; }
                }
                if ($all) {
                    $short[] = $sec;
                    $clean = array_values(array_filter($clean, function ($k) use ($sec) { return strpos($k, $sec . '.') !== 0; }));
                }
            }
            $kyc_csv = substr(implode(',', array_merge($short, $clean)), 0, 250);
        }

        /* 2) Area mode — all India, one pincode, a bulk pincode list, or by state */
        $mode = in_array(($_POST['area_mode'] ?? 'all'), ['all', 'single', 'bulk', 'state'], true) ? $_POST['area_mode'] : 'all';

        $db->insert("UPDATE seller_services SET required_kyc = ?, area_mode = ? WHERE id = ?", [$kyc_csv, $mode, $sid]);

        /* Rebuild the area list from scratch */
        $db->insert("DELETE FROM product_areas WHERE service_id = ? AND service_type = 'seller'", [$sid]);

        $pins = []; $states = [];
        if ($mode === 'single') {
            $p = preg_replace('/\D/', '', (string)($_POST['single_pincode'] ?? ''));
            if ($p !== '') $pins[] = $p;
        } elseif ($mode === 'bulk') {
            $raw = (string)($_POST['bulk_pincodes'] ?? '');
            foreach (preg_split('/[\s,;]+/', $raw) as $p) {
                $p = preg_replace('/\D/', '', $p);
                if ($p !== '') $pins[] = $p;
            }
            // Optional .txt / .csv upload
            if (!empty($_FILES['pincode_file']['tmp_name']) && is_uploaded_file($_FILES['pincode_file']['tmp_name'])) {
                $content = @file_get_contents($_FILES['pincode_file']['tmp_name']);
                foreach (preg_split('/[\s,;]+/', (string)$content) as $p) {
                    $p = preg_replace('/\D/', '', $p);
                    if ($p !== '') $pins[] = $p;
                }
            }
        } elseif ($mode === 'state') {
            $sel_states = (isset($_POST['states']) && is_array($_POST['states'])) ? $_POST['states'] : [];
            foreach ($sel_states as $st) {
                $st = sanitize($st);
                if ($st !== '') $states[] = $st;
            }
        }

        $pins   = array_values(array_unique($pins));
        $states = array_values(array_unique($states));

        foreach ($pins as $p) {
            try { $db->insert("INSERT IGNORE INTO product_areas (service_id, service_type, pincode) VALUES (?, 'seller', ?)", [$sid, $p]); }
            catch (\Throwable $e) {}
        }
        foreach ($states as $st) {
            try { $db->insert("INSERT INTO product_areas (service_id, service_type, pincode, state) VALUES (?, 'seller', NULL, ?)", [$sid, $st]); }
            catch (\Throwable $e) {}
        }

        $summary = "KYC: " . (count($clean) ?: 'none') . " field(s) | Area: $mode ("
                 . ($mode === 'state' ? count($states) . ' state' : count($pins) . ' pincode') . ")";
        $db->insert("INSERT INTO product_update_history (service_id, service_type, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'seller', 'Customer Data Recruitment', '', ?, ?, ?)",
            [$sid, $summary, $me['id'], $me['name']]);

        $_SESSION['flash_success'] = "Recruitment settings saved — " . $summary . ".";
    }
    redirect($PM_SELF);
}

if (isset($_POST['toggle_status'])) {
    $sid = intval($_POST['service_id']);
    $cur = intval($_POST['current_status']);
    $new = $cur == 1 ? 0 : 1;
    $db->insert("UPDATE seller_services SET status = ? WHERE id = ?", [$new, $sid]);
    $db->insert("INSERT INTO product_update_history (service_id, service_type, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'seller', 'Status', ?, ?, ?, ?)",
        [$sid, $cur ? 'Active' : 'Inactive', $new ? 'Active' : 'Inactive', $me['id'], $me['name']]);
    $_SESSION['flash_success'] = "Status updated successfully!";
    redirect($PM_SELF);
}

if (isset($_POST['delete_product'])) {
    $sid = intval($_POST['service_id']);
    $db->insert("DELETE FROM seller_services WHERE id = ?", [$sid]);
    $_SESSION['flash_success'] = "Product deleted successfully!";
    redirect($PM_SELF);
}

if (isset($_POST['bulk_delete'])) {
    $ids = (isset($_POST['product_ids']) && is_array($_POST['product_ids'])) ? array_map('intval', $_POST['product_ids']) : [];
    $n = 0;
    foreach ($ids as $id) { if ($id > 0) { $db->insert("DELETE FROM seller_services WHERE id = ?", [$id]); $n++; } }
    $_SESSION['flash_success'] = $n > 0 ? "$n product(s) deleted." : "Nothing was deleted.";
    redirect($PM_SELF);
}

/* ============================================================
   FILTERS + DATA
   ============================================================ */
$PM_DEFAULTS = ['search'=>'', 'f_cat'=>'', 'f_sub'=>'', 'f_seller'=>'', 'f_status'=>'', 'f_price'=>'', 'f_mode'=>'', 'f_kyc'=>'', 'f_area'=>''];
$PM = alist_filters($PM_KEY, $PM_DEFAULTS);

$search    = $PM['search'];
$f_cat     = $PM['f_cat'];
$f_sub     = $PM['f_sub'];
$f_seller  = $PM['f_seller'];
$f_status  = $PM['f_status'];
$f_price   = $PM['f_price'];

$where = "1" . $PM_CATSQL; $params = [];
if ($search !== '') {
    $where .= " AND (ss.id = ? OR ss.title LIKE ? OR u.name LIKE ?)";
    $like = "%$search%";
    $params[] = intval(preg_replace('/\D/', '', $search));
    $params[] = $like; $params[] = $like;
}
if ($f_cat !== '')    { $where .= " AND ss.category_id = ?";     $params[] = intval($f_cat); }
if ($f_sub !== '')    { $where .= " AND ss.sub_category_id = ?"; $params[] = intval($f_sub); }
if ($f_seller !== '') { $where .= " AND ss.seller_id = ?";       $params[] = intval($f_seller); }
if ($f_status === '1' || $f_status === '0' || $f_status === '2') { $where .= " AND ss.status = ?"; $params[] = intval($f_status); }
if ($f_price === 'free') { $where .= " AND ss.discount_price <= 0"; }
elseif ($f_price === 'paid') { $where .= " AND ss.discount_price > 0"; }
if ($PM['f_mode'] === 'amount')  { $where .= " AND ss.share_mode = 'amount'"; }
elseif ($PM['f_mode'] === 'percent') { $where .= " AND (ss.share_mode IS NULL OR ss.share_mode <> 'amount')"; }
if ($PM['f_kyc'] === 'yes') { $where .= " AND ss.required_kyc IS NOT NULL AND ss.required_kyc <> ''"; }
elseif ($PM['f_kyc'] === 'no') { $where .= " AND (ss.required_kyc IS NULL OR ss.required_kyc = '')"; }
if ($PM['f_area'] === 'restricted') { $where .= " AND ss.area_mode <> 'all'"; }
elseif ($PM['f_area'] === 'all') { $where .= " AND (ss.area_mode IS NULL OR ss.area_mode = 'all')"; }

/* ---------------- CSV EXPORT ---------------- */
if (isset($_GET['export'])) {
    $ex = $db->select(
        "SELECT ss.*, u.name AS seller_name, u.mobile AS seller_mobile,
                sc.title AS cat_name, sub.title AS sub_cat_name
         FROM seller_services ss
         LEFT JOIN users u ON ss.seller_id = u.id
         LEFT JOIN service_categories sc ON ss.category_id = sc.id
         LEFT JOIN agency_sub_categories sub ON ss.sub_category_id = sub.id
         WHERE $where ORDER BY ss.id DESC LIMIT 10000", $params);
    $bd = function ($r, $k, $what) {
        $b = (float)($r['discount_price'] > 0 ? $r['discount_price'] : $r['price']);
        $x = shares_breakdown($r, $b);
        return number_format($x[$k][$what], 2, '.', '');
    };
    alist_export_csv('product_list', [
        'ID' => 'id',
        'Product No' => function ($r) { return 'WBP' . str_pad($r['id'], 5, '0', STR_PAD_LEFT); },
        'Name' => 'title', 'Category' => 'cat_name', 'Sub Category' => 'sub_cat_name',
        'Seller' => 'seller_name', 'Seller Mobile' => 'seller_mobile',
        'MRP' => function ($r) { return number_format((float)$r['price'], 2, '.', ''); },
        'Discount Price' => function ($r) { return number_format((float)$r['discount_price'], 2, '.', ''); },
        'Share Mode' => function ($r) { return shares_mode($r) === 'amount' ? 'Fixed Amount' : 'Percentage'; },
        'Seller Share Rs'   => function ($r) use ($bd) { return $bd($r, 'seller', 'amount'); },
        'Seller Share %'    => function ($r) use ($bd) { return $bd($r, 'seller', 'percent'); },
        'Sub Discount Rs'   => function ($r) use ($bd) { return $bd($r, 'subscription', 'amount'); },
        'Referral Share Rs' => function ($r) use ($bd) { return $bd($r, 'referral', 'amount'); },
        'Staff Share Rs'    => function ($r) use ($bd) { return $bd($r, 'staff', 'amount'); },
        'Company Share Rs'  => function ($r) use ($bd) { return $bd($r, 'company', 'amount'); },
        'Required KYC' => 'required_kyc',
        'Area Mode' => 'area_mode',
        'Status' => function ($r) { $x = (int)$r['status']; return $x === 1 ? 'Active' : ($x === 2 ? 'Rejected' : 'Pending'); },
        'Created' => 'created_at',
    ], $ex);
}

$products = $db->select(
    "SELECT ss.*, u.name AS seller_name, u.mobile AS seller_mobile, u.email AS seller_email,
            u.call_number, u.whatsapp_number,
            sc.title AS cat_name, sub.title AS sub_cat_name
     FROM seller_services ss
     LEFT JOIN users u ON ss.seller_id = u.id
     LEFT JOIN service_categories sc ON ss.category_id = sc.id
     LEFT JOIN agency_sub_categories sub ON ss.sub_category_id = sub.id
     WHERE $where ORDER BY ss.id DESC", $params);

$cats     = $db->select("SELECT id, title FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
/* The government page only ever offers the Government Portals category, and the
   agency page never offers it — so a product cannot slip from one page to the other. */
$cats = array_values(array_filter($cats, function ($c) use ($IS_GOV) {
    return $IS_GOV ? ((int)$c['id'] === 1) : ((int)$c['id'] !== 1);
}));
$subcats  = $db->select("SELECT id, category_id, title FROM agency_sub_categories WHERE status = 1 ORDER BY category_id, id");

/* Everything an admin can tick in Customer Data Recruitment: the standard KYC
   boxes, one by one, plus the questions written in admin/kyc_fields.php */
$KYC_TREE = kycf_catalog($db);

/* States, for the "available in these states" area mode */
$IN_STATES = ['Andaman and Nicobar Islands','Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chandigarh',
    'Chhattisgarh','Dadra and Nagar Haveli and Daman and Diu','Delhi','Goa','Gujarat','Haryana','Himachal Pradesh',
    'Jammu and Kashmir','Jharkhand','Karnataka','Kerala','Ladakh','Lakshadweep','Madhya Pradesh','Maharashtra',
    'Manipur','Meghalaya','Mizoram','Nagaland','Odisha','Puducherry','Punjab','Rajasthan','Sikkim','Tamil Nadu',
    'Telangana','Tripura','Uttar Pradesh','Uttarakhand','West Bengal'];
$sellers  = $db->select("SELECT DISTINCT u.id, u.name FROM users u JOIN seller_services s ON s.seller_id = u.id ORDER BY u.name ASC");

$all_ids = array_map('intval', array_column($products, 'id'));

// Actual paid-out totals from the share ledger (real earnings, not just settings)
$ledger_totals = [];
try {
    foreach ($db->select("SELECT share_type, SUM(amount) AS total, COUNT(*) AS cnt FROM product_share_ledger GROUP BY share_type") as $lt) {
        $ledger_totals[$lt['share_type']] = ['total' => (float)$lt['total'], 'cnt' => (int)$lt['cnt']];
    }
} catch (\Throwable $e) {}
function lt($arr, $k) { return isset($arr[$k]) ? $arr[$k] : ['total' => 0, 'cnt' => 0]; }

/* ---------------------------------------------------------------------------
   Government portal headline numbers. Every portal here is free, so the five
   rupee cards say nothing useful. These four do: how many portals exist, how
   many are live, how many are switched off, and whether anybody has asked for
   a portal that is not on the site yet (a website_requests row).
   --------------------------------------------------------------------------- */
$gov_cards = [];
if ($IS_GOV) {
    $g_total = $g_live = $g_off = $g_req = 0;
    try {
        $r = $db->select("SELECT COUNT(*) t, SUM(status = 1) a, SUM(status <> 1) i
                          FROM seller_services WHERE category_id = 1");
        if (!empty($r)) { $g_total = (int)$r[0]['t']; $g_live = (int)$r[0]['a']; $g_off = (int)$r[0]['i']; }
    } catch (\Throwable $e) {}
    try {
        $r = $db->select("SELECT COUNT(*) c FROM website_requests WHERE status = 'Pending'");
        if (!empty($r)) { $g_req = (int)$r[0]['c']; }
    } catch (\Throwable $e) {}

    $gov_cards = [
        ['Total portals',   $g_total, 'text-slate-700 bg-slate-100',     'fa-landmark',     $PM_SELF],
        ['Active',          $g_live,  'text-emerald-700 bg-emerald-100', 'fa-circle-check', $PM_SELF . '?f=' . $PM_KEY . '&f_status=1'],
        ['Inactive',        $g_off,   'text-slate-600 bg-slate-100',     'fa-circle-pause', $PM_SELF . '?f=' . $PM_KEY . '&f_status=0'],
        ['Portal requests', $g_req,   'text-amber-700 bg-amber-100',     'fa-inbox',        'website_requests.php'],
    ];
}
$filters_on = ($search !== '' || $f_cat !== '' || $f_sub !== '' || $f_seller !== '' || $f_status !== '' || $f_price !== '');

$user = $db->select("SELECT * FROM users WHERE id = ?", [$user_id])[0] ?? ['name' => 'Admin', 'profile_pic' => ''];
$raw_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

function pcode($id) { return str_pad(1000 + (int)$id, 4, '0', STR_PAD_LEFT); }
function amt($base, $pct) { return ((float)$base * (float)$pct) / 100; }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($PM_TITLE); ?> - Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .hide-scrollbar::-webkit-scrollbar { display: none; }
        .cell-btn { display:block; width:100%; text-align:center; font-size:10px; font-weight:700; padding:3px 6px; border-radius:4px; color:#fff; white-space:nowrap; }
        .pending-tag { display:inline-block; font-size:9px; font-weight:700; color:#b45309; background:#fef3c7; border:1px dashed #f59e0b; padding:1px 6px; border-radius:9999px; }
        table.pm { border: 2px solid #cbd5e1; }
        table.pm th, table.pm td { border: 1px solid #e2e8f0; vertical-align: top; }
        .fld { width:100%; border:1px solid #cbd5e1; border-radius:0.5rem; padding:0.5rem 0.75rem; font-size:0.875rem; outline:none; }
        .fld:focus { box-shadow:0 0 0 2px rgba(16,185,129,0.4); border-color:#10b981; }
        .lbl { display:block; font-size:0.7rem; font-weight:700; color:#475569; text-transform:uppercase; margin-bottom:0.25rem; }
        .pct { font-weight:800; color:#0f172a; }
        .pct-amt { font-size:10px; color:#059669; font-weight:700; }
    </style>
</head>
<body class="bg-gray-50" x-data="pmApp()">
<div class="flex h-screen overflow-hidden">

        <?php include __DIR__ . '/includes/sidebar.php'; ?>
    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
        <header class="h-20 bg-white flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40">
            <div class="flex items-center">
                <button @click="sidebarOpen=!sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
                <h2 class="text-xl font-bold hidden md:block text-slate-800"><?php echo htmlspecialchars($PM_TITLE); ?></h2>
            </div>
            <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                <img src="<?php echo $profile_image_url; ?>" class="w-10 h-10 rounded-full border-2 border-emerald-100 object-cover">
            <?php else: ?>
                <div class="w-10 h-10 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center font-bold"><?php echo strtoupper(substr($user['name'],0,1)); ?></div>
            <?php endif; ?>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6">

            <div class="mb-5 flex flex-col md:flex-row md:justify-between md:items-center gap-3">
                <div>
                    <h2 class="text-2xl font-bold text-slate-800 mb-1"><?php echo $IS_GOV ? 'Government Portal Management' : 'Product &amp; Service Management'; ?></h2>
                    <p class="text-xs text-slate-400 mb-3"><?php echo htmlspecialchars($PM_SUB); ?></p>
                    <p class="text-gray-500 text-sm">All products/services with pricing, share breakdown, notes &amp; updates.</p>
                </div>
                <div class="flex items-center gap-2">
                    <button type="button" @click="openAddSvc()" class="flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-indigo-600 to-blue-600 text-white rounded-xl text-sm font-bold shadow hover:shadow-lg transition">
                        <i class="fas fa-plus"></i> <?php echo $IS_GOV ? 'Add Portal' : 'Add Product'; ?>
                    </button>
                    <a href="service_import.php" class="flex items-center gap-2 px-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm font-semibold text-slate-600 shadow-sm hover:border-emerald-300">
                        <i class="fas fa-file-import text-emerald-500"></i> Bulk Upload
                    </a>
                    <button type="button" @click="filtersOpen = !filtersOpen" class="flex items-center gap-2 px-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm font-semibold text-slate-600 shadow-sm hover:border-indigo-300">
                        <i class="fas fa-sliders text-indigo-500"></i> Filters
                        <?php if($filters_on): ?><span class="w-2 h-2 rounded-full bg-indigo-500"></span><?php endif; ?>
                        <i class="fas fa-chevron-down text-xs" :class="filtersOpen ? 'rotate-180' : ''"></i>
                    </button>
                    <form method="GET" class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none"><i class="fas fa-search text-slate-400"></i></div>
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="<?php echo $IS_GOV ? 'Search portal name or ID...' : 'Search No, Name, Seller...'; ?>" class="w-full md:w-64 pl-10 pr-10 py-2.5 bg-white border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500 shadow-sm">
                        <?php foreach(['f_cat'=>$f_cat,'f_sub'=>$f_sub,'f_seller'=>$f_seller,'f_status'=>$f_status,'f_price'=>$f_price] as $k=>$v): if($v!==''): ?><input type="hidden" name="<?php echo $k; ?>" value="<?php echo htmlspecialchars($v); ?>"><?php endif; endforeach; ?>
                        <?php if($search!==''): ?><a href="<?php echo $PM_SELF; ?>" class="absolute inset-y-0 right-0 pr-3.5 flex items-center text-slate-400 hover:text-rose-500"><i class="fas fa-times-circle text-lg"></i></a><?php endif; ?>
                    </form>
                </div>
            </div>

            <?php if ($IS_GOV): ?>
            <!-- Counts, not rupees — a government portal is always free -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
                <?php foreach ($gov_cards as $gc): ?>
                    <a href="<?php echo htmlspecialchars($gc[4]); ?>" class="bg-white border border-slate-200 rounded-xl p-3.5 shadow-sm hover:border-indigo-300 transition-colors block">
                        <span class="w-8 h-8 rounded-lg flex items-center justify-center <?php echo $gc[2]; ?> mb-2"><i class="fas <?php echo $gc[3]; ?> text-xs"></i></span>
                        <p class="text-2xl font-extrabold text-slate-800 leading-none"><?php echo number_format($gc[1]); ?></p>
                        <p class="text-[10px] text-slate-500 font-semibold mt-1"><?php echo $gc[0]; ?></p>
                    </a>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <!-- LIVE PAID-OUT SUMMARY (from product_share_ledger) -->
            <div class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-5">
                <?php
                $sum_cards = [
                    ['Seller Paid',        'seller',                'text-slate-700 bg-slate-100',     'fa-store'],
                    ['Subscriber Savings', 'subscription_discount', 'text-indigo-700 bg-indigo-100',   'fa-crown'],
                    ['Referral Paid',      'referral',              'text-emerald-700 bg-emerald-100', 'fa-user-group'],
                    ['Staff Payable',      'staff',                 'text-amber-700 bg-amber-100',     'fa-user-tie'],
                    ['Company Profit',     'company',               'text-rose-700 bg-rose-100',       'fa-building'],
                ];
                foreach ($sum_cards as $sc): $d = lt($ledger_totals, $sc[1]); ?>
                    <div class="bg-white border border-slate-200 rounded-xl p-3.5 shadow-sm">
                        <span class="w-8 h-8 rounded-lg flex items-center justify-center <?php echo $sc[2]; ?> mb-2"><i class="fas <?php echo $sc[3]; ?> text-xs"></i></span>
                        <p class="text-lg font-extrabold text-slate-800 leading-none">₹<?php echo number_format($d['total'], 2); ?></p>
                        <p class="text-[10px] text-slate-500 font-semibold mt-1"><?php echo $sc[0]; ?> <span class="text-slate-400">(<?php echo $d['cnt']; ?>)</span></p>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- FILTER PANEL -->
            <div x-show="filtersOpen" x-transition style="display:none;" class="mb-5 bg-white border border-slate-200 rounded-2xl shadow-sm p-4">
                <form method="GET" class="grid grid-cols-2 lg:grid-cols-4 xl:grid-cols-5 gap-3 items-end">
                    <input type="hidden" name="f" value="<?php echo htmlspecialchars($PM_KEY); ?>">
                    <div class="col-span-2 lg:col-span-1">
                        <label class="lbl">Search</label>
                        <input name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="<?php echo $IS_GOV ? 'Portal name or product ID' : 'No, name or seller'; ?>" class="fld bg-slate-50">
                    </div>
                    <?php if (!$IS_GOV): /* everything here IS the one category */ ?>
                    <div>
                        <label class="lbl">Category</label>
                        <select name="f_cat" class="fld bg-slate-50">
                            <option value="">All Categories</option>
                            <?php foreach($cats as $c): ?><option value="<?php echo $c['id']; ?>" <?php echo $f_cat===(string)$c['id']?'selected':''; ?>><?php echo esc($c['title']); ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    <div>
                        <label class="lbl">Sub Category</label>
                        <select name="f_sub" class="fld bg-slate-50">
                            <option value="">All Sub Categories</option>
                            <?php foreach($subcats as $c): ?><option value="<?php echo $c['id']; ?>" <?php echo $f_sub===(string)$c['id']?'selected':''; ?>><?php echo esc($c['title']); ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <?php if (!$IS_GOV): /* portals belong to the company */ ?>
                    <div>
                        <label class="lbl">Seller</label>
                        <select name="f_seller" class="fld bg-slate-50">
                            <option value="">All Sellers</option>
                            <?php foreach($sellers as $sl): ?><option value="<?php echo $sl['id']; ?>" <?php echo $f_seller===(string)$sl['id']?'selected':''; ?>><?php echo esc($sl['name']); ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    <div>
                        <label class="lbl">Status</label>
                        <select name="f_status" class="fld bg-slate-50">
                            <option value="">All Status</option>
                            <option value="1" <?php echo $f_status==='1'?'selected':''; ?>>Active</option>
                            <option value="0" <?php echo $f_status==='0'?'selected':''; ?>>Pending / Inactive</option>
                            <option value="2" <?php echo $f_status==='2'?'selected':''; ?>>Rejected</option>
                        </select>
                    </div>
                    <?php if (!$IS_GOV): /* free by definition, no shares, no area rules */ ?>
                    <div>
                        <label class="lbl">Price</label>
                        <select name="f_price" class="fld bg-slate-50">
                            <option value="">Any Price</option>
                            <option value="free" <?php echo $f_price==='free'?'selected':''; ?>>Free</option>
                            <option value="paid" <?php echo $f_price==='paid'?'selected':''; ?>>Paid</option>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Share Mode</label>
                        <select name="f_mode" class="fld bg-slate-50">
                            <option value="">Any Mode</option>
                            <option value="percent" <?php echo $PM['f_mode']==='percent'?'selected':''; ?>>Percentage</option>
                            <option value="amount"  <?php echo $PM['f_mode']==='amount'?'selected':''; ?>>Fixed Amount</option>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Required KYC</label>
                        <select name="f_kyc" class="fld bg-slate-50">
                            <option value="">Any</option>
                            <option value="yes" <?php echo $PM['f_kyc']==='yes'?'selected':''; ?>>KYC required</option>
                            <option value="no"  <?php echo $PM['f_kyc']==='no'?'selected':''; ?>>No KYC</option>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Service Area</label>
                        <select name="f_area" class="fld bg-slate-50">
                            <option value="">Any</option>
                            <option value="restricted" <?php echo $PM['f_area']==='restricted'?'selected':''; ?>>Pincode restricted</option>
                            <option value="all"        <?php echo $PM['f_area']==='all'?'selected':''; ?>>All India</option>
                        </select>
                    </div>
                    <?php endif; ?>
                    <div class="col-span-2 lg:col-span-1 flex gap-2">
                        <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-4 py-2.5 rounded-lg text-xs flex-1"><i class="fas fa-filter mr-1"></i>Apply</button>
                        <a href="<?php echo $PM_SELF; ?>?reset=1" class="px-3 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold rounded-lg text-xs flex items-center">Reset</a>
                    </div>
                    <div class="col-span-2 lg:col-span-1">
                        <a href="<?php echo alist_url($PM_SELF,$PM_KEY,$PM,['export'=>1]); ?>" class="block text-center bg-emerald-600 hover:bg-emerald-700 text-white font-bold px-4 py-2.5 rounded-lg text-xs"><i class="fas fa-file-csv mr-1"></i>Export CSV</a>
                    </div>
                </form>
            </div>

            <?php if ($success_msg): ?><div class="mb-4 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm"><i class="fas fa-check-circle text-xl mr-3"></i><span class="font-medium"><?php echo $success_msg; ?></span></div><?php endif; ?>
            <?php if ($error_msg): ?><div class="mb-4 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm"><i class="fas fa-exclamation-circle text-xl mr-3"></i><span class="font-medium"><?php echo $error_msg; ?></span></div><?php endif; ?>

            <!-- BULK BAR -->
            <div x-show="selected.length > 0" x-transition style="display:none;" class="mb-4 bg-slate-800 text-white rounded-2xl shadow-lg px-4 py-3 flex flex-col sm:flex-row sm:items-center gap-3">
                <div class="flex items-center gap-2 font-semibold text-sm">
                    <span class="w-7 h-7 rounded-full bg-indigo-500 flex items-center justify-center text-xs font-bold" x-text="selected.length"></span> product(s) selected
                </div>
                <div class="flex flex-wrap items-center gap-2 sm:ml-auto">
                    <button type="button" @click="selected = [...allIds]" class="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-xs font-bold"><i class="fas fa-check-double mr-1"></i>Select All</button>
                    <button type="button" @click="selected = []" class="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-xs font-bold"><i class="fas fa-xmark mr-1"></i>Clear</button>
                    <button type="button" @click="bulkConfirm = true" class="px-4 py-1.5 rounded-lg bg-red-600 hover:bg-red-700 text-xs font-bold shadow"><i class="fas fa-trash-alt mr-1"></i>Delete Selected</button>
                </div>
            </div>

            <?php echo alist_banner($PM_SELF, $PM_KEY, $PM, $PM_DEFAULTS, [
                'search'=>'Search','f_cat'=>'Category','f_sub'=>'Sub Cat','f_seller'=>'Seller',
                'f_status'=>'Status','f_price'=>'Price','f_mode'=>'Share mode','f_kyc'=>'KYC','f_area'=>'Area']); ?>
            <?php echo alist_styles(); ?>
            <div class="bg-white rounded-2xl shadow-sm border-2 border-slate-300 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="pm w-full text-left border-collapse text-xs">
                        <thead>
                            <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider">
                                <th class="p-3 w-10">
                                    <input type="checkbox" class="w-4 h-4 rounded border-slate-300 text-indigo-600" :checked="allIds.length > 0 && selected.length === allIds.length" @change="selected = $event.target.checked ? [...allIds] : []">
                                </th>
                                <th class="p-3 font-semibold">Product &amp; Service No.<br>Date &amp; Time</th>
                                <th class="p-3 font-semibold">Category &amp;<br>Sub Category</th>
                                <th class="p-3 font-semibold">Product /<br>Service Name</th>
                                <?php if (!$IS_GOV): /* a government portal is free, so none of these apply */ ?>
                                <?php if (pm_col('mrp')): ?><th class="p-3 font-semibold">MRP</th><?php endif; ?>
                                <?php if (pm_col('discount')): ?><th class="p-3 font-semibold">Discount<br>Price</th><?php endif; ?>
                                <?php if (pm_col('seller')): ?><th class="p-3 font-semibold">Seller<br>Details</th><?php endif; ?>
                                <?php if (pm_col('seller_share')): ?><th class="p-3 font-semibold">Seller<br>Share</th><?php endif; ?>
                                <?php if (pm_col('sub_share')): ?><th class="p-3 font-semibold">Discount Share<br>(Subscription)</th><?php endif; ?>
                                <?php if (pm_col('referral_share')): ?><th class="p-3 font-semibold">Referral<br>Share</th><?php endif; ?>
                                <?php if (pm_col('staff_share')): ?><th class="p-3 font-semibold">Staff<br>Share</th><?php endif; ?>
                                <?php if (pm_col('company_share')): ?><th class="p-3 font-semibold">Company<br>Share</th><?php endif; ?>
                                <?php if (pm_col('quick')): ?><th class="p-3 font-semibold min-w-[110px]">Quick Response</th><?php endif; ?>
                                <?php else: ?>
                                <?php if (pm_col('links')): ?><th class="p-3 font-semibold min-w-[130px]">Portal Links</th><?php endif; ?>
                                <?php if (pm_col('customer_data')): ?><th class="p-3 font-semibold min-w-[110px]">Customer Data</th><?php endif; ?>
                                <?php endif; ?>
                                <?php if (pm_col('update')): ?><th class="p-3 font-semibold min-w-[130px]">Update</th><?php endif; ?>
                                <?php if (pm_col('notes')): ?><th class="p-3 font-semibold min-w-[110px]">Notes</th><?php endif; ?>
                                <?php if (pm_col('action')): ?><th class="p-3 font-semibold min-w-[110px]">Action</th><?php endif; ?>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                        <?php if(!empty($products)): foreach($products as $p):
                            $base   = (float)($p['discount_price'] > 0 ? $p['discount_price'] : $p['price']);
                            $jsName = htmlspecialchars(addslashes(html_entity_decode((string)$p['title'], ENT_QUOTES | ENT_HTML5, 'UTF-8')), ENT_QUOTES);
                            $call   = !empty($p['call_number']) ? $p['call_number'] : $p['seller_mobile'];
                            $wa     = !empty($p['whatsapp_number']) ? $p['whatsapp_number'] : $p['seller_mobile'];
                            $bd     = shares_breakdown($p, $base);
                            $pmode  = shares_mode($p);
                            $shares = [];
                            foreach ([
                                ['seller',       'text-slate-800',  'seller_share'],
                                ['subscription', 'text-indigo-700', 'sub_share'],
                                ['referral',     'text-emerald-700','referral_share'],
                                ['staff',        'text-amber-700',  'staff_share'],
                                ['company',      'text-rose-700',   'company_share'],
                            ] as $__sh) { if (pm_col($__sh[2])) { $shares[] = $__sh; } }
                        ?>
                            <tr class="hover:bg-slate-50/50 transition align-top" :class="selected.includes(<?php echo $p['id']; ?>) ? 'bg-indigo-50/40' : ''">
                                <td class="p-3"><input type="checkbox" :value="<?php echo $p['id']; ?>" x-model.number="selected" class="w-4 h-4 rounded border-slate-300 text-indigo-600"></td>

                                <!-- Product number + date/time -->
                                <td class="p-3">
                                    <p class="font-bold text-slate-800"><?php echo pcode($p['id']); ?></p>
                                    <p class="text-slate-500"><?php echo date('d/m/Y', strtotime($p['created_at'])); ?></p>
                                    <p class="text-slate-500"><?php echo date('h:i A', strtotime($p['created_at'])); ?></p>
                                </td>

                                <!-- Category / sub category -->
                                <td class="p-3">
                                    <p class="font-semibold text-slate-700 uppercase"><?php echo esc($p['cat_name'] ?: '—'); ?></p>
                                    <p class="text-slate-500 uppercase"><?php echo esc($p['sub_cat_name'] ?: '—'); ?></p>
                                </td>

                                <!-- Name -->
                                <td class="p-3">
                                    <p class="font-bold text-slate-800 uppercase"><?php echo esc($p['title']); ?></p>
                                    <span class="inline-block mt-1 px-1.5 py-0.5 rounded text-[9px] font-black uppercase <?php echo $pmode === 'amount' ? 'bg-emerald-100 text-emerald-700' : 'bg-indigo-100 text-indigo-700'; ?>">
                                        <?php echo $pmode === 'amount' ? '₹ Fixed' : '% Percent'; ?>
                                    </span>
                                </td>

                                <?php if (!$IS_GOV): ?>
                                <!-- MRP / Discount price -->
                                <?php if (pm_col('mrp')): ?><td class="p-3"><span class="text-slate-500 line-through">₹<?php echo number_format((float)$p['price'], 2); ?></span></td><?php endif; ?>
                                <?php if (pm_col('discount')): ?><td class="p-3"><span class="font-bold text-emerald-600">₹<?php echo number_format((float)$p['discount_price'], 2); ?></span></td><?php endif; ?>

                                <!-- Seller details -->
                                <?php if (pm_col('seller')): ?>
                                <td class="p-3">
                                    <p class="font-semibold text-slate-700"><?php echo esc($p['seller_name'] ?: '—'); ?></p>
                                    <p class="text-slate-500"><?php echo htmlspecialchars($p['seller_mobile'] ?: ''); ?></p>
                                </td>
                                <?php endif; ?>

                                <!-- Share columns: % + calculated amount -->
                                <?php foreach($shares as $sh):
                                    $sv = $bd[$sh[0]];
                                ?>
                                <td class="p-3 whitespace-nowrap">
                                    <?php if($pmode === 'amount'): ?>
                                        <p class="pct <?php echo $sh[1]; ?>">₹<?php echo number_format($sv['amount'], 2); ?></p>
                                        <p class="pct-amt"><?php echo rtrim(rtrim(number_format($sv['percent'], 2), '0'), '.'); ?>%</p>
                                    <?php else: ?>
                                        <p class="pct <?php echo $sh[1]; ?>"><?php echo rtrim(rtrim(number_format($sv['percent'], 2), '0'), '.'); ?>%</p>
                                        <p class="pct-amt">₹<?php echo number_format($sv['amount'], 2); ?></p>
                                    <?php endif; ?>
                                </td>
                                <?php endforeach; ?>

                                <?php if (pm_col('quick')): ?>
                                <!-- Quick response — sellers only -->
                                <td class="p-3 space-y-1">
                                    <a href="tel:<?php echo htmlspecialchars($call); ?>" class="cell-btn bg-slate-500 hover:bg-slate-600"><i class="fas fa-phone-alt mr-1"></i>Call</a>
                                    <a href="https://wa.me/91<?php echo preg_replace('/\D/','',$wa); ?>" target="_blank" class="cell-btn bg-green-500 hover:bg-green-600"><i class="fab fa-whatsapp mr-1"></i>Whatsapp</a>
                                    <a href="mailto:<?php echo htmlspecialchars($p['seller_email']); ?>" class="cell-btn bg-rose-600 hover:bg-rose-700"><i class="fas fa-envelope mr-1"></i>Email</a>
                                    <span class="cell-btn bg-purple-300 cursor-not-allowed" title="Chatbot integration pending"># Chatbot</span>
                                </td>
                                <?php endif; ?>

                                                                <?php else: ?>

                                <?php if (pm_col('links')): ?>
                                <!-- Portal links — what a government portal actually needs -->
                                <td class="p-3 space-y-1">
                                    <?php if (!empty($p['web_url'])): ?>
                                        <a href="<?php echo htmlspecialchars($p['web_url']); ?>" target="_blank" rel="noopener" class="cell-btn bg-sky-600 hover:bg-sky-700"><i class="fas fa-globe mr-1"></i>Website</a>
                                    <?php endif; ?>
                                    <?php if (!empty($p['app_url'])): ?>
                                        <a href="<?php echo htmlspecialchars($p['app_url']); ?>" target="_blank" rel="noopener" class="cell-btn bg-emerald-600 hover:bg-emerald-700"><i class="fas fa-mobile-screen mr-1"></i>App</a>
                                    <?php endif; ?>
                                    <?php if (!empty($p['tutorial_url'])): ?>
                                        <a href="<?php echo htmlspecialchars($p['tutorial_url']); ?>" target="_blank" rel="noopener" class="cell-btn bg-rose-600 hover:bg-rose-700"><i class="fas fa-circle-play mr-1"></i>Tutorial</a>
                                    <?php endif; ?>
                                    <?php if (empty($p['web_url']) && empty($p['app_url']) && empty($p['tutorial_url'])): ?>
                                        <span class="text-slate-300">No link added yet</span>
                                    <?php endif; ?>
                                </td>
                                <?php endif; ?>

                                                                <?php if (pm_col('customer_data')): ?>
                                <!-- What the customer must supply -->
                                <td class="p-3">
                                    <?php
                                        $gk = trim((string)($p['required_kyc'] ?? ''));
                                        $gn = $gk === '' ? 0 : count(explode(',', $gk));
                                        $gp = 0;
                                        try { $gp = (int)($db->select("SELECT COUNT(*) c FROM product_areas WHERE service_id = ? AND service_type='seller'", [$p['id']])[0]['c'] ?? 0); } catch (\Throwable $e) {}
                                    ?>
                                    <p class="font-semibold text-slate-700"><?php echo $gn; ?> KYC field<?php echo $gn === 1 ? '' : 's'; ?></p>
                                    <p class="text-slate-500"><?php echo $gp > 0 ? $gp . ' area(s)' : 'All India'; ?></p>
                                </td>
                                <?php endif; ?>

                                                                <?php endif; ?>

                                <?php if (pm_col('update')): ?>
                                <!-- Update -->
                                <td class="p-3 space-y-1">
                                    <button type="button" @click="openHistory(<?php echo $p['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-orange-500 hover:bg-orange-600"><i class="fas fa-clock-rotate-left mr-1"></i>Update History</button>
                                    <button type="button" @click="openEditSvc(<?php echo $p['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-sky-600 hover:bg-sky-700" title="Edit name, links, image, category"><i class="fas fa-pen-to-square mr-1"></i>Edit Product</button>
                                    <?php if (!$IS_GOV): ?><button type="button" @click="openUpdate(<?php echo $p['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-lime-600 hover:bg-lime-700"><i class="fas fa-percent mr-1"></i>Price &amp; Share</button><?php endif; ?>
                                    <?php
                                        $rk    = trim((string)($p['required_kyc'] ?? ''));
                                        $nkyc  = $rk === '' ? 0 : count(explode(',', $rk));
                                        $npin  = 0;
                                        try { $npin = (int)($db->select("SELECT COUNT(*) c FROM product_areas WHERE service_id = ? AND service_type='seller'", [$p['id']])[0]['c'] ?? 0); } catch (\Throwable $e) {}
                                    ?>
                                    <button type="button" @click="openRecruit(<?php echo $p['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-indigo-600 hover:bg-indigo-700" title="Required KYC & serviceable area">
                                        <i class="fas fa-user-shield mr-1"></i>Customer Data<?php if($nkyc || $npin): ?> <span class="opacity-80">(<?php echo $nkyc; ?>K/<?php echo $npin; ?>P)</span><?php endif; ?>
                                    </button>
                                </td>
                                <?php endif; ?>

                                                                <?php if (pm_col('notes')): ?>
                                <!-- Notes -->
                                <td class="p-3 space-y-1">
                                    <button type="button" @click="openNotes(<?php echo $p['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-cyan-500 hover:bg-cyan-600"><i class="fas fa-clock-rotate-left mr-1"></i>Note History</button>
                                    <button type="button" @click="openNewNote(<?php echo $p['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-amber-500 hover:bg-amber-600"><i class="fas fa-plus mr-1"></i>Note</button>
                                    <span class="cell-btn bg-pink-200 text-pink-700 cursor-not-allowed" title="Not available yet"># Discount Offer</span>
                                </td>
                                <?php endif; ?>

                                                                <?php if (pm_col('action')): ?>
                                <!-- Action -->
                                <td class="p-3 space-y-1">
                                    <form method="POST">
                                        <input type="hidden" name="service_id" value="<?php echo $p['id']; ?>">
                                        <input type="hidden" name="current_status" value="<?php echo $p['status']; ?>">
                                        <?php $__st = (int)$p['status']; ?>
                                        <button type="submit" name="toggle_status" class="cell-btn <?php echo $__st===1 ? 'bg-emerald-500 hover:bg-emerald-600' : ($__st===2 ? 'bg-rose-500 hover:bg-rose-600' : 'bg-amber-500 hover:bg-amber-600'); ?>" title="<?php echo $__st===2 ? 'Rejected in Pending Services — click to make live' : 'Click to toggle'; ?>">
                                            <?php echo $__st===1 ? 'Active' : ($__st===2 ? 'Rejected' : 'Pending'); ?>
                                        </button>
                                    </form>
                                    <form method="POST" onsubmit="return confirm('Delete this product permanently?');">
                                        <input type="hidden" name="service_id" value="<?php echo $p['id']; ?>">
                                        <button type="submit" name="delete_product" class="cell-btn bg-red-600 hover:bg-red-700"><i class="fas fa-trash-alt mr-1"></i>Delete</button>
                                    </form>
                                </td>
                                <?php endif; ?>
                                                        </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="<?php echo (int)$PM_SPAN; ?>" class="p-12 text-center text-gray-500">
                                <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-400 text-2xl border"><i class="fas fa-box-open"></i></div>
                                <p class="text-lg font-medium">No products found.</p>
                            </td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="mt-4 grid gap-3 md:grid-cols-2">
                <div class="bg-emerald-50 border border-emerald-200 rounded-xl p-4 text-xs text-emerald-800">
                    <p class="font-bold mb-1"><i class="fas fa-circle-check mr-1"></i> Live &amp; enforced</p>
                    <ul class="list-disc pl-4 space-y-0.5">
                        <li>Share % are calculated on the <b>discount price</b> (selling price). <b>Company Share is auto-derived</b> — 100% minus seller + subscription discount + referral + staff — and cannot be edited by hand.</li>
                        <li><b>Customer Data Recruitment</b> → <b>Required KYC</b>: a buyer must fill the ticked sections and be <b>approved</b>, otherwise a popup blocks the purchase.</li>
                        <li><b>Customer Data Recruitment</b> → <b>Available Area</b>: only users whose registration pincode is in the list can buy; everyone else sees “Not available in your area”.</li>
                    </ul>
                </div>
                <div class="bg-amber-50 border border-amber-200 rounded-xl p-4 text-xs text-amber-800">
                    <p class="font-bold mb-1"><i class="fas fa-info-circle mr-1"></i> Fields marked with <span class="pending-tag">#</span> are not yet available.</p>
                    <p>Pending client confirmation: <b>Discount Offer</b> and <b>Chatbot</b>.</p>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- ================= MODALS ================= -->
<template x-teleport="body">
<div x-show="modal" x-transition.opacity class="fixed inset-0 z-[100] flex items-center justify-center p-4" style="display:none;">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="close()"></div>

    <!-- NOTE HISTORY -->
    <div x-show="modal==='notes'" x-transition class="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-cyan-500 to-blue-500 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-clock-rotate-left mr-2"></i>Note History</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <div class="px-5 py-2 bg-cyan-50 text-cyan-800 text-xs font-semibold border-b border-cyan-100"><i class="fas fa-box mr-1"></i><span x-text="curName"></span></div>
        <div class="p-5 max-h-[60vh] overflow-y-auto">
            <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
            <div x-show="!loading && !viewNote">
                <template x-if="notes.length===0"><p class="text-center text-slate-400 py-8"><i class="fas fa-note-sticky text-2xl mb-2 block"></i>No notes yet.</p></template>
                <div class="space-y-2">
                    <template x-for="n in notes" :key="n.id">
                        <div class="flex items-center justify-between gap-3 p-3 rounded-xl border border-slate-100 bg-slate-50">
                            <div class="min-w-0">
                                <p class="font-bold text-slate-800 truncate" x-text="n.title"></p>
                                <p class="text-xs text-slate-500 mt-0.5"><i class="fas fa-user-pen mr-1"></i><span class="font-semibold text-indigo-600" x-text="n.created_by_name"></span> • <span x-text="fmt(n.created_at)"></span></p>
                            </div>
                            <button @click="viewNote=n" class="flex-shrink-0 text-xs font-bold text-white bg-cyan-500 hover:bg-cyan-600 px-3 py-1.5 rounded-lg"><i class="fas fa-eye mr-1"></i>View</button>
                        </div>
                    </template>
                </div>
            </div>
            <div x-show="viewNote" class="space-y-3">
                <button @click="viewNote=null" class="text-xs font-semibold text-slate-500 hover:text-cyan-600"><i class="fas fa-arrow-left mr-1"></i>Back</button>
                <h4 class="text-lg font-bold" x-text="viewNote?.title"></h4>
                <p class="text-xs text-slate-500"><span x-text="viewNote?.created_by_name"></span> • <span x-text="fmt(viewNote?.created_at)"></span></p>
                <div class="bg-slate-50 border rounded-xl p-4 text-sm whitespace-pre-wrap" x-text="viewNote?.description || '(no description)'"></div>
            </div>
        </div>
    </div>

    <!-- NEW NOTE -->
    <div x-show="modal==='newNote'" x-transition class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-plus mr-2"></i>New Note</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" class="p-5 space-y-4">
            <input type="hidden" name="service_id" :value="curId">
            <div><label class="lbl">Note Title <span class="text-rose-500">*</span></label><input name="note_title" required class="fld" placeholder="e.g. Commission revised"></div>
            <div><label class="lbl">Description</label><textarea name="note_description" rows="4" class="fld" placeholder="Write details..."></textarea></div>
            <div class="flex justify-end gap-2">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                <button type="submit" name="add_note" class="px-5 py-2 text-sm font-bold text-white bg-amber-500 hover:bg-amber-600 rounded-lg shadow">Submit</button>
            </div>
        </form>
    </div>

    <!-- UPDATE HISTORY -->
    <div x-show="modal==='history'" x-transition class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-orange-500 to-rose-500 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-clock-rotate-left mr-2"></i>Update History</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <div class="px-5 py-2 bg-orange-50 text-orange-800 text-xs font-semibold border-b"><i class="fas fa-box mr-1"></i><span x-text="curName"></span></div>
        <div class="p-5 max-h-[60vh] overflow-y-auto">
            <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
            <template x-if="!loading && history.length===0"><p class="text-center text-slate-400 py-8">No updates recorded yet.</p></template>
            <div x-show="!loading && history.length" class="overflow-x-auto">
                <table class="w-full text-left text-xs">
                    <thead><tr class="text-slate-500 uppercase text-[10px] border-b"><th class="py-2 pr-2">Field</th><th class="py-2 px-2">Old</th><th class="py-2 px-2">New</th><th class="py-2 px-2">By</th><th class="py-2 pl-2">When</th></tr></thead>
                    <tbody class="divide-y divide-slate-100">
                        <template x-for="h in history" :key="h.id">
                            <tr>
                                <td class="py-2 pr-2 font-bold text-slate-700" x-text="h.field_label"></td>
                                <td class="py-2 px-2 text-rose-500" x-text="h.old_value || '—'"></td>
                                <td class="py-2 px-2 text-emerald-600" x-text="h.new_value || '—'"></td>
                                <td class="py-2 px-2 font-semibold text-indigo-600" x-text="h.updated_by_name || '—'"></td>
                                <td class="py-2 pl-2 text-slate-500 whitespace-nowrap" x-text="fmt(h.updated_at)"></td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- CUSTOMER DATA RECRUITMENT -->
    <div x-show="modal==='recruit'" x-transition class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
        <div class="bg-gradient-to-r from-indigo-600 to-violet-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-user-shield mr-2"></i>Customer Data Recruitment</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <div class="px-5 py-2 bg-indigo-50 text-indigo-800 text-xs font-semibold border-b"><i class="fas fa-box mr-1"></i><span x-text="curName"></span></div>

        <!-- tabs -->
        <div class="flex border-b border-slate-200 flex-shrink-0">
            <button type="button" @click="rtab='kyc'" class="flex-1 py-3 text-sm font-bold transition-colors" :class="rtab==='kyc' ? 'text-indigo-600 border-b-2 border-indigo-600 bg-indigo-50/40' : 'text-slate-500 hover:bg-slate-50'"><i class="fas fa-id-card mr-1"></i> Required KYC</button>
            <button type="button" @click="rtab='area'" class="flex-1 py-3 text-sm font-bold transition-colors" :class="rtab==='area' ? 'text-indigo-600 border-b-2 border-indigo-600 bg-indigo-50/40' : 'text-slate-500 hover:bg-slate-50'"><i class="fas fa-location-dot mr-1"></i> Available Area</button>
        </div>

        <form method="POST" enctype="multipart/form-data" class="flex flex-col overflow-hidden">
            <input type="hidden" name="service_id" :value="curId">
            <div class="p-5 overflow-y-auto">
                <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>

                <!-- KYC TAB -->
                <div x-show="!loading && rtab==='kyc'" class="space-y-3">
                    <p class="text-xs text-slate-500">
                        Tick the exact boxes a customer <b>must fill and get approved</b> before buying this product.
                        Open a section to pick single lines — you do not have to demand the whole address just to get a pincode.
                    </p>

                    <div class="flex flex-wrap items-center gap-2">
                        <span class="text-[11px] font-bold text-slate-500">Ticked: <span x-text="picked.length"></span></span>
                        <button type="button" @click="picked = []" class="text-[11px] font-bold text-rose-600 hover:underline">Clear all</button>
                        <a href="kyc_fields.php" target="_blank" class="text-[11px] font-bold text-violet-600 hover:underline ml-auto">
                            <i class="fas fa-plus mr-1"></i>Write my own question
                        </a>
                    </div>

                    <?php foreach ($KYC_TREE as $__gk => $__g): ?>
                    <div class="border border-slate-200 rounded-xl overflow-hidden" x-data="{ open: false }">
                        <div class="flex items-center gap-2 px-3 py-2.5 bg-slate-50">
                            <i class="fas <?php echo esc($__g['icon']); ?> text-indigo-500 text-sm w-4"></i>
                            <span class="text-sm font-bold text-slate-700 flex-1"><?php echo esc($__g['label']); ?></span>
                            <span class="text-[10px] font-black px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700"
                                  x-text="countIn(<?php echo htmlspecialchars(json_encode(array_keys($__g['fields'])), ENT_QUOTES); ?>) + ' / <?php echo count($__g['fields']); ?>'"></span>
                            <button type="button" class="text-[11px] font-bold text-indigo-600"
                                    @click="toggleGroup(<?php echo htmlspecialchars(json_encode(array_keys($__g['fields'])), ENT_QUOTES); ?>)">All / none</button>
                            <button type="button" @click="open = !open" class="text-slate-400 hover:text-slate-600 w-6 text-center">
                                <i class="fas" :class="open ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
                            </button>
                        </div>
                        <div x-show="open" style="display:none" class="p-3 grid grid-cols-1 sm:grid-cols-2 gap-1.5">
                            <?php foreach ($__g['fields'] as $__fk => $__fl): ?>
                            <label class="flex items-center gap-2 px-2.5 py-2 rounded-lg border border-slate-100 hover:bg-slate-50 cursor-pointer">
                                <input type="checkbox" name="required_kyc[]" value="<?php echo esc($__fk); ?>"
                                       x-model="picked" class="w-4 h-4 rounded border-slate-300 text-indigo-600">
                                <span class="text-[12px] font-semibold text-slate-600"><?php echo esc($__fl); ?></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <div x-show="!open && countIn(<?php echo htmlspecialchars(json_encode(array_keys($__g['fields'])), ENT_QUOTES); ?>) > 0"
                             style="display:none" class="px-3 pb-2.5 -mt-0.5">
                            <p class="text-[10.5px] text-slate-400">
                                <?php echo esc($__g['label']); ?> — <span x-text="labelsIn(<?php echo htmlspecialchars(json_encode($__g['fields']), ENT_QUOTES); ?>)"></span>
                            </p>
                        </div>
                    </div>
                    <?php endforeach; ?>

                    <div class="bg-amber-50 border border-amber-200 rounded-xl p-3 text-[11px] text-amber-800">
                        <i class="fas fa-circle-info mr-1"></i>
                        The buyer's popup lists <b>only the ticked boxes they have not filled yet</b> — anything already in their
                        KYC is left out. Purchase stays blocked until the missing ones are filled and the KYC is approved.
                    </div>
                </div>

                <!-- AREA TAB -->
                <div x-show="!loading && rtab==='area'" class="space-y-4">
                    <p class="text-xs text-slate-500">Choose where this product is available. A customer outside that area sees <b>“Not available in your area”</b>.</p>
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
                        <label class="cursor-pointer">
                            <input type="radio" name="area_mode" value="all" x-model="rec.area_mode" class="peer sr-only">
                            <div class="p-3 rounded-xl border-2 text-center text-xs font-bold transition-all peer-checked:border-indigo-500 peer-checked:bg-indigo-50 peer-checked:text-indigo-700 border-slate-200 text-slate-500"><i class="fas fa-globe block text-lg mb-1"></i>All India</div>
                        </label>
                        <label class="cursor-pointer">
                            <input type="radio" name="area_mode" value="single" x-model="rec.area_mode" class="peer sr-only">
                            <div class="p-3 rounded-xl border-2 text-center text-xs font-bold transition-all peer-checked:border-indigo-500 peer-checked:bg-indigo-50 peer-checked:text-indigo-700 border-slate-200 text-slate-500"><i class="fas fa-location-pin block text-lg mb-1"></i>Single</div>
                        </label>
                        <label class="cursor-pointer">
                            <input type="radio" name="area_mode" value="bulk" x-model="rec.area_mode" class="peer sr-only">
                            <div class="p-3 rounded-xl border-2 text-center text-xs font-bold transition-all peer-checked:border-indigo-500 peer-checked:bg-indigo-50 peer-checked:text-indigo-700 border-slate-200 text-slate-500"><i class="fas fa-layer-group block text-lg mb-1"></i>Bulk pincode</div>
                        </label>
                        <label class="cursor-pointer">
                            <input type="radio" name="area_mode" value="state" x-model="rec.area_mode" class="peer sr-only">
                            <div class="p-3 rounded-xl border-2 text-center text-xs font-bold transition-all peer-checked:border-indigo-500 peer-checked:bg-indigo-50 peer-checked:text-indigo-700 border-slate-200 text-slate-500"><i class="fas fa-map block text-lg mb-1"></i>By State</div>
                        </label>
                    </div>

                    <div x-show="rec.area_mode==='single'">
                        <label class="lbl">Pincode</label>
                        <input name="single_pincode" maxlength="6" :value="(rec.pincodes && rec.pincodes.length) ? rec.pincodes[0] : ''" placeholder="e.g. 700010" class="fld">
                    </div>

                    <div x-show="rec.area_mode==='bulk'" class="space-y-2">
                        <label class="lbl">Pincodes (comma / space / new line separated)</label>
                        <textarea name="bulk_pincodes" rows="5" class="fld" placeholder="700010, 700011&#10;743502" :value="(rec.pincodes || []).join(', ')"></textarea>
                        <label class="lbl mt-2">Or upload a .txt / .csv file</label>
                        <input type="file" name="pincode_file" accept=".txt,.csv" class="w-full text-xs text-slate-600 file:mr-2 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:bg-indigo-50 file:text-indigo-700 file:font-semibold">
                    </div>

                    <div x-show="rec.area_mode==='state'" style="display:none" class="space-y-2">
                        <div class="flex items-center justify-between">
                            <label class="lbl mb-0">States this product serves</label>
                            <div class="flex gap-2">
                                <button type="button" class="text-[11px] font-bold text-indigo-600" @click="pickStates = allStates.slice()">Select all</button>
                                <button type="button" class="text-[11px] font-bold text-rose-600" @click="pickStates = []">Clear</button>
                            </div>
                        </div>
                        <input x-model="stateQuery" placeholder="Type to find a state…" class="fld">
                        <div class="max-h-56 overflow-y-auto border border-slate-200 rounded-xl p-2 grid grid-cols-1 sm:grid-cols-2 gap-1">
                            <?php foreach ($IN_STATES as $__st): ?>
                            <label class="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-slate-50 cursor-pointer"
                                   x-show="!stateQuery || '<?php echo esc(strtolower($__st)); ?>'.includes(stateQuery.toLowerCase())">
                                <input type="checkbox" name="states[]" value="<?php echo esc($__st); ?>" x-model="pickStates"
                                       class="w-4 h-4 rounded border-slate-300 text-indigo-600">
                                <span class="text-[12px] font-semibold text-slate-600"><?php echo esc($__st); ?></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <p class="text-[11px] text-slate-400">
                            <span x-text="pickStates.length"></span> state(s) selected. A customer's state comes from their profile,
                            and falls back to the state on their KYC address.
                        </p>
                    </div>

                    <div x-show="rec.states && rec.states.length" style="display:none" class="bg-emerald-50 border border-emerald-200 rounded-xl p-3">
                        <p class="text-[11px] font-bold text-emerald-700 uppercase mb-2">Currently allowed states (<span x-text="(rec.states||[]).length"></span>)</p>
                        <div class="flex flex-wrap gap-1.5 max-h-24 overflow-y-auto">
                            <template x-for="st in (rec.states||[])" :key="st"><span class="px-2 py-0.5 bg-white border border-emerald-200 rounded-md text-[11px] font-semibold text-emerald-700" x-text="st"></span></template>
                        </div>
                    </div>

                    <div x-show="rec.pincodes && rec.pincodes.length" class="bg-slate-50 border border-slate-200 rounded-xl p-3">
                        <p class="text-[11px] font-bold text-slate-500 uppercase mb-2">Currently serviceable (<span x-text="(rec.pincodes||[]).length"></span>)</p>
                        <div class="flex flex-wrap gap-1.5 max-h-28 overflow-y-auto">
                            <template x-for="p in (rec.pincodes||[])" :key="p"><span class="px-2 py-0.5 bg-white border border-slate-200 rounded-md text-[11px] font-semibold text-slate-600" x-text="p"></span></template>
                        </div>
                    </div>
                </div>
            </div>
            <div class="flex justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" name="save_recruitment" class="px-5 py-2 text-sm font-bold text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg shadow">Save Settings</button>
            </div>
        </form>
    </div>

    <!-- ================= FULL EDIT (same fields the seller has) ================= -->
    <div x-show="modal==='editsvc'" x-transition class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
        <div class="bg-gradient-to-r from-sky-600 to-blue-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <div class="min-w-0">
                <h3 class="text-white font-bold text-lg">
                    <i class="fas mr-2" :class="svcMode === 'add' ? 'fa-plus' : 'fa-pen-to-square'"></i>
                    <span x-text="svcMode === 'add' ? '<?php echo $IS_GOV ? 'Add Portal' : 'Add Product'; ?>' : 'Edit Product'"></span>
                </h3>
                <p class="text-white/70 text-[11px] truncate" x-text="svcMode === 'add' ? '<?php echo $IS_GOV ? 'It goes live in Government Portals straight away' : 'It goes live straight away'; ?>' : curName"></p>
            </div>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" enctype="multipart/form-data" class="flex flex-col overflow-hidden">
            <input type="hidden" name="service_id" :value="curId">
            <div class="p-5 overflow-y-auto space-y-4">
                <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading…</p></template>

                <div x-show="!loading" class="space-y-4">
                    <div><label class="lbl">Product / Service name</label><input name="title" x-model="esvc.title" class="fld" required></div>
                    <div><label class="lbl">Description</label><textarea name="description" x-model="esvc.description" rows="3" class="fld"></textarea></div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div><label class="lbl">Category</label>
                            <select name="category_id" x-model="esvc.category_id" class="fld" <?php echo $IS_GOV ? 'readonly onchange="this.value=1"' : ''; ?>>
                                <?php foreach ($cats as $c): ?>
                                    <option value="<?php echo (int)$c['id']; ?>"><?php echo esc($c['title']); ?></option>
                                <?php endforeach; ?>
                            </select></div>
                        <div><label class="lbl">Sub category</label>
                            <select name="sub_category_id" x-model="esvc.sub_category_id" class="fld">
                                <option value="0">— none —</option>
                                <template x-for="sc in subsFor(esvc.category_id)" :key="sc.id">
                                    <option :value="sc.id" x-text="sc.title"></option>
                                </template>
                            </select>
                            <p class="text-[10px] text-slate-400 mt-1">Sub categories are created in <a href="services.php#sub_cats" class="text-indigo-600 font-bold">Service Directory</a> — sellers cannot add them.</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-3" x-show="String(esvc.category_id) !== '1'">
                        <div><label class="lbl">MRP (₹)</label><input type="number" step="0.01" name="price" x-model="esvc.price" class="fld"></div>
                        <div><label class="lbl">Discount price (₹)</label><input type="number" step="0.01" name="discount_price" x-model="esvc.discount_price" class="fld"></div>
                    </div>
                    <p x-show="String(esvc.category_id) === '1'" style="display:none" class="text-[11px] text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-xl p-2.5">
                        <i class="fas fa-circle-info mr-1"></i>Government Portals are always free — the price is forced to ₹0.
                    </p>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div><label class="lbl">Website link</label><input name="web_url" x-model="esvc.web_url" class="fld" placeholder="https://"></div>
                        <div><label class="lbl">App link</label><input name="app_url" x-model="esvc.app_url" class="fld" placeholder="https://"></div>
                        <div><label class="lbl">Tutorial link</label><input name="tutorial_url" x-model="esvc.tutorial_url" class="fld" placeholder="https://youtu.be/…"></div>
                        <div><label class="lbl">Colour</label>
                            <select name="color_class" x-model="esvc.color_class" class="fld">
                                <template x-for="n in 8" :key="n"><option :value="'color-' + n" x-text="'color-' + n"></option></template>
                            </select></div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div><label class="lbl">Icon class or image URL</label>
                            <input name="icon_class" x-model="esvc.icon_class" class="fld" placeholder="fa-id-card  or  uploads/services/x.png"></div>
                        <div><label class="lbl">…or upload a new image</label>
                            <input type="file" name="image_upload" accept="image/*" class="fld !py-2"></div>
                    </div>

                    <div class="flex items-center gap-3">
                        <div class="w-14 h-14 rounded-xl border border-slate-200 flex items-center justify-center bg-slate-50 overflow-hidden flex-shrink-0">
                            <template x-if="isImg(esvc.icon_class)">
                                <img :src="(esvc.icon_class || '').startsWith('http') ? esvc.icon_class : '../' + (esvc.icon_class || '')" class="w-full h-full object-cover" alt="">
                            </template>
                            <template x-if="!isImg(esvc.icon_class)"><i class="fas text-xl text-indigo-500" :class="esvc.icon_class || 'fa-cube'"></i></template>
                        </div>
                        <div class="flex-1">
                            <label class="lbl">Status</label>
                            <select name="status" x-model="esvc.status" class="fld">
                                <option value="1">Approved / live</option>
                                <option value="0">Pending / hidden</option>
                            </select>
                        </div>
                    </div>

                    <p class="text-[10px] text-slate-400"><i class="fas fa-clock-rotate-left mr-1"></i>Every changed field is written to this product's update history.</p>
                </div>
            </div>
            <div class="flex justify-between gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                <button type="button" x-show="svcMode !== 'add'" @click="askDelete()" class="px-4 py-2 text-sm font-bold text-rose-600 hover:bg-rose-50 rounded-lg"><i class="fas fa-trash mr-1"></i>Delete</button>
                <div class="flex gap-2">
                    <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                    <button type="submit" :name="svcMode === 'add' ? 'add_service' : 'edit_service'" value="1" class="px-5 py-2 text-sm font-bold text-white bg-sky-600 hover:bg-sky-700 rounded-lg shadow">
                        <i class="fas fa-save mr-1"></i><span x-text="svcMode === 'add' ? 'Add now' : 'Save Product'"></span>
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- UPDATE PRODUCT -->
    <div x-show="modal==='update'" x-transition class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
        <div class="bg-gradient-to-r from-lime-600 to-emerald-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-pen mr-2"></i>Update — <span x-text="curName"></span></h3>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" class="flex flex-col overflow-hidden">
            <input type="hidden" name="service_id" :value="curId">
            <div class="p-5 overflow-y-auto space-y-4">
                <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
                <div x-show="!loading" class="space-y-4">
                    <div><label class="lbl">Product / Service Name</label><input name="title" x-model="form.title" class="fld"></div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="lbl">MRP (₹)</label><input type="number" step="0.01" name="price" x-model="form.price" class="fld"></div>
                        <div><label class="lbl">Discount Price (₹)</label><input type="number" step="0.01" name="discount_price" x-model="form.discount_price" class="fld"></div>
                    </div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-slate-500 border-b pb-1 pt-1">Share breakdown — calculated on the discount price (₹<span x-text="base().toFixed(2)"></span>)</p>

                    <!-- mode switch -->
                    <input type="hidden" name="share_mode" :value="form.share_mode || 'percent'">
                    <div class="grid grid-cols-2 gap-2">
                        <button type="button" @click="setMode('percent')"
                                class="py-2.5 rounded-xl text-xs font-black border-2 transition-all"
                                :class="mode()==='percent' ? 'border-indigo-500 bg-indigo-50 text-indigo-700' : 'border-slate-200 text-slate-500'">
                            <i class="fas fa-percent mr-1"></i> PERCENTAGE
                        </button>
                        <button type="button" @click="setMode('amount')"
                                class="py-2.5 rounded-xl text-xs font-black border-2 transition-all"
                                :class="mode()==='amount' ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-slate-200 text-slate-500'">
                            <i class="fas fa-indian-rupee-sign mr-1"></i> FIXED AMOUNT
                        </button>
                    </div>
                    <p class="text-[10px] text-slate-400 -mt-2" x-text="mode()==='amount' ? 'Type the rupee value for each share. Company share is whatever is left of the price.' : 'Type a percentage for each share. Company share is 100% minus the rest.'"></p>

                    <!-- PERCENT MODE -->
                    <div x-show="mode()==='percent'" class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div><label class="lbl">Seller Share %</label><input type="number" step="0.01" min="0" name="seller_share_pct" x-model="form.seller_share_pct" class="fld"><p class="text-[11px] text-emerald-600 font-bold mt-1">₹<span x-text="calc(form.seller_share_pct)"></span></p></div>
                        <div><label class="lbl">Discount Share (Subscription) %</label><input type="number" step="0.01" min="0" name="subscription_discount_pct" x-model="form.subscription_discount_pct" class="fld"><p class="text-[11px] text-emerald-600 font-bold mt-1">₹<span x-text="calc(form.subscription_discount_pct)"></span> <span class="text-slate-400 font-normal">(subscribed users only)</span></p></div>
                        <div><label class="lbl">Referral Share %</label><input type="number" step="0.01" min="0" name="referral_share_pct" x-model="form.referral_share_pct" class="fld"><p class="text-[11px] text-emerald-600 font-bold mt-1">₹<span x-text="calc(form.referral_share_pct)"></span></p></div>
                        <div><label class="lbl">Staff Share %</label><input type="number" step="0.01" min="0" name="staff_share_pct" x-model="form.staff_share_pct" class="fld"><p class="text-[11px] text-emerald-600 font-bold mt-1">₹<span x-text="calc(form.staff_share_pct)"></span></p></div>
                        <div>
                            <label class="lbl">Company Share % <span class="text-[9px] text-slate-400 normal-case">(auto — the remainder)</span></label>
                            <input type="text" :value="companyPct().toFixed(2) + ' %'" readonly class="fld bg-slate-100 text-slate-500 cursor-not-allowed font-bold">
                            <p class="text-[11px] text-emerald-600 font-bold mt-1">₹<span x-text="calc(companyPct())"></span></p>
                        </div>
                    </div>

                    <!-- AMOUNT MODE -->
                    <div x-show="mode()==='amount'" class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div><label class="lbl">Seller Share ₹</label><input type="number" step="0.01" min="0" name="seller_share_amt" x-model="form.seller_share_amt" class="fld"><p class="text-[11px] text-indigo-600 font-bold mt-1"><span x-text="pctOf(form.seller_share_amt)"></span>%</p></div>
                        <div><label class="lbl">Discount Share (Subscription) ₹</label><input type="number" step="0.01" min="0" name="subscription_discount_amt" x-model="form.subscription_discount_amt" class="fld"><p class="text-[11px] text-indigo-600 font-bold mt-1"><span x-text="pctOf(form.subscription_discount_amt)"></span>% <span class="text-slate-400 font-normal">(subscribed users only)</span></p></div>
                        <div><label class="lbl">Referral Share ₹</label><input type="number" step="0.01" min="0" name="referral_share_amt" x-model="form.referral_share_amt" class="fld"><p class="text-[11px] text-indigo-600 font-bold mt-1"><span x-text="pctOf(form.referral_share_amt)"></span>%</p></div>
                        <div><label class="lbl">Staff Share ₹</label><input type="number" step="0.01" min="0" name="staff_share_amt" x-model="form.staff_share_amt" class="fld"><p class="text-[11px] text-indigo-600 font-bold mt-1"><span x-text="pctOf(form.staff_share_amt)"></span>%</p></div>
                        <div>
                            <label class="lbl">Company Share ₹ <span class="text-[9px] text-slate-400 normal-case">(auto — what's left)</span></label>
                            <input type="text" :value="'₹' + companyAmt().toFixed(2)" readonly class="fld bg-slate-100 text-slate-500 cursor-not-allowed font-bold">
                            <p class="text-[11px] text-indigo-600 font-bold mt-1"><span x-text="pctOf(companyAmt())"></span>%</p>
                        </div>
                    </div>

                    <div class="rounded-xl border p-3 text-xs" :class="isOver() ? 'bg-rose-50 border-rose-200 text-rose-700' : 'bg-slate-50 border-slate-200 text-slate-600'">
                        <template x-if="mode()==='percent'">
                            <span><b>Allocated:</b> <span x-text="usedPct().toFixed(2)"></span>% &nbsp;•&nbsp;
                            <b>Company gets:</b> <span x-text="companyPct().toFixed(2)"></span>% (₹<span x-text="calc(companyPct())"></span>)</span>
                        </template>
                        <template x-if="mode()==='amount'">
                            <span><b>Allocated:</b> ₹<span x-text="usedAmt().toFixed(2)"></span> of ₹<span x-text="base().toFixed(2)"></span> &nbsp;•&nbsp;
                            <b>Company gets:</b> ₹<span x-text="companyAmt().toFixed(2)"></span></span>
                        </template>
                        <span x-show="isOver()" class="font-bold block mt-1" x-text="mode()==='amount' ? '⚠ Shares are more than the selling price. Please reduce.' : '⚠ Shares exceed 100% — company share would be negative. Please reduce.'"></span>
                    </div>
                </div>
            </div>
            <div class="flex justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" name="update_product" :disabled="isOver()" class="px-5 py-2 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow disabled:opacity-40 disabled:cursor-not-allowed">Save Changes</button>
            </div>
        </form>
    </div>
</div>
</template>

<!-- BULK DELETE CONFIRM -->
<div x-show="bulkConfirm" x-transition.opacity style="display:none;" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="bulkConfirm=false"></div>
    <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-rose-500 to-red-600 px-5 py-4 flex items-center gap-3">
            <i class="fas fa-triangle-exclamation text-white text-xl"></i>
            <h3 class="text-white font-bold text-lg">Delete Selected Products</h3>
        </div>
        <div class="p-6">
            <p class="text-slate-600 text-sm">Permanently delete <b class="text-rose-600" x-text="selected.length"></b> product(s)? This cannot be undone.</p>
            <form method="POST" class="mt-5">
                <template x-for="id in selected" :key="id"><input type="hidden" name="product_ids[]" :value="id"></template>
                <div class="flex justify-end gap-2">
                    <button type="button" @click="bulkConfirm=false" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                    <button type="submit" name="bulk_delete" class="px-5 py-2 text-sm font-bold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function pmApp() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        filtersOpen: <?php echo $filters_on ? 'true' : 'false'; ?>,
        selected: [], allIds: <?php echo json_encode($all_ids); ?>,
        bulkConfirm: false,
        modal: null, loading: false, curId: null, curName: '',
        notes: [], history: [], viewNote: null, form: {},
        rtab: 'kyc', rec: { area_mode: 'all', pincodes: [], states: [], kyc_list: [] },
        picked: [],                                   // the KYC boxes ticked right now
        pickStates: [], stateQuery: '',
        allStates: <?php echo json_encode($IN_STATES); ?>,
        subcats: <?php echo json_encode($subcats); ?>,
        esvc: {},                                     // the full edit form

        openRecruit(id, name) {
            this.curId = id; this.curName = name; this.rtab = 'kyc';
            this.rec = { area_mode: 'all', pincodes: [], states: [], kyc_list: [] };
            this.picked = []; this.pickStates = []; this.stateQuery = '';
            this.modal = 'recruit'; this.loading = true;
            this.fetchJSON('recruitment', id, d => {
                if (d) {
                    this.rec = Object.assign({ area_mode: 'all', pincodes: [], states: [], kyc_list: [] }, d);
                    this.picked     = (this.rec.kyc_list || []).slice();
                    this.pickStates = (this.rec.states   || []).slice();
                }
            });
        },
        /* how many of a section's boxes are ticked */
        countIn(keys) { return (keys || []).filter(k => this.picked.includes(k)).length; },
        toggleGroup(keys) {
            const all = (keys || []).every(k => this.picked.includes(k));
            if (all) { this.picked = this.picked.filter(k => !keys.includes(k)); }
            else { (keys || []).forEach(k => { if (!this.picked.includes(k)) this.picked.push(k); }); }
        },
        labelsIn(map) {
            return Object.keys(map || {}).filter(k => this.picked.includes(k)).map(k => map[k]).join(', ');
        },

        /* ---------- add / edit a product ---------- */
        svcMode: 'edit',
        blankSvc() {
            return { title: '', description: '', category_id: '<?php echo $IS_GOV ? 1 : ($cats[0]['id'] ?? 1); ?>',
                     sub_category_id: '0', price: '0', discount_price: '0', web_url: '', app_url: '',
                     tutorial_url: '', icon_class: '', color_class: 'color-1', status: '1' };
        },
        openAddSvc() {
            this.svcMode = 'add'; this.curId = ''; this.curName = '';
            this.esvc = this.blankSvc(); this.loading = false; this.modal = 'editsvc';
        },
        openEditSvc(id, name) {
            this.svcMode = 'edit';
            this.curId = id; this.curName = name; this.esvc = {}; this.modal = 'editsvc';
            this.fetchJSON('product', id, d => {
                const b = { title: '', description: '', category_id: '1', sub_category_id: '0', price: '0',
                            discount_price: '0', web_url: '', app_url: '', tutorial_url: '',
                            icon_class: '', color_class: 'color-1', status: '1' };
                Object.keys(b).forEach(k => { if (d && d[k] !== null && d[k] !== undefined) b[k] = String(d[k]); });
                this.esvc = b;
            });
        },
        subsFor(cid) { return (this.subcats || []).filter(sc => String(sc.category_id) === String(cid)); },
        isImg(v) { v = String(v || ''); return v.indexOf('http') === 0 || v.indexOf('uploads/') === 0; },
        askDelete() {
            if (confirm('Delete this product permanently? This cannot be undone.')) {
                const f = document.createElement('form');
                f.method = 'POST';
                f.innerHTML = '<input name="service_id" value="' + this.curId + '"><input name="delete_product" value="1">';
                document.body.appendChild(f); f.submit();
            }
        },
        openNotes(id, name)   { this.curId=id; this.curName=name; this.viewNote=null; this.notes=[]; this.modal='notes'; this.fetchJSON('notes', id, d => this.notes = d); },
        openNewNote(id, name) { this.curId=id; this.curName=name; this.modal='newNote'; },
        openHistory(id, name) { this.curId=id; this.curName=name; this.history=[]; this.modal='history'; this.fetchJSON('history', id, d => this.history = d); },
        openUpdate(id, name)  { this.curId=id; this.curName=name; this.form={}; this.modal='update'; this.fetchJSON('product', id, d => this.form = d || {}); },
        close() { this.modal=null; this.viewNote=null; },
        base() { var d = parseFloat(this.form.discount_price)||0, m = parseFloat(this.form.price)||0; return d > 0 ? d : m; },
        calc(pct) { return ((this.base() * (parseFloat(pct)||0)) / 100).toFixed(2); },
        mode() { return this.form.share_mode === 'amount' ? 'amount' : 'percent'; },
        setMode(m) {
            var b = this.base();
            if (m === 'amount') {
                // carry the current percentages over as rupees
                ['seller','subscription_discount','referral','staff'].forEach(k => {
                    var pc = (k === 'subscription_discount') ? 'subscription_discount_pct' : k + '_share_pct';
                    var ac = (k === 'subscription_discount') ? 'subscription_discount_amt' : k + '_share_amt';
                    if (!this.form[ac] || Number(this.form[ac]) === 0) {
                        this.form[ac] = (((parseFloat(this.form[pc]) || 0) * b) / 100).toFixed(2);
                    }
                });
            }
            this.form.share_mode = m;
        },
        pctOf(amt) { var b = this.base(); return b > 0 ? (((parseFloat(amt)||0) / b) * 100).toFixed(2) : '0.00'; },
        usedPct() {
            var k = ['seller_share_pct','subscription_discount_pct','referral_share_pct','staff_share_pct'];
            return k.reduce((s,x) => s + (parseFloat(this.form[x])||0), 0);
        },
        usedAmt() {
            var k = ['seller_share_amt','subscription_discount_amt','referral_share_amt','staff_share_amt'];
            return k.reduce((s,x) => s + (parseFloat(this.form[x])||0), 0);
        },
        companyPct() { return Math.max(0, 100 - this.usedPct()); },
        companyAmt() { return Math.max(0, this.base() - this.usedAmt()); },
        isOver() { return this.mode() === 'amount' ? (this.usedAmt() > this.base() + 0.001) : (this.usedPct() > 100); },
        async fetchJSON(kind, id, cb) {
            this.loading = true;
            try { const r = await fetch('<?php echo $PM_SELF; ?>?ajax=' + kind + '&sid=' + id); cb(await r.json()); }
            catch(e) { cb([]); }
            this.loading = false;
        },
        fmt(s) {
            if (!s) return '';
            const d = new Date(String(s).replace(' ', 'T'));
            if (isNaN(d)) return s;
            return d.toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'}) + ', ' + d.toLocaleTimeString('en-US', {hour:'2-digit', minute:'2-digit'});
        }
    }
}
</script>
</body>
</html>
