<?php
/* ============================================================================
   WBMCZ ADMIN — SUBSCRIPTION MANAGEMENT
   ----------------------------------------------------------------------------
   As many plans as you like. Each one carries its own price, its own length,
   and its own list of products. Move a price up or down in one click, add or
   drop products from a plan, and every change is written to the plan history.
   ============================================================================ */
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/rbac.php';
require_once __DIR__ . '/../includes/activity.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
rbac_guard(['manage_subscriptions', 'manage_settings']);

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];
$company_name = getSetting('site_name', 'WBMCZ');

$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'];

$flash_ok  = $_SESSION['flash_success'] ?? ''; unset($_SESSION['flash_success']);
$flash_err = $_SESSION['flash_error']   ?? ''; unset($_SESSION['flash_error']);

/* ============================================================
   SCHEMA — built on demand so the page works before the migration
   ============================================================ */
$conn = $db->getConnection();
foreach ([
  "CREATE TABLE IF NOT EXISTS subscription_plans (
      id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(120) NOT NULL, plan_code VARCHAR(40) NULL,
      tagline VARCHAR(200) NULL, description TEXT NULL,
      mrp DECIMAL(10,2) NOT NULL DEFAULT 0.00, price DECIMAL(10,2) NOT NULL DEFAULT 0.00,
      duration_days INT NOT NULL DEFAULT 365, discount_pct DECIMAL(5,2) NOT NULL DEFAULT 0.00,
      product_scope VARCHAR(20) NOT NULL DEFAULT 'selected', badge VARCHAR(60) NULL,
      color VARCHAR(30) NOT NULL DEFAULT 'indigo', features TEXT NULL,
      is_default TINYINT(1) NOT NULL DEFAULT 0, is_popular TINYINT(1) NOT NULL DEFAULT 0,
      status TINYINT(1) NOT NULL DEFAULT 1, sort_order INT NOT NULL DEFAULT 0,
      created_by INT NULL, created_by_name VARCHAR(150) NULL,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NULL DEFAULT NULL,
      UNIQUE KEY uniq_sp_code (plan_code), KEY idx_sp_status (status, sort_order)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",

  "CREATE TABLE IF NOT EXISTS subscription_plan_items (
      id INT AUTO_INCREMENT PRIMARY KEY, plan_id INT NOT NULL, service_id INT NOT NULL,
      service_type VARCHAR(20) NOT NULL DEFAULT 'seller', service_title VARCHAR(255) NULL,
      discount_pct DECIMAL(5,2) NULL, discount_amount DECIMAL(10,2) NULL,
      is_free TINYINT(1) NOT NULL DEFAULT 0, added_by INT NULL, added_by_name VARCHAR(150) NULL,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      UNIQUE KEY uniq_spi (plan_id, service_id, service_type), KEY idx_spi_plan (plan_id)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",

  "CREATE TABLE IF NOT EXISTS subscription_plan_history (
      id BIGINT AUTO_INCREMENT PRIMARY KEY, plan_id INT NOT NULL, plan_name VARCHAR(120) NULL,
      action VARCHAR(30) NOT NULL DEFAULT 'update', field_label VARCHAR(120) NULL,
      old_value VARCHAR(255) NULL, new_value VARCHAR(255) NULL, remark VARCHAR(500) NULL,
      done_by INT NULL, done_by_name VARCHAR(150) NULL,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, KEY idx_sph_plan (plan_id, created_at)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
  "CREATE TABLE IF NOT EXISTS user_subscriptions (
      id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, plan_id INT NULL,
      plan_name VARCHAR(120) NULL, amount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
      payment_mode VARCHAR(30) NULL, payment_ref VARCHAR(120) NULL,
      starts_at DATETIME NULL, expires_at DATETIME NULL,
      status VARCHAR(20) NOT NULL DEFAULT 'active', created_by INT NULL, created_by_name VARCHAR(150) NULL,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      KEY idx_us_user (user_id, status), KEY idx_us_plan (plan_id), KEY idx_us_expiry (expires_at)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
] as $q) { try { $conn->query($q); } catch (\Throwable $e) {} }

/* The columns on users that tie a customer to a plan. acvmigration.php adds these
   too, but the page adds them itself so it works even if that page was never run —
   without them the plan list query fails and the screen looks empty. */
function sp_col_exists($conn, $table, $col) {
    try { $r = $conn->query("SHOW COLUMNS FROM `$table` LIKE '$col'"); return $r && $r->num_rows > 0; }
    catch (\Throwable $e) { return false; }
}
foreach ([
    'is_subscribed'           => "TINYINT(1) NOT NULL DEFAULT 0",
    'subscription_plan_id'    => "INT NULL",
    'subscription_started_at' => "DATETIME NULL",
    'subscription_expires_at' => "DATETIME NULL",
] as $__c => $__d) {
    if (!sp_col_exists($conn, 'users', $__c)) {
        try { $conn->query("ALTER TABLE users ADD COLUMN `$__c` $__d"); } catch (\Throwable $e) {}
    }
}
$SP_HAS_PLAN_COL = sp_col_exists($conn, 'users', 'subscription_plan_id');

/* ============================================================
   HELPERS
   ============================================================ */
function sp_log($db, $planId, $planName, $action, $field = null, $old = null, $new = null, $remark = '') {
    global $ME;
    try {
        $db->insert(
            "INSERT INTO subscription_plan_history
                (plan_id, plan_name, action, field_label, old_value, new_value, remark, done_by, done_by_name)
             VALUES (?,?,?,?,?,?,?,?,?)",
            [(int)$planId, substr((string)$planName, 0, 120), substr((string)$action, 0, 30),
             $field !== null ? substr((string)$field, 0, 120) : null,
             $old !== null ? substr((string)$old, 0, 255) : null,
             $new !== null ? substr((string)$new, 0, 255) : null,
             $remark !== '' ? substr($remark, 0, 500) : null,
             (int)$ME['id'], substr((string)$ME['name'], 0, 150)]
        );
    } catch (\Throwable $e) {}
}
function sp_plan($db, $id) {
    $r = $db->select("SELECT * FROM subscription_plans WHERE id = ?", [(int)$id]);
    return !empty($r) ? $r[0] : null;
}
/* Keep the old single setting in step with the default plan so subscription.php
   carries on working exactly as before. */
function sp_sync_setting($db) {
    try {
        $d = $db->select("SELECT price FROM subscription_plans WHERE is_default = 1 AND status = 1 ORDER BY sort_order ASC LIMIT 1");
        if (empty($d)) return;
        $p = (float)$d[0]['price'];
        $ex = $db->select("SELECT id FROM settings WHERE setting_key = 'subscription_price' LIMIT 1");
        if (!empty($ex)) { $db->insert("UPDATE settings SET setting_value = ? WHERE setting_key = 'subscription_price'", [$p]); }
        else { $db->insert("INSERT INTO settings (setting_key, setting_value) VALUES ('subscription_price', ?)", [$p]); }
    } catch (\Throwable $e) {}
}
function sp_money($n) { return '₹' . number_format((float)$n, 2); }

/* ============================================================
   AJAX — plan detail, its products, and its history
   ============================================================ */
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $id = (int)($_GET['id'] ?? 0);
    $p  = $id ? sp_plan($db, $id) : null;
    if (!$p) { echo json_encode(['ok' => false, 'msg' => 'Plan not found.']); exit; }

    $items = []; $hist = [];
    try {
        $items = $db->select(
            "SELECT i.*, s.title AS live_title, s.price AS mrp, s.discount_price, s.category_id, c.title AS cat_name
             FROM subscription_plan_items i
             LEFT JOIN seller_services s ON s.id = i.service_id
             LEFT JOIN service_categories c ON c.id = s.category_id
             WHERE i.plan_id = ? ORDER BY i.id DESC", [$id]);
    } catch (\Throwable $e) {}
    try { $hist = $db->select("SELECT * FROM subscription_plan_history WHERE plan_id = ? ORDER BY id DESC LIMIT 200", [$id]); }
    catch (\Throwable $e) {}

    foreach ($hist as &$h) { $h['when'] = date('d M Y, h:i A', strtotime($h['created_at'])); }
    unset($h);
    foreach ($items as &$it) {
        $it['title_show'] = $it['live_title'] ?: $it['service_title'];
        $base = (float)($it['discount_price'] > 0 ? $it['discount_price'] : $it['mrp']);
        $it['base_price'] = number_format($base, 2);
        $eff = (int)$it['is_free'] ? 0.0
             : ($it['discount_amount'] !== null ? max(0, $base - (float)$it['discount_amount'])
             : ($it['discount_pct'] !== null ? $base * (1 - (float)$it['discount_pct'] / 100)
             : $base * (1 - (float)$p['discount_pct'] / 100)));
        $it['member_price'] = number_format($eff, 2);
    }
    unset($it);

    echo json_encode(['ok' => true, 'plan' => $p, 'items' => $items, 'history' => $hist]);
    exit;
}

/* ============================================================
   CREATE / EDIT A PLAN
   ============================================================ */
if (isset($_POST['save_plan'])) {
    $id      = (int)($_POST['plan_id'] ?? 0);
    $name    = trim((string)($_POST['name'] ?? ''));
    $code    = strtoupper(trim((string)($_POST['plan_code'] ?? '')));
    $price   = round((float)($_POST['price'] ?? 0), 2);
    $mrp     = round((float)($_POST['mrp'] ?? 0), 2);
    $days    = max(1, (int)($_POST['duration_days'] ?? 365));
    $disc    = max(0, min(100, (float)($_POST['discount_pct'] ?? 0)));
    $scope   = ($_POST['product_scope'] ?? 'selected') === 'all' ? 'all' : 'selected';
    $tagline = trim((string)($_POST['tagline'] ?? ''));
    $desc    = trim((string)($_POST['description'] ?? ''));
    $badge   = trim((string)($_POST['badge'] ?? ''));
    $color   = trim((string)($_POST['color'] ?? 'indigo'));
    $feat    = trim((string)($_POST['features'] ?? ''));
    $order   = (int)($_POST['sort_order'] ?? 0);
    $status  = !empty($_POST['status'])     ? 1 : 0;
    $popular = !empty($_POST['is_popular']) ? 1 : 0;

    if ($name === '') {
        $_SESSION['flash_error'] = 'Give the plan a name.';
        redirect('subscription_plans.php');
    }
    if ($mrp <= 0) { $mrp = $price; }
    if ($code === '') { $code = strtoupper(preg_replace('/[^A-Z0-9]/i', '', substr($name, 0, 12))) . ($id ?: ''); }

    if ($id > 0) {
        $old = sp_plan($db, $id);
        if (!$old) { $_SESSION['flash_error'] = 'That plan no longer exists.'; redirect('subscription_plans.php'); }
        try {
            $db->insert(
                "UPDATE subscription_plans SET name=?, plan_code=?, tagline=?, description=?, mrp=?, price=?,
                        duration_days=?, discount_pct=?, product_scope=?, badge=?, color=?, features=?,
                        is_popular=?, status=?, sort_order=?, updated_at=NOW() WHERE id=?",
                [$name, $code, $tagline, $desc, $mrp, $price, $days, $disc, $scope, $badge, $color, $feat,
                 $popular, $status, $order, $id]
            );
        } catch (\Throwable $e) {
            $_SESSION['flash_error'] = 'The plan could not be saved — the plan code may already be in use.';
            redirect('subscription_plans.php');
        }

        $watch = [
            'Name' => ['name', $old['name'], $name],
            'Price' => ['price', sp_money($old['price']), sp_money($price)],
            'MRP' => ['mrp', sp_money($old['mrp']), sp_money($mrp)],
            'Duration' => ['duration_days', $old['duration_days'] . ' days', $days . ' days'],
            'Member discount' => ['discount_pct', $old['discount_pct'] . '%', $disc . '%'],
            'Product scope' => ['product_scope', $old['product_scope'], $scope],
            'Status' => ['status', (int)$old['status'] ? 'Active' : 'Hidden', $status ? 'Active' : 'Hidden'],
        ];
        foreach ($watch as $label => $w) {
            if ((string)$w[1] !== (string)$w[2]) {
                $act = 'update';
                if ($label === 'Price') { $act = $price > (float)$old['price'] ? 'price_up' : ($price < (float)$old['price'] ? 'price_down' : 'update'); }
                sp_log($db, $id, $name, $act, $label, $w[1], $w[2]);
            }
        }
        activity_log($db, 'update', 'Subscription Management', "Updated plan $name", 'plan', $id);
        $_SESSION['flash_success'] = "Plan “$name” saved.";
    } else {
        try {
            $id = $db->insert(
                "INSERT INTO subscription_plans
                    (name, plan_code, tagline, description, mrp, price, duration_days, discount_pct,
                     product_scope, badge, color, features, is_popular, status, sort_order, created_by, created_by_name)
                 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                [$name, $code, $tagline, $desc, $mrp, $price, $days, $disc, $scope, $badge, $color, $feat,
                 $popular, $status, $order, $ME['id'], $ME['name']]
            );
        } catch (\Throwable $e) { $id = 0; }

        if ($id) {
            sp_log($db, $id, $name, 'create', 'Plan', null, $name . ' at ' . sp_money($price));
            activity_log($db, 'create', 'Subscription Management', "Created plan $name at " . sp_money($price), 'plan', $id);
            $_SESSION['flash_success'] = "Plan “$name” created. Now add the products it should carry.";
        } else {
            $_SESSION['flash_error'] = 'The plan could not be created — try a different plan code.';
        }
    }
    sp_sync_setting($db);
    redirect('subscription_plans.php');
}

/* ============================================================
   QUICK PRICE MOVE  —  up or down, in one click
   ============================================================ */
if (isset($_POST['move_price'])) {
    $id   = (int)($_POST['plan_id'] ?? 0);
    $p    = sp_plan($db, $id);
    $mode = $_POST['mode'] ?? 'amount';           // amount | percent | set
    $val  = (float)($_POST['value'] ?? 0);
    $dir  = ($_POST['direction'] ?? 'up') === 'down' ? -1 : 1;

    if (!$p) { $_SESSION['flash_error'] = 'That plan no longer exists.'; redirect('subscription_plans.php'); }

    $oldPrice = (float)$p['price'];
    if     ($mode === 'set')     { $newPrice = max(0, $val); }
    elseif ($mode === 'percent') { $newPrice = max(0, round($oldPrice + ($dir * $oldPrice * $val / 100), 2)); }
    else                         { $newPrice = max(0, round($oldPrice + ($dir * $val), 2)); }

    if (abs($newPrice - $oldPrice) < 0.005) {
        $_SESSION['flash_error'] = 'The price did not change.';
        redirect('subscription_plans.php');
    }

    $newMrp = (float)$p['mrp'];
    if ($newPrice > $newMrp) { $newMrp = $newPrice; }

    try {
        $db->insert("UPDATE subscription_plans SET price = ?, mrp = ?, updated_at = NOW() WHERE id = ?", [$newPrice, $newMrp, $id]);
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = 'The price could not be changed.';
        redirect('subscription_plans.php');
    }

    $act    = $newPrice > $oldPrice ? 'price_up' : 'price_down';
    $remark = trim((string)($_POST['reason'] ?? ''));
    sp_log($db, $id, $p['name'], $act, 'Price', sp_money($oldPrice), sp_money($newPrice), $remark);
    activity_log($db, 'update', 'Subscription Management',
        "Plan {$p['name']} price " . ($act === 'price_up' ? 'raised' : 'lowered') . ' from ' . sp_money($oldPrice) . ' to ' . sp_money($newPrice), 'plan', $id);

    sp_sync_setting($db);
    $_SESSION['flash_success'] = "{$p['name']} is now " . sp_money($newPrice) . ' — the old price is kept in the plan history.';
    redirect('subscription_plans.php');
}

/* ============================================================
   ADD PRODUCTS TO A PLAN
   ============================================================ */
if (isset($_POST['add_products'])) {
    $id  = (int)($_POST['plan_id'] ?? 0);
    $p   = sp_plan($db, $id);
    $ids = (isset($_POST['service_ids']) && is_array($_POST['service_ids'])) ? array_map('intval', $_POST['service_ids']) : [];
    if (!$p) { $_SESSION['flash_error'] = 'That plan no longer exists.'; redirect('subscription_plans.php'); }
    if (empty($ids)) { $_SESSION['flash_error'] = 'Tick at least one product.'; redirect('subscription_plans.php'); }

    $n = 0; $names = [];
    foreach ($ids as $sid) {
        if ($sid <= 0) continue;
        $s = $db->select("SELECT id, title FROM seller_services WHERE id = ?", [$sid]);
        if (empty($s)) continue;
        try {
            $db->insert(
                "INSERT INTO subscription_plan_items (plan_id, service_id, service_type, service_title, added_by, added_by_name)
                 VALUES (?,?,'seller',?,?,?)
                 ON DUPLICATE KEY UPDATE service_title = VALUES(service_title)",
                [$id, $sid, $s[0]['title'], $ME['id'], $ME['name']]
            );
            $n++; $names[] = $s[0]['title'];
        } catch (\Throwable $e) {}
    }

    sp_log($db, $id, $p['name'], 'product_add', 'Products added', null, $n . ' product(s)', implode(', ', array_slice($names, 0, 12)));
    activity_log($db, 'update', 'Subscription Management', "Added $n product(s) to plan {$p['name']}", 'plan', $id);
    $_SESSION['flash_success'] = "$n product(s) added to {$p['name']}.";
    redirect('subscription_plans.php');
}

/* ============================================================
   REMOVE ONE PRODUCT / EDIT ITS DISCOUNT
   ============================================================ */
if (isset($_POST['remove_product'])) {
    $id  = (int)($_POST['plan_id'] ?? 0);
    $iid = (int)($_POST['item_id'] ?? 0);
    $p   = sp_plan($db, $id);
    $it  = $db->select("SELECT * FROM subscription_plan_items WHERE id = ? AND plan_id = ?", [$iid, $id]);
    if ($p && !empty($it)) {
        try { $db->insert("DELETE FROM subscription_plan_items WHERE id = ?", [$iid]); } catch (\Throwable $e) {}
        sp_log($db, $id, $p['name'], 'product_remove', 'Product removed', $it[0]['service_title'], null);
        activity_log($db, 'update', 'Subscription Management', "Removed {$it[0]['service_title']} from plan {$p['name']}", 'plan', $id);
        $_SESSION['flash_success'] = "“{$it[0]['service_title']}” removed from {$p['name']}.";
    }
    redirect('subscription_plans.php');
}

if (isset($_POST['save_item'])) {
    $id  = (int)($_POST['plan_id'] ?? 0);
    $iid = (int)($_POST['item_id'] ?? 0);
    $p   = sp_plan($db, $id);
    $it  = $db->select("SELECT * FROM subscription_plan_items WHERE id = ? AND plan_id = ?", [$iid, $id]);
    if ($p && !empty($it)) {
        $free = !empty($_POST['is_free']) ? 1 : 0;
        $pct  = ($_POST['item_pct'] ?? '') !== '' ? max(0, min(100, (float)$_POST['item_pct'])) : null;
        $amt  = ($_POST['item_amt'] ?? '') !== '' ? max(0, (float)$_POST['item_amt']) : null;
        try {
            $db->insert("UPDATE subscription_plan_items SET is_free = ?, discount_pct = ?, discount_amount = ? WHERE id = ?",
                        [$free, $pct, $amt, $iid]);
        } catch (\Throwable $e) {}
        $desc = $free ? 'free for members' : ($pct !== null ? $pct . '% off' : ($amt !== null ? '₹' . $amt . ' off' : 'plan default'));
        sp_log($db, $id, $p['name'], 'update', 'Product deal — ' . $it[0]['service_title'], null, $desc);
        $_SESSION['flash_success'] = "Deal updated for “{$it[0]['service_title']}”.";
    }
    redirect('subscription_plans.php');
}

/* ============================================================
   STATUS · DEFAULT · DELETE
   ============================================================ */
if (isset($_POST['toggle_plan'])) {
    $id = (int)($_POST['plan_id'] ?? 0);
    $p  = sp_plan($db, $id);
    if ($p) {
        $new = (int)$p['status'] === 1 ? 0 : 1;
        try { $db->insert("UPDATE subscription_plans SET status = ?, updated_at = NOW() WHERE id = ?", [$new, $id]); } catch (\Throwable $e) {}
        sp_log($db, $id, $p['name'], 'update', 'Status', (int)$p['status'] ? 'Active' : 'Hidden', $new ? 'Active' : 'Hidden');
        activity_log($db, 'update', 'Subscription Management', "Plan {$p['name']} " . ($new ? 'shown' : 'hidden'), 'plan', $id);
        $_SESSION['flash_success'] = "{$p['name']} is now " . ($new ? 'visible to customers.' : 'hidden from customers.');
        sp_sync_setting($db);
    }
    redirect('subscription_plans.php');
}

if (isset($_POST['set_default'])) {
    $id = (int)($_POST['plan_id'] ?? 0);
    $p  = sp_plan($db, $id);
    if ($p) {
        try {
            $db->insert("UPDATE subscription_plans SET is_default = 0", []);
            $db->insert("UPDATE subscription_plans SET is_default = 1 WHERE id = ?", [$id]);
        } catch (\Throwable $e) {}
        sp_log($db, $id, $p['name'], 'update', 'Default plan', 'no', 'yes');
        activity_log($db, 'update', 'Subscription Management', "Plan {$p['name']} set as the default", 'plan', $id);
        sp_sync_setting($db);
        $_SESSION['flash_success'] = "{$p['name']} is now the default plan.";
    }
    redirect('subscription_plans.php');
}

if (isset($_POST['delete_plan'])) {
    $id = (int)($_POST['plan_id'] ?? 0);
    $p  = sp_plan($db, $id);
    if ($p) {
        $inUse = 0;
        try { $inUse = (int)($db->select("SELECT COUNT(*) c FROM users WHERE subscription_plan_id = ?", [$id])[0]['c'] ?? 0); }
        catch (\Throwable $e) {}
        if ($inUse > 0) {
            $_SESSION['flash_error'] = "$inUse customer(s) are on “{$p['name']}”. Hide the plan instead of deleting it, so their subscription is not broken.";
        } else {
            try {
                $db->insert("DELETE FROM subscription_plan_items WHERE plan_id = ?", [$id]);
                $db->insert("DELETE FROM subscription_plans WHERE id = ?", [$id]);
            } catch (\Throwable $e) {}
            sp_log($db, $id, $p['name'], 'delete', 'Plan', $p['name'], null);
            activity_log($db, 'delete', 'Subscription Management', "Deleted plan {$p['name']}", 'plan', $id);
            $_SESSION['flash_success'] = "Plan “{$p['name']}” deleted.";
        }
    }
    redirect('subscription_plans.php');
}

/* ============================================================
   DATA
   ============================================================ */
$plans = [];
$plans_error = '';
/* Only count members when the column is really there, so one missing column can
   never turn the whole screen blank. */
$__members = $SP_HAS_PLAN_COL
    ? "(SELECT COUNT(*) FROM users u WHERE u.subscription_plan_id = p.id)"
    : "0";
try {
    $plans = $db->select(
        "SELECT p.*,
                (SELECT COUNT(*) FROM subscription_plan_items i WHERE i.plan_id = p.id) AS item_count,
                $__members AS member_count
         FROM subscription_plans p ORDER BY p.sort_order ASC, p.id ASC");
    /* $db->select() answers with an empty array when the statement itself fails,
       so ask the connection whether anything actually went wrong. */
    if (empty($plans) && $conn->errno) { $plans_error = $conn->error; }
} catch (\Throwable $e) { $plans_error = $e->getMessage(); }

/* Last resort: if something above still went wrong, read the plans on their own so
   the list is never blank while rows exist. */
if ($plans_error !== '') {
    try {
        $plans = $db->select("SELECT * FROM subscription_plans ORDER BY sort_order ASC, id ASC");
        foreach ($plans as &$__p) { $__p['item_count'] = 0; $__p['member_count'] = 0; }
        unset($__p);
    } catch (\Throwable $e) {}
}

$totals = ['plans' => count($plans), 'active' => 0, 'members' => 0, 'products' => 0, 'revenue' => 0.0];
foreach ($plans as $p) {
    if ((int)$p['status'] === 1) { $totals['active']++; }
    $totals['members']  += (int)$p['member_count'];
    $totals['products'] += (int)$p['item_count'];
    $totals['revenue']  += (float)$p['price'] * (int)$p['member_count'];
}

/* the product picker */
$pick_q   = trim((string)($_GET['pq']   ?? ''));
$pick_cat = trim((string)($_GET['pcat'] ?? ''));
$pw = "1"; $pp = [];
if ($pick_q !== '')   { $pw .= " AND (s.title LIKE ? OR s.id = ?)"; $pp[] = "%$pick_q%"; $pp[] = (int)preg_replace('/\D/', '', $pick_q); }
if ($pick_cat !== '') { $pw .= " AND s.category_id = ?"; $pp[] = (int)$pick_cat; }

$pickable = [];
try {
    $pickable = $db->select(
        "SELECT s.id, s.title, s.price, s.discount_price, s.category_id, c.title AS cat_name
         FROM seller_services s LEFT JOIN service_categories c ON c.id = s.category_id
         WHERE $pw AND s.status = 1 ORDER BY s.id DESC LIMIT 300", $pp);
} catch (\Throwable $e) {}

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

$COLORS = ['indigo' => 'Indigo', 'violet' => 'Violet', 'emerald' => 'Emerald', 'amber' => 'Amber',
           'rose' => 'Rose', 'sky' => 'Sky', 'teal' => 'Teal', 'slate' => 'Slate'];
?>
<!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>Subscription Management - <?php echo htmlspecialchars($company_name); ?> 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;900&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        [x-cloak] { display: none !important; }
        .lbl { display:block; font-size:11px; font-weight:700; color:#475569; margin-bottom:4px; }
        .fld { width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:8px 11px; font-size:13px; background:#fff; }
        .fld:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.15); }
    </style>
</head>
<body class="bg-gray-50" x-data="planBoard()" x-cloak>

<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 text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative flex-shrink-0">
            <div class="flex items-center min-w-0">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-indigo-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
                <div class="min-w-0">
                    <h2 class="text-xl font-bold truncate">Subscription Management</h2>
                    <p class="text-[11px] text-slate-400 hidden sm:block">Plans, prices, and the products each plan carries</p>
                </div>
            </div>
            <button @click="openPlan(null)" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-white text-xs font-bold shadow hover:shadow-lg">
                <i class="fas fa-plus"></i> New Plan
            </button>
        </header>

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

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

            <?php if ($plans_error !== ''): ?>
            <div class="mb-5 bg-amber-50 border border-amber-200 text-amber-800 px-4 py-3 rounded-xl text-xs">
                <p class="font-bold mb-1"><i class="fas fa-triangle-exclamation mr-1"></i>The plan list had to be read the simple way</p>
                <p>The database said: <span class="font-mono"><?php echo htmlspecialchars($plans_error); ?></span></p>
                <p class="mt-1">Every plan is still shown below, but the product and subscriber counts read zero.
                   Run <b>acvmigration.php</b> once and this notice goes away.</p>
            </div>
            <?php endif; ?>

            <!-- ============ TOTALS ============ -->
            <div class="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
                <?php
                $tc = [
                    ['Plans',            $totals['plans'],                        'fa-layer-group',   'indigo'],
                    ['Live plans',       $totals['active'],                       'fa-eye',           'emerald'],
                    ['Subscribers',      $totals['members'],                      'fa-users',         'sky'],
                    ['Products covered', $totals['products'],                     'fa-box-open',      'violet'],
                    ['Plan value',       '₹' . number_format($totals['revenue']), 'fa-indian-rupee-sign', 'amber'],
                ];
                foreach ($tc as $c): ?>
                <div class="bg-white rounded-2xl border border-slate-200 p-5">
                    <div class="w-10 h-10 rounded-xl bg-<?php echo $c[3]; ?>-100 text-<?php echo $c[3]; ?>-600 flex items-center justify-center mb-3"><i class="fas <?php echo $c[2]; ?>"></i></div>
                    <p class="text-2xl font-black text-slate-800"><?php echo $c[1]; ?></p>
                    <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide"><?php echo $c[0]; ?></p>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- ============ PLAN CARDS ============ -->
            <?php if (empty($plans)): ?>
            <div class="bg-white rounded-2xl border border-slate-200 p-16 text-center">
                <div class="w-16 h-16 rounded-2xl bg-slate-100 text-slate-300 flex items-center justify-center text-2xl mx-auto mb-4"><i class="fas fa-crown"></i></div>
                <p class="font-bold text-slate-600 text-sm">No subscription plans yet</p>
                <p class="text-slate-400 text-xs mt-1 mb-5">Create your first plan, set its price, and pick the products it carries.</p>
                <button @click="openPlan(null)" class="px-6 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold"><i class="fas fa-plus mr-1"></i> Create the first plan</button>
            </div>
            <?php else: ?>
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
                <?php foreach ($plans as $p):
                    $col  = $p['color'] ?: 'indigo';
                    $save = (float)$p['mrp'] - (float)$p['price'];
                ?>
                <div class="bg-white rounded-2xl border-2 <?php echo (int)$p['is_default'] ? 'border-' . $col . '-400' : 'border-slate-200'; ?> overflow-hidden flex flex-col">

                    <div class="bg-gradient-to-r from-<?php echo $col; ?>-500 to-<?php echo $col; ?>-600 text-white p-5">
                        <div class="flex items-start justify-between gap-2">
                            <div class="min-w-0">
                                <h3 class="text-lg font-extrabold truncate"><?php echo htmlspecialchars($p['name']); ?></h3>
                                <p class="text-[11px] text-white/70 truncate"><?php echo htmlspecialchars($p['tagline'] ?: $p['plan_code']); ?></p>
                            </div>
                            <div class="flex flex-col items-end gap-1 flex-shrink-0">
                                <?php if ((int)$p['is_default']): ?><span class="text-[9px] font-black bg-white/25 px-2 py-0.5 rounded-full uppercase">Default</span><?php endif; ?>
                                <?php if ($p['badge']): ?><span class="text-[9px] font-black bg-white/25 px-2 py-0.5 rounded-full uppercase"><?php echo htmlspecialchars($p['badge']); ?></span><?php endif; ?>
                            </div>
                        </div>
                        <div class="mt-4 flex items-end gap-2">
                            <span class="text-3xl font-black"><?php echo sp_money($p['price']); ?></span>
                            <?php if ($save > 0): ?><span class="text-sm line-through text-white/60 mb-1"><?php echo sp_money($p['mrp']); ?></span><?php endif; ?>
                        </div>
                        <p class="text-[11px] text-white/75 mt-1">
                            for <?php echo (int)$p['duration_days']; ?> days
                            <?php if ((float)$p['discount_pct'] > 0): ?> · <?php echo rtrim(rtrim(number_format((float)$p['discount_pct'], 2), '0'), '.'); ?>% off products<?php endif; ?>
                        </p>
                    </div>

                    <div class="p-5 flex-1 space-y-3">
                        <div class="grid grid-cols-3 gap-2 text-center">
                            <div class="rounded-xl bg-slate-50 border border-slate-200 py-2">
                                <p class="text-lg font-black text-slate-800"><?php echo (int)$p['item_count']; ?></p>
                                <p class="text-[9px] font-bold text-slate-400 uppercase">Products</p>
                            </div>
                            <div class="rounded-xl bg-slate-50 border border-slate-200 py-2">
                                <p class="text-lg font-black text-slate-800"><?php echo (int)$p['member_count']; ?></p>
                                <p class="text-[9px] font-bold text-slate-400 uppercase">Members</p>
                            </div>
                            <div class="rounded-xl bg-slate-50 border border-slate-200 py-2">
                                <p class="text-lg font-black <?php echo (int)$p['status'] ? 'text-emerald-600' : 'text-slate-400'; ?>"><i class="fas <?php echo (int)$p['status'] ? 'fa-eye' : 'fa-eye-slash'; ?>"></i></p>
                                <p class="text-[9px] font-bold text-slate-400 uppercase"><?php echo (int)$p['status'] ? 'Live' : 'Hidden'; ?></p>
                            </div>
                        </div>

                        <p class="text-[11px] text-slate-500 leading-relaxed">
                            <?php if ($p['product_scope'] === 'all'): ?>
                                <i class="fas fa-infinity text-<?php echo $col; ?>-500 mr-1"></i>Covers <b>every product</b> on the site.
                            <?php else: ?>
                                <i class="fas fa-list-check text-<?php echo $col; ?>-500 mr-1"></i>Covers only the <b><?php echo (int)$p['item_count']; ?></b> product(s) you picked.
                            <?php endif; ?>
                        </p>

                        <?php if (trim((string)$p['features']) !== ''): ?>
                        <ul class="space-y-1">
                            <?php foreach (array_slice(preg_split('/\r\n|\r|\n/', $p['features']), 0, 4) as $f): if (trim($f) === '') continue; ?>
                            <li class="text-[11px] text-slate-600 flex items-start gap-2"><i class="fas fa-check text-emerald-500 mt-0.5"></i><span><?php echo htmlspecialchars(trim($f)); ?></span></li>
                            <?php endforeach; ?>
                        </ul>
                        <?php endif; ?>
                    </div>

                    <!-- price up / down -->
                    <div class="px-5 pb-3 flex gap-2">
                        <button @click="openPrice(<?php echo (int)$p['id']; ?>, '<?php echo htmlspecialchars(addslashes($p['name']), ENT_QUOTES); ?>', <?php echo (float)$p['price']; ?>, 'up')"
                                class="flex-1 px-3 py-2 rounded-xl bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200 text-[11px] font-bold hover:bg-emerald-100"><i class="fas fa-arrow-up mr-1"></i> Price up</button>
                        <button @click="openPrice(<?php echo (int)$p['id']; ?>, '<?php echo htmlspecialchars(addslashes($p['name']), ENT_QUOTES); ?>', <?php echo (float)$p['price']; ?>, 'down')"
                                class="flex-1 px-3 py-2 rounded-xl bg-rose-50 text-rose-700 ring-1 ring-rose-200 text-[11px] font-bold hover:bg-rose-100"><i class="fas fa-arrow-down mr-1"></i> Price down</button>
                    </div>

                    <div class="px-5 pb-5 grid grid-cols-2 gap-2">
                        <button @click="openProducts(<?php echo (int)$p['id']; ?>)" class="px-3 py-2 rounded-xl bg-indigo-600 text-white text-[11px] font-bold hover:bg-indigo-700"><i class="fas fa-box-open mr-1"></i> Products</button>
                        <button @click="openPlan(<?php echo (int)$p['id']; ?>)" class="px-3 py-2 rounded-xl bg-sky-600 text-white text-[11px] font-bold hover:bg-sky-700"><i class="fas fa-pen mr-1"></i> Edit plan</button>
                        <button @click="openHistory(<?php echo (int)$p['id']; ?>)" class="px-3 py-2 rounded-xl bg-slate-100 text-slate-600 text-[11px] font-bold hover:bg-slate-200"><i class="fas fa-clock-rotate-left mr-1"></i> History</button>
                        <form method="POST" onsubmit="return true;">
                            <input type="hidden" name="toggle_plan" value="1">
                            <input type="hidden" name="plan_id" value="<?php echo (int)$p['id']; ?>">
                            <button type="submit" class="w-full px-3 py-2 rounded-xl <?php echo (int)$p['status'] ? 'bg-amber-100 text-amber-700 hover:bg-amber-200' : 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200'; ?> text-[11px] font-bold">
                                <i class="fas <?php echo (int)$p['status'] ? 'fa-eye-slash' : 'fa-eye'; ?> mr-1"></i><?php echo (int)$p['status'] ? 'Hide' : 'Show'; ?>
                            </button>
                        </form>
                        <?php if (!(int)$p['is_default']): ?>
                        <form method="POST"><input type="hidden" name="set_default" value="1"><input type="hidden" name="plan_id" value="<?php echo (int)$p['id']; ?>">
                            <button type="submit" class="w-full px-3 py-2 rounded-xl bg-violet-100 text-violet-700 text-[11px] font-bold hover:bg-violet-200"><i class="fas fa-star mr-1"></i> Make default</button>
                        </form>
                        <button @click="askDelete(<?php echo (int)$p['id']; ?>, '<?php echo htmlspecialchars(addslashes($p['name']), ENT_QUOTES); ?>')" class="px-3 py-2 rounded-xl bg-rose-100 text-rose-700 text-[11px] font-bold hover:bg-rose-200"><i class="fas fa-trash mr-1"></i> Delete</button>
                        <?php else: ?>
                        <p class="col-span-2 text-[10px] text-slate-400 text-center pt-1"><i class="fas fa-lock mr-1"></i>The default plan cannot be deleted — make another plan the default first.</p>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </main>
    </div>
</div>

<!-- ================= PLAN EDITOR ================= -->
<div x-show="planBox" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="planBox = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[92vh] overflow-y-auto">
        <form method="POST">
            <input type="hidden" name="save_plan" value="1">
            <input type="hidden" name="plan_id" :value="f.id">

            <div class="px-6 py-5 border-b border-slate-100 sticky top-0 bg-white z-10 flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-extrabold text-slate-800" x-text="f.id ? 'Edit plan' : 'New subscription plan'"></h3>
                    <p class="text-xs text-slate-400">Name it, price it, and say how long it lasts</p>
                </div>
                <button type="button" @click="planBox = false" class="w-9 h-9 rounded-xl bg-slate-100 text-slate-500 hover:bg-slate-200"><i class="fas fa-xmark"></i></button>
            </div>

            <div class="p-6 space-y-4">
                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div class="sm:col-span-2"><label class="lbl">Plan name <span class="text-rose-500">*</span></label><input type="text" name="name" x-model="f.name" class="fld" required placeholder="Pro Membership"></div>
                    <div><label class="lbl">Plan code</label><input type="text" name="plan_code" x-model="f.plan_code" class="fld" placeholder="PRO"></div>
                </div>

                <div><label class="lbl">One-line tagline</label><input type="text" name="tagline" x-model="f.tagline" class="fld" placeholder="Everything a growing agency needs"></div>

                <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                    <div><label class="lbl">MRP (struck through)</label><input type="number" step="0.01" min="0" name="mrp" x-model="f.mrp" class="fld"></div>
                    <div><label class="lbl">Selling price <span class="text-rose-500">*</span></label><input type="number" step="0.01" min="0" name="price" x-model="f.price" class="fld" required></div>
                    <div><label class="lbl">Valid for (days)</label><input type="number" min="1" name="duration_days" x-model="f.duration_days" class="fld"></div>
                    <div><label class="lbl">Member discount %</label><input type="number" step="0.01" min="0" max="100" name="discount_pct" x-model="f.discount_pct" class="fld"></div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div>
                        <label class="lbl">Products in this plan</label>
                        <select name="product_scope" x-model="f.product_scope" class="fld">
                            <option value="selected">Only the products I pick</option>
                            <option value="all">Every product on the site</option>
                        </select>
                    </div>
                    <div><label class="lbl">Badge</label><input type="text" name="badge" x-model="f.badge" class="fld" placeholder="Popular"></div>
                    <div>
                        <label class="lbl">Card colour</label>
                        <select name="color" x-model="f.color" class="fld">
                            <?php foreach ($COLORS as $ck => $cl): ?><option value="<?php echo $ck; ?>"><?php echo $cl; ?></option><?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div><label class="lbl">What the customer gets — one line each</label><textarea name="features" x-model="f.features" rows="4" class="fld" placeholder="Discount on every listed product&#10;Referral program unlocked&#10;Priority support"></textarea></div>

                <div><label class="lbl">Description</label><textarea name="description" x-model="f.description" rows="2" class="fld"></textarea></div>

                <div class="grid grid-cols-2 gap-4 items-end">
                    <div><label class="lbl">Sort order</label><input type="number" name="sort_order" x-model="f.sort_order" class="fld"></div>
                    <div class="flex flex-col gap-2 pb-1">
                        <label class="flex items-center gap-2 text-xs font-bold text-slate-600"><input type="checkbox" name="status" x-model="f.status" class="w-4 h-4 rounded accent-emerald-600"> Show this plan to customers</label>
                        <label class="flex items-center gap-2 text-xs font-bold text-slate-600"><input type="checkbox" name="is_popular" x-model="f.is_popular" class="w-4 h-4 rounded accent-indigo-600"> Highlight as most popular</label>
                    </div>
                </div>
            </div>

            <div class="px-6 py-4 border-t border-slate-100 flex justify-end gap-2 sticky bottom-0 bg-white">
                <button type="button" @click="planBox = false" class="px-5 py-2.5 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600">Cancel</button>
                <button type="submit" class="px-6 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold hover:bg-indigo-700"><i class="fas fa-check mr-1"></i> Save plan</button>
            </div>
        </form>
    </div>
</div>

<!-- ================= PRICE UP / DOWN ================= -->
<div x-show="priceBox" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="priceBox = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md">
        <form method="POST">
            <input type="hidden" name="move_price" value="1">
            <input type="hidden" name="plan_id" :value="pr.id">
            <input type="hidden" name="direction" :value="pr.direction">

            <div class="px-6 py-5 border-b border-slate-100">
                <h3 class="text-lg font-extrabold text-slate-800">
                    <span x-text="pr.direction === 'up' ? 'Raise the price' : 'Lower the price'"></span>
                </h3>
                <p class="text-xs text-slate-400"><span x-text="pr.name"></span> · now ₹<span x-text="Number(pr.price).toFixed(2)"></span></p>
            </div>

            <div class="p-6 space-y-4">
                <div>
                    <label class="lbl">How?</label>
                    <select name="mode" x-model="pr.mode" class="fld">
                        <option value="amount">By an amount (₹)</option>
                        <option value="percent">By a percentage (%)</option>
                        <option value="set">Set an exact new price</option>
                    </select>
                </div>
                <div>
                    <label class="lbl" x-text="pr.mode === 'set' ? 'New price (₹)' : (pr.mode === 'percent' ? 'Percentage' : 'Amount (₹)')"></label>
                    <input type="number" step="0.01" min="0" name="value" x-model="pr.value" class="fld" required>
                </div>
                <div class="rounded-xl bg-slate-50 border border-slate-200 px-4 py-3">
                    <p class="text-[10px] font-bold text-slate-400 uppercase">New price will be</p>
                    <p class="text-2xl font-black" :class="pr.direction === 'up' ? 'text-emerald-600' : 'text-rose-600'">₹<span x-text="preview()"></span></p>
                </div>
                <div><label class="lbl">Why is the price changing? <span class="text-slate-400 font-normal">(saved in the plan history)</span></label><input type="text" name="reason" class="fld" placeholder="Festival offer / cost increase…"></div>
            </div>

            <div class="px-6 py-4 border-t border-slate-100 flex justify-end gap-2">
                <button type="button" @click="priceBox = false" class="px-5 py-2.5 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600">Cancel</button>
                <button type="submit" class="px-6 py-2.5 rounded-xl text-white text-xs font-bold" :class="pr.direction === 'up' ? 'bg-emerald-600 hover:bg-emerald-700' : 'bg-rose-600 hover:bg-rose-700'">
                    <i class="fas mr-1" :class="pr.direction === 'up' ? 'fa-arrow-up' : 'fa-arrow-down'"></i> Apply new price
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ================= PRODUCTS IN THIS PLAN ================= -->
<div x-show="prodBox" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="prodBox = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[92vh] overflow-y-auto">

        <div class="px-6 py-5 border-b border-slate-100 sticky top-0 bg-white z-10 flex items-center justify-between">
            <div>
                <h3 class="text-lg font-extrabold text-slate-800">Products in <span x-text="plan.name"></span></h3>
                <p class="text-xs text-slate-400">Add what the plan should carry, or drop what it should not</p>
            </div>
            <button type="button" @click="prodBox = false" class="w-9 h-9 rounded-xl bg-slate-100 text-slate-500 hover:bg-slate-200"><i class="fas fa-xmark"></i></button>
        </div>

        <div class="p-6 grid grid-cols-1 lg:grid-cols-2 gap-6">

            <!-- already in the plan -->
            <div>
                <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider mb-3">In this plan (<span x-text="items.length"></span>)</p>
                <div x-show="loading" class="py-12 text-center text-slate-400 text-xs"><i class="fas fa-circle-notch fa-spin text-xl block mb-2"></i>Loading…</div>
                <div class="space-y-2 max-h-[55vh] overflow-y-auto pr-1" x-show="!loading">
                    <template x-for="it in items" :key="it.id">
                        <div class="rounded-xl border border-slate-200 p-3">
                            <div class="flex items-start justify-between gap-2">
                                <div class="min-w-0">
                                    <p class="text-xs font-bold text-slate-800 truncate" x-text="it.title_show"></p>
                                    <p class="text-[10px] text-slate-400 uppercase" x-text="(it.cat_name || '') + ' · #' + it.service_id"></p>
                                </div>
                                <form method="POST" class="flex-shrink-0">
                                    <input type="hidden" name="remove_product" value="1">
                                    <input type="hidden" name="plan_id" :value="plan.id">
                                    <input type="hidden" name="item_id" :value="it.id">
                                    <button type="submit" class="w-7 h-7 rounded-lg bg-rose-50 text-rose-600 hover:bg-rose-100 text-xs" title="Remove from plan"><i class="fas fa-xmark"></i></button>
                                </form>
                            </div>
                            <form method="POST" class="mt-2 grid grid-cols-4 gap-2 items-end">
                                <input type="hidden" name="save_item" value="1">
                                <input type="hidden" name="plan_id" :value="plan.id">
                                <input type="hidden" name="item_id" :value="it.id">
                                <div><label class="lbl text-[9px]">% off</label><input type="number" step="0.01" min="0" max="100" name="item_pct" :value="it.discount_pct" class="fld !py-1.5 !text-[11px]" placeholder="plan"></div>
                                <div><label class="lbl text-[9px]">₹ off</label><input type="number" step="0.01" min="0" name="item_amt" :value="it.discount_amount" class="fld !py-1.5 !text-[11px]" placeholder="—"></div>
                                <label class="flex items-center gap-1 text-[10px] font-bold text-slate-600 pb-2"><input type="checkbox" name="is_free" :checked="it.is_free == 1" class="w-3.5 h-3.5 rounded accent-emerald-600"> Free</label>
                                <button type="submit" class="px-2 py-1.5 rounded-lg bg-slate-800 text-white text-[10px] font-bold">Save</button>
                            </form>
                            <p class="text-[10px] text-slate-400 mt-1.5">MRP ₹<span x-text="it.base_price"></span> → member pays <b class="text-emerald-600">₹<span x-text="it.member_price"></span></b></p>
                        </div>
                    </template>
                    <p x-show="!items.length && !loading" class="text-center text-xs text-slate-400 py-10">
                        No product picked yet. Choose some on the right, or set the plan to cover every product.
                    </p>
                </div>
            </div>

            <!-- picker -->
            <div>
                <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider mb-3">Add products</p>

                <form method="GET" class="grid grid-cols-3 gap-2 mb-3">
                    <input type="hidden" name="pplan" :value="plan.id">
                    <input type="text" name="pq" value="<?php echo htmlspecialchars($pick_q); ?>" class="fld col-span-2" placeholder="Search a product…">
                    <select name="pcat" class="fld">
                        <option value="">All categories</option>
                        <?php foreach ($cats as $c): ?>
                        <option value="<?php echo (int)$c['id']; ?>" <?php echo $pick_cat === (string)$c['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>

                <form method="POST">
                    <input type="hidden" name="add_products" value="1">
                    <input type="hidden" name="plan_id" :value="plan.id">
                    <div class="space-y-1.5 max-h-[48vh] overflow-y-auto pr-1 border border-slate-200 rounded-xl p-2">
                        <?php if (empty($pickable)): ?>
                        <p class="text-center text-xs text-slate-400 py-10">No product matched that search.</p>
                        <?php else: foreach ($pickable as $s):
                            $base = (float)($s['discount_price'] > 0 ? $s['discount_price'] : $s['price']); ?>
                        <label class="flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-slate-50 cursor-pointer">
                            <input type="checkbox" name="service_ids[]" value="<?php echo (int)$s['id']; ?>" class="w-4 h-4 rounded accent-indigo-600 flex-shrink-0">
                            <span class="min-w-0 flex-1">
                                <span class="block text-xs font-bold text-slate-700 truncate"><?php echo htmlspecialchars($s['title']); ?></span>
                                <span class="block text-[10px] text-slate-400 uppercase"><?php echo htmlspecialchars($s['cat_name'] ?: '—'); ?> · #<?php echo (int)$s['id']; ?></span>
                            </span>
                            <span class="text-[11px] font-bold text-slate-500 flex-shrink-0"><?php echo sp_money($base); ?></span>
                        </label>
                        <?php endforeach; endif; ?>
                    </div>
                    <button type="submit" class="w-full mt-3 px-4 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold hover:bg-indigo-700"><i class="fas fa-plus mr-1"></i> Add the ticked products to this plan</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- ================= PLAN HISTORY ================= -->
<div x-show="histBox" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="histBox = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[88vh] overflow-y-auto">
        <div class="px-6 py-5 border-b border-slate-100 sticky top-0 bg-white flex items-center justify-between">
            <div>
                <h3 class="text-lg font-extrabold text-slate-800">Plan history</h3>
                <p class="text-xs text-slate-400"><span x-text="plan.name"></span> — every price move and product change</p>
            </div>
            <button type="button" @click="histBox = false" class="w-9 h-9 rounded-xl bg-slate-100 text-slate-500 hover:bg-slate-200"><i class="fas fa-xmark"></i></button>
        </div>
        <div class="p-6 space-y-2">
            <div x-show="loading" class="py-12 text-center text-slate-400 text-xs"><i class="fas fa-circle-notch fa-spin text-xl block mb-2"></i>Loading…</div>
            <template x-for="h in history" :key="h.id">
                <div class="rounded-xl border border-slate-200 px-4 py-3">
                    <div class="flex items-start justify-between gap-3 flex-wrap">
                        <p class="text-xs font-bold" :class="h.action === 'price_up' ? 'text-emerald-600' : (h.action === 'price_down' ? 'text-rose-600' : 'text-slate-700')" x-text="h.field_label || h.action"></p>
                        <p class="text-[10px] text-slate-400" x-text="h.when"></p>
                    </div>
                    <p class="text-[11px] text-slate-600 mt-1">
                        <template x-if="h.old_value"><span class="line-through text-slate-400" x-text="h.old_value"></span></template>
                        <template x-if="h.new_value"><span> → <b x-text="h.new_value"></b></span></template>
                    </p>
                    <p class="text-[11px] text-slate-500 mt-1" x-show="h.remark" x-text="h.remark"></p>
                    <p class="text-[10px] text-slate-400 mt-1.5"><i class="fas fa-user mr-1"></i><span x-text="h.done_by_name || 'System'"></span></p>
                </div>
            </template>
            <p x-show="!history.length && !loading" class="text-center text-xs text-slate-400 py-10">Nothing has changed on this plan yet.</p>
        </div>
    </div>
</div>

<!-- ================= DELETE ================= -->
<div x-show="delBox" x-cloak class="fixed inset-0 z-[80] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="delBox = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-sm p-6 text-center">
        <div class="w-14 h-14 rounded-2xl bg-rose-50 text-rose-500 flex items-center justify-center text-xl mx-auto mb-4"><i class="fas fa-trash"></i></div>
        <h3 class="text-base font-extrabold text-slate-800 mb-1">Delete this plan?</h3>
        <p class="text-xs text-slate-500 mb-5">“<b x-text="delName"></b>” and its product list will be removed. If anyone is subscribed to it, hide it instead.</p>
        <form method="POST" class="flex gap-2">
            <input type="hidden" name="delete_plan" value="1">
            <input type="hidden" name="plan_id" :value="delId">
            <button type="button" @click="delBox = false" class="flex-1 px-4 py-2.5 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600">Keep it</button>
            <button type="submit" class="flex-1 px-4 py-2.5 rounded-xl bg-rose-600 text-white text-xs font-bold">Delete</button>
        </form>
    </div>
</div>

<script>
function planBoard() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        planBox: false, priceBox: false, prodBox: false, histBox: false, delBox: false,
        loading: false,
        plan: {}, items: [], history: [],
        delId: 0, delName: '',
        f: { id: 0, name: '', plan_code: '', tagline: '', description: '', mrp: 0, price: 0,
             duration_days: 365, discount_pct: 0, product_scope: 'selected', badge: '',
             color: 'indigo', features: '', sort_order: 0, status: true, is_popular: false },
        pr: { id: 0, name: '', price: 0, direction: 'up', mode: 'amount', value: 0 },

        /* a product search reloads the page — come back to the same plan's box */
        init() {
            const back = <?php echo (int)($_GET['pplan'] ?? 0); ?>;
            if (back > 0) { this.openProducts(back); }
        },

        async load(id) {
            this.loading = true; this.plan = {}; this.items = []; this.history = [];
            try {
                const r = await fetch('subscription_plans.php?ajax=1&id=' + id, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
                const j = await r.json();
                if (!j.ok) { alert(j.msg || 'Plan not found.'); this.loading = false; return null; }
                this.plan = j.plan; this.items = j.items || []; this.history = j.history || [];
                this.loading = false;
                return j.plan;
            } catch (e) { this.loading = false; alert('Could not load the plan.'); return null; }
        },

        async openPlan(id) {
            if (!id) {
                this.f = { id: 0, name: '', plan_code: '', tagline: '', description: '', mrp: 0, price: 0,
                           duration_days: 365, discount_pct: 0, product_scope: 'selected', badge: '',
                           color: 'indigo', features: '', sort_order: 0, status: true, is_popular: false };
                this.planBox = true;
                return;
            }
            const p = await this.load(id);
            if (!p) return;
            this.f = {
                id: p.id, name: p.name || '', plan_code: p.plan_code || '', tagline: p.tagline || '',
                description: p.description || '', mrp: p.mrp, price: p.price,
                duration_days: p.duration_days, discount_pct: p.discount_pct,
                product_scope: p.product_scope || 'selected', badge: p.badge || '',
                color: p.color || 'indigo', features: p.features || '', sort_order: p.sort_order || 0,
                status: String(p.status) === '1', is_popular: String(p.is_popular) === '1'
            };
            this.planBox = true;
        },

        openPrice(id, name, price, dir) {
            this.pr = { id: id, name: name, price: price, direction: dir, mode: 'amount', value: 0 };
            this.priceBox = true;
        },

        preview() {
            const cur = Number(this.pr.price) || 0;
            const v   = Number(this.pr.value) || 0;
            const s   = this.pr.direction === 'down' ? -1 : 1;
            let out;
            if (this.pr.mode === 'set')          out = v;
            else if (this.pr.mode === 'percent') out = cur + (s * cur * v / 100);
            else                                 out = cur + (s * v);
            return (Math.max(0, out)).toFixed(2);
        },

        async openProducts(id) { this.prodBox = true; await this.load(id); },
        async openHistory(id)  { this.histBox = true; await this.load(id); },
        askDelete(id, name)    { this.delId = id; this.delName = name; this.delBox = true; }
    };
}
</script>

</body>
</html>
