<?php
/* ============================================================================
   WBMCZ — Seller · Bulk Upload

   The seller version of the admin importer. Same three steps — choose a file,
   check the preview, import — with two rules of its own:

     · a seller may only import into the categories they are allowed to add to
     · every imported row lands as PENDING (status 0) and waits for the admin
       to approve it, exactly like a service typed in one at a time
   ============================================================================ */

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

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

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

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('../login.php'); }

try { shares_ensure_schema($db); } catch (\Throwable $e) {}

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']); }

/* ---------------------------------------------------------------------------
   Which categories may this seller submit to?
   --------------------------------------------------------------------------- */
$categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");

$no_add_cats = [];
try {
    foreach ($db->select("SELECT id, title FROM service_categories WHERE COALESCE(seller_can_add, 1) = 0") as $__nc) {
        $no_add_cats[(int)$__nc['id']] = $__nc['title'];
    }
} catch (\Throwable $e) {}

$seller_cat_ids = !empty($user['seller_categories']) ? array_map('intval', explode(',', $user['seller_categories'])) : [1, 5];

$my_cats = [];
foreach ($categories as $c) {
    $cid = (int)$c['id'];
    if (isset($no_add_cats[$cid])) continue;                 // admin managed
    if (!in_array($cid, $seller_cat_ids, true)) continue;    // not assigned to me
    $my_cats[] = $c;
}

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

/* ---------------------------------------------------------------------------
   Accepted CSV headers
   --------------------------------------------------------------------------- */
$IMP_COLS = [
    'title'          => ['title', 'name', 'product', 'product name', 'service', 'service name'],
    'description'    => ['description', 'desc', 'details', 'about'],
    'web_url'        => ['web_url', 'url', 'website', 'link', 'web link'],
    'app_url'        => ['app_url', 'app', 'app link', 'play store', 'android'],
    'tutorial_url'   => ['tutorial_url', 'tutorial', 'video', 'youtube', 'help video'],
    'icon_class'     => ['icon_class', 'icon', 'image', 'image_url', 'logo'],
    'color_class'    => ['color_class', 'color', 'colour'],
    'price'          => ['price', 'mrp', 'rate', 'amount'],
    'discount_price' => ['discount_price', 'selling price', 'sale price', 'offer price'],
    'sub_category'   => ['sub_category', 'sub category', 'subcategory', 'sub_cat', 'group'],
];

function simp_norm($s) { return strtolower(trim(preg_replace('/\s+/', ' ', (string)$s))); }

/* ---------------------------------------------------------------------------
   Sample CSV
   --------------------------------------------------------------------------- */
if (isset($_GET['template'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="wbmcz_seller_import_sample.csv"');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF));
    fputcsv($out, ['title', 'description', 'web_url', 'app_url', 'tutorial_url', 'icon_class', 'color_class', 'price', 'discount_price', 'sub_category']);
    fputcsv($out, ['Aadhaar Address Update', 'Address change with document support', 'https://myaadhaar.uidai.gov.in/', '', '', 'fa-id-card', 'color-1', '150', '99', '']);
    fputcsv($out, ['PAN Card Apply', 'New PAN application', 'https://www.onlineservices.nsdl.com/', '', '', 'fa-address-card', 'color-2', '200', '149', '']);
    fclose($out);
    exit;
}

/* ---------------------------------------------------------------------------
   STEP 2 — preview
   --------------------------------------------------------------------------- */
$preview     = null;
$parse_error = '';

if (isset($_POST['preview_csv'])) {
    $cat_id = (int)($_POST['category_id'] ?? 0);
    $sub_id = (int)($_POST['sub_category_id'] ?? 0);

    $allowed = false;
    foreach ($my_cats as $c) { if ((int)$c['id'] === $cat_id) { $allowed = true; break; } }

    if (!$allowed) {
        $parse_error = 'You cannot add services to that category. Pick one from the list.';
    } elseif (empty($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        $parse_error = 'No file was received. Please choose a .csv file and try again.';
    } else {
        $ext = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['csv', 'txt'], true)) {
            $parse_error = 'Only .csv files are supported. Save your Excel sheet as "CSV UTF-8" first.';
        } else {
            $fh = fopen($_FILES['csv_file']['tmp_name'], 'r');
            if (!$fh) {
                $parse_error = 'The file could not be opened.';
            } else {
                $header = fgetcsv($fh);
                if ($header && isset($header[0])) { $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]); }

                $map = [];
                if (is_array($header)) {
                    foreach ($header as $i => $h) {
                        $h = simp_norm($h);
                        foreach ($IMP_COLS as $key => $aliases) {
                            if (in_array($h, $aliases, true)) { $map[$key] = $i; break; }
                        }
                    }
                }

                if (!isset($map['title'])) {
                    $parse_error = 'A "title" column was not found in the first row. Download the sample CSV and use the same headers.';
                } else {
                    $existing = [];
                    try {
                        $rs = $db->select("SELECT title FROM seller_services WHERE seller_id = ? AND category_id = ?", [$user_id, $cat_id]);
                        foreach ($rs as $r) { $existing[simp_norm(html_entity_decode((string)$r['title'], ENT_QUOTES))] = true; }
                    } catch (\Throwable $e) {}

                    $sub_by_name = [];
                    foreach ($all_subs as $sc) {
                        if ((int)$sc['category_id'] === $cat_id) {
                            $sub_by_name[simp_norm(html_entity_decode((string)$sc['title'], ENT_QUOTES))] = (int)$sc['id'];
                        }
                    }

                    $rows = []; $seen = []; $line = 1; $n_ok = 0; $n_dup = 0; $n_err = 0;
                    while (($data = fgetcsv($fh)) !== false) {
                        $line++;
                        if (count(array_filter($data, function ($v) { return trim((string)$v) !== ''; })) === 0) continue;
                        if (count($rows) >= 500) break;                       // sellers get a smaller ceiling

                        $get = function ($key) use ($map, $data) {
                            return isset($map[$key], $data[$map[$key]]) ? trim((string)$data[$map[$key]]) : '';
                        };

                        $r = [
                            'line' => $line, 'title' => $get('title'), 'description' => $get('description'),
                            'web_url' => $get('web_url'), 'app_url' => $get('app_url'),
                            'tutorial_url' => $get('tutorial_url'), 'icon_class' => $get('icon_class'),
                            'color_class' => $get('color_class'), 'price' => $get('price'),
                            'discount_price' => $get('discount_price'), 'sub_raw' => $get('sub_category'),
                        ];

                        $verdict = 'ok'; $note = '';
                        $key = simp_norm($r['title']);

                        if ($r['title'] === '')                    { $verdict = 'error'; $note = 'Title is empty'; }
                        elseif (mb_strlen($r['title']) > 250)      { $verdict = 'error'; $note = 'Title is longer than 250 characters'; }
                        elseif (isset($seen[$key]))                { $verdict = 'dup';   $note = 'Repeated in this file (line ' . $seen[$key] . ')'; }
                        elseif (isset($existing[$key]))            { $verdict = 'dup';   $note = 'You already have this one in this category'; }
                        $seen[$key] = $line;

                        foreach (['web_url', 'app_url', 'tutorial_url'] as $u) {
                            if ($r[$u] !== '' && !preg_match('~^https?://~i', $r[$u])) { $r[$u] = 'https://' . ltrim($r[$u], '/'); }
                        }

                        $sub = $sub_id;
                        if ($r['sub_raw'] !== '') {
                            if (ctype_digit($r['sub_raw'])) { $sub = (int)$r['sub_raw']; }
                            elseif (isset($sub_by_name[simp_norm($r['sub_raw'])])) { $sub = $sub_by_name[simp_norm($r['sub_raw'])]; }
                            else { $note = trim($note . ' · sub-category "' . $r['sub_raw'] . '" not found, page default used', ' ·'); }
                        }
                        $r['sub_id'] = $sub;

                        $price = (float)preg_replace('/[^0-9.]/', '', $r['price']);
                        $disc  = (float)preg_replace('/[^0-9.]/', '', $r['discount_price']);
                        if ($cat_id === 1) { $price = 0.0; $disc = 0.0; }
                        if ($disc > 0 && $price > 0 && $disc > $price) {
                            $verdict = ($verdict === 'ok') ? 'error' : $verdict;
                            $note = 'Discount price is higher than the price';
                        }
                        $r['price_f'] = $price; $r['disc_f'] = $disc;

                        $icon = $r['icon_class'];
                        $r['is_img'] = (strpos($icon, 'http') === 0 || strpos($icon, 'uploads/') === 0) ? 1 : 0;
                        $r['icon_f']  = $icon !== '' ? $icon : 'fa-cube';
                        $r['color_f'] = $r['color_class'] !== '' ? $r['color_class'] : 'color-1';

                        $r['verdict'] = $verdict; $r['note'] = $note;
                        if ($verdict === 'ok') $n_ok++; elseif ($verdict === 'dup') $n_dup++; else $n_err++;
                        $rows[] = $r;
                    }
                    fclose($fh);

                    if (empty($rows)) {
                        $parse_error = 'The file has a header row but no data rows.';
                    } else {
                        $preview = ['rows' => $rows, 'cat_id' => $cat_id, 'sub_id' => $sub_id,
                                    'file' => $_FILES['csv_file']['name'],
                                    'ok' => $n_ok, 'dup' => $n_dup, 'err' => $n_err];
                    }
                }
            }
        }
    }
    if ($parse_error !== '') { $error_msg = $parse_error; }
}

/* ---------------------------------------------------------------------------
   STEP 3 — write, always as pending
   --------------------------------------------------------------------------- */
if (isset($_POST['confirm_import'])) {
    $cat_id = (int)($_POST['category_id'] ?? 0);

    $allowed = false;
    foreach ($my_cats as $c) { if ((int)$c['id'] === $cat_id) { $allowed = true; break; } }
    if (!$allowed) {
        $_SESSION['flash_error'] = 'You cannot add services to that category.';
        redirect('service_import.php');
    }

    $payload  = json_decode(base64_decode((string)($_POST['payload'] ?? '')), true);
    $keep_dup = !empty($_POST['include_duplicates']);

    if (!is_array($payload) || empty($payload)) {
        $_SESSION['flash_error'] = 'Nothing to import — the preview had expired. Please upload the file again.';
        redirect('service_import.php');
    }

    $made = 0; $skipped = 0; $failed = 0;
    foreach ($payload as $r) {
        $verdict = $r['verdict'] ?? 'ok';
        if ($verdict === 'error') { $skipped++; continue; }
        if ($verdict === 'dup' && !$keep_dup) { $skipped++; continue; }

        try {
            $ok = $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 (?,?,?,?,?,?,?,?,?,?,?,?,?,0)",
                [
                    $user_id, $cat_id, (int)($r['sub_id'] ?? 0),
                    sanitize($r['title'] ?? ''), sanitize($r['description'] ?? ''),
                    (float)($r['price_f'] ?? 0), (float)($r['disc_f'] ?? 0),
                    (int)($r['is_img'] ?? 0), sanitize($r['icon_f'] ?? 'fa-cube'),
                    sanitize($r['color_f'] ?? 'color-1'), sanitize($r['web_url'] ?? ''),
                    sanitize($r['app_url'] ?? ''), sanitize($r['tutorial_url'] ?? ''),
                ]
            );
            if ($ok) $made++; else $failed++;
        } catch (\Throwable $e) { $failed++; }
    }

    $_SESSION['flash_success'] = "Uploaded — $made service(s) sent for admin approval"
        . ($skipped ? ", $skipped skipped" : '') . ($failed ? ", $failed failed" : '') . '.';
    redirect('service_import.php');
}

/* recent uploads */
$recent = [];
try {
    $recent = $db->select("SELECT ss.id, ss.title, ss.status, ss.created_at, sc.title AS cat_name
                           FROM seller_services ss LEFT JOIN service_categories sc ON ss.category_id = sc.id
                           WHERE ss.seller_id = ? ORDER BY ss.id DESC LIMIT 10", [$user_id]);
} catch (\Throwable $e) {}

$unread_notifs  = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo   = getSetting('company_logo', '../assets/images/logo.png');
$company_logo   = (strpos($company_logo, 'http') === 0) ? $company_logo : '../' . ltrim($company_logo, '/');
$company_name   = getSetting('company_name', 'WBMCZ');

$sel_cat = (int)($preview['cat_id'] ?? ($_POST['category_id'] ?? (!empty($my_cats) ? $my_cats[0]['id'] : 0)));
?>
<!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>Bulk Upload - <?php echo htmlspecialchars($company_name); ?></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=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter',sans-serif; }
        .sl { display:block; font-size:10px; font-weight:800; color:#64748b; margin-bottom:.25rem; text-transform:uppercase; letter-spacing:.05em; }
        .sf { width:100%; padding:.65rem .8rem; background:#fff; border:1.5px solid #cbd5e1; border-radius:.8rem; font-size:.84rem; outline:none; color:#0f172a; }
        .sf:focus { border-color:#C8901B; box-shadow:0 0 0 3px rgba(200,144,27,.15); }
        .drop { border:2px dashed #cbd5e1; border-radius:1rem; background:#f8fafc; padding:1.75rem 1rem; text-align:center; cursor:pointer; transition:.15s; }
        .drop:hover { border-color:#C8901B; background:#fffbf2; }
        .itbl { width:100%; border-collapse:collapse; font-size:11.5px; }
        .itbl th { background:#f8fafc; text-align:left; padding:.55rem .6rem; font-size:9.5px; font-weight:900;
                   text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; border-bottom:1px solid #e2e8f0; position:sticky; top:0; }
        .itbl td { padding:.5rem .6rem; border-bottom:1px solid #f1f5f9; color:#334155; vertical-align:top; }
        .itbl tr.err td { background:#fff1f2; } .itbl tr.dup td { background:#fffbeb; }
        .ipill { display:inline-flex; align-items:center; gap:.3rem; padding:.15rem .5rem; border-radius:999px;
                 font-size:9.5px; font-weight:900; text-transform:uppercase; letter-spacing:.05em; }
        .iok { background:#dcfce7; color:#15803d; } .idp { background:#fef3c7; color:#b45309; } .ier { background:#ffe4e6; color:#be123c; }
        .icode { font-family:ui-monospace,'Courier New',monospace; font-size:10.5px; color:#475569; background:#f1f5f9; padding:.1rem .35rem; border-radius:.35rem; }
        .btn-gold { background:linear-gradient(135deg,#C8901B,#a8760f); color:#fff; }
    </style>
</head>
<?php
require_once __DIR__ . '/../includes/theme.php';
$__scats = [];
foreach ($categories as $__c) { if (in_array((int)$__c['id'], $seller_cat_ids, true)) $__scats[] = $__c; }
$__menu = theme_seller_menu($__scats);
theme_open([
    'panel'  => 'seller',
    'base'   => '../',
    'title'  => 'Bulk Upload',
    'active' => 'services',
    'user'   => $user,
    'wallet' => $wallet_balance,
    'notifs' => $unread_notifs,
    'logo'   => $company_logo,
    'brand'  => $company_name,
    'menu'   => $__menu,
    'state'  => "fileName: ''",
]);
?>

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

                <?php if (isset($success_msg)): ?>
                <div class="mb-5 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 mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($success_msg); ?></span>
                </div>
                <?php endif; ?>
                <?php if (isset($error_msg)): ?>
                <div class="mb-5 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-triangle-exclamation mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($error_msg); ?></span>
                </div>
                <?php endif; ?>

                <div class="mb-6 flex flex-wrap items-start justify-between gap-3">
                    <div>
                        <h2 class="text-2xl font-bold text-slate-800 mb-1">Bulk Upload</h2>
                        <p class="text-slate-500 text-sm">Add many services at once from a CSV file instead of typing them one by one.</p>
                    </div>
                    <div class="flex gap-2">
                        <a href="service_import.php?template=1" class="px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-slate-600 text-sm font-bold"><i class="fas fa-file-csv mr-1"></i>Sample CSV</a>
                        <a href="services.php" class="px-4 py-2.5 rounded-xl btn-gold text-sm font-bold"><i class="fas fa-list mr-1"></i>My Services</a>
                    </div>
                </div>

                <?php if (empty($my_cats)): ?>
                    <div class="bg-white border border-slate-200 rounded-2xl p-10 text-center">
                        <i class="fas fa-lock text-4xl text-slate-300 mb-3"></i>
                        <p class="font-bold text-slate-700">No category is open to you yet</p>
                        <p class="text-sm text-slate-500 mt-1">Ask the admin to assign you a category you can submit services to.</p>
                    </div>

                <?php elseif (!$preview): ?>
                <!-- ============== STEP 1 ============== -->
                <div class="grid grid-cols-1 xl:grid-cols-3 gap-5">
                    <form method="POST" enctype="multipart/form-data" class="bg-white border border-slate-200 rounded-2xl p-5 xl:col-span-2">
                        <h3 class="text-base font-extrabold text-slate-800 mb-1"><i class="fas fa-file-import text-amber-600 mr-2"></i>Upload a CSV</h3>
                        <p class="text-xs text-slate-500 mb-5">Each row becomes one service. Nothing is saved until you have seen the preview.</p>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
                            <div>
                                <label class="sl">Category</label>
                                <select name="category_id" class="sf">
                                    <?php foreach ($my_cats as $c): ?>
                                        <option value="<?php echo (int)$c['id']; ?>" <?php echo ((int)$c['id'] === $sel_cat) ? 'selected' : ''; ?>><?php echo esc($c['title']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <?php if (!empty($no_add_cats)): ?>
                                <p class="text-[10px] text-slate-400 mt-1">
                                    <?php echo esc(implode(', ', $no_add_cats)); ?> — managed by the admin, you can sell them but not add to them.
                                </p>
                                <?php endif; ?>
                            </div>
                            <div>
                                <label class="sl">Default sub-category <span class="text-slate-400 normal-case font-medium">(optional)</span></label>
                                <select name="sub_category_id" class="sf">
                                    <option value="0">— none —</option>
                                    <?php foreach ($all_subs as $sc): ?>
                                        <option value="<?php echo (int)$sc['id']; ?>"><?php echo esc($sc['title']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="text-[10px] text-slate-400 mt-1">Sub-categories are created by the admin — pick one, you cannot add new ones.</p>
                            </div>
                        </div>

                        <label class="drop block" for="csvFile">
                            <i class="fas fa-cloud-arrow-up text-3xl text-amber-500 mb-2"></i>
                            <p class="text-sm font-bold text-slate-700" x-text="fileName || 'Click to choose a .csv file'"></p>
                            <p class="text-[11px] text-slate-400 mt-1">Up to 500 rows per file · UTF-8 CSV</p>
                            <input id="csvFile" type="file" name="csv_file" accept=".csv,text/csv" class="hidden"
                                   @change="fileName = $event.target.files.length ? $event.target.files[0].name : ''">
                        </label>

                        <div class="flex flex-wrap gap-2 mt-5">
                            <button type="submit" name="preview_csv" value="1" class="px-5 py-2.5 rounded-xl btn-gold text-sm font-bold"><i class="fas fa-eye mr-1"></i>Preview rows</button>
                            <a href="service_import.php?template=1" class="px-5 py-2.5 rounded-xl bg-slate-100 text-slate-600 text-sm font-bold"><i class="fas fa-download mr-1"></i>Sample</a>
                        </div>
                    </form>

                    <div class="bg-white border border-slate-200 rounded-2xl p-5">
                        <h3 class="text-sm font-extrabold text-slate-800 mb-3"><i class="fas fa-circle-info text-slate-400 mr-1.5"></i>Column reference</h3>
                        <ul class="text-[11.5px] text-slate-600 space-y-2">
                            <li><span class="icode">title</span> <b class="text-rose-500">required</b></li>
                            <li><span class="icode">description</span></li>
                            <li><span class="icode">web_url</span> · <span class="icode">app_url</span> · <span class="icode">tutorial_url</span></li>
                            <li><span class="icode">icon_class</span> Font Awesome class or an image URL</li>
                            <li><span class="icode">color_class</span> color-1 … color-8</li>
                            <li><span class="icode">price</span> · <span class="icode">discount_price</span></li>
                            <li><span class="icode">sub_category</span> name or id</li>
                        </ul>
                        <div class="mt-4 text-[11px] bg-amber-50 border border-amber-100 text-amber-800 rounded-xl p-3 leading-relaxed">
                            Everything you upload arrives as <b>Pending</b> and goes live once the admin approves it —
                            the same as adding a service by hand.
                        </div>
                    </div>
                </div>

                <?php if (!empty($recent)): ?>
                <div class="bg-white border border-slate-200 rounded-2xl mt-5 overflow-hidden">
                    <div class="px-5 py-3 border-b border-slate-100"><h3 class="text-sm font-extrabold text-slate-800"><i class="fas fa-clock-rotate-left text-slate-400 mr-1.5"></i>Recently added</h3></div>
                    <div class="overflow-x-auto">
                        <table class="itbl">
                            <thead><tr><th>#</th><th>Title</th><th>Category</th><th>Status</th><th>Added</th></tr></thead>
                            <tbody>
                            <?php foreach ($recent as $r): ?>
                                <tr>
                                    <td><?php echo (int)$r['id']; ?></td>
                                    <td class="font-bold text-slate-700"><?php echo esc($r['title']); ?></td>
                                    <td><?php echo esc($r['cat_name']); ?></td>
                                    <td><?php echo ((int)$r['status'] === 1) ? '<span class="ipill iok">Approved</span>' : '<span class="ipill idp">Pending</span>'; ?></td>
                                    <td class="text-slate-400"><?php echo !empty($r['created_at']) ? date('d M Y', strtotime($r['created_at'])) : '—'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>

                <?php else: ?>
                <!-- ============== STEP 2 — PREVIEW ============== -->
                <?php
                    $cat_title = 'Category #' . $preview['cat_id'];
                    foreach ($my_cats as $c) { if ((int)$c['id'] === (int)$preview['cat_id']) { $cat_title = $c['title']; break; } }
                    $payload = base64_encode(json_encode($preview['rows']));
                ?>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
                    <div class="bg-white border border-slate-200 rounded-2xl p-4"><p class="text-[10px] font-black uppercase text-slate-400">Rows in file</p><p class="text-2xl font-extrabold text-slate-800"><?php echo count($preview['rows']); ?></p></div>
                    <div class="bg-white border border-slate-200 rounded-2xl p-4"><p class="text-[10px] font-black uppercase text-slate-400">Ready</p><p class="text-2xl font-extrabold text-emerald-600"><?php echo $preview['ok']; ?></p></div>
                    <div class="bg-white border border-slate-200 rounded-2xl p-4"><p class="text-[10px] font-black uppercase text-slate-400">Duplicates</p><p class="text-2xl font-extrabold text-amber-600"><?php echo $preview['dup']; ?></p></div>
                    <div class="bg-white border border-slate-200 rounded-2xl p-4"><p class="text-[10px] font-black uppercase text-slate-400">Errors</p><p class="text-2xl font-extrabold text-rose-600"><?php echo $preview['err']; ?></p></div>
                </div>

                <form method="POST" class="bg-white border border-slate-200 rounded-2xl overflow-hidden">
                    <input type="hidden" name="category_id" value="<?php echo (int)$preview['cat_id']; ?>">
                    <input type="hidden" name="payload" value="<?php echo $payload; ?>">

                    <div class="px-5 py-4 border-b border-slate-100 flex flex-wrap items-center justify-between gap-3">
                        <div>
                            <h3 class="text-base font-extrabold text-slate-800">Check before uploading</h3>
                            <p class="text-xs text-slate-500 mt-0.5">
                                <?php echo esc($cat_title); ?> · <?php echo esc($preview['file']); ?> —
                                <b class="text-emerald-600"><?php echo $preview['ok']; ?></b> row(s) will be sent for approval.
                            </p>
                        </div>
                        <div class="flex flex-wrap items-center gap-2">
                            <?php if ($preview['dup'] > 0): ?>
                            <label class="flex items-center gap-2 text-[11.5px] font-bold text-amber-700 bg-amber-50 border border-amber-200 rounded-xl px-3 py-2">
                                <input type="checkbox" name="include_duplicates" value="1" class="rounded">
                                Upload the <?php echo $preview['dup']; ?> duplicate(s) too
                            </label>
                            <?php endif; ?>
                            <a href="service_import.php" class="px-4 py-2.5 rounded-xl bg-slate-100 text-slate-600 text-sm font-bold">Start over</a>
                            <button type="submit" name="confirm_import" value="1" class="px-5 py-2.5 rounded-xl btn-gold text-sm font-bold"
                                    <?php echo ($preview['ok'] === 0 && $preview['dup'] === 0) ? 'disabled style="opacity:.5;cursor:not-allowed"' : ''; ?>>
                                <i class="fas fa-cloud-arrow-up mr-1"></i>Upload now
                            </button>
                        </div>
                    </div>

                    <div class="overflow-x-auto" style="max-height:60vh">
                        <table class="itbl">
                            <thead><tr><th>Line</th><th>Verdict</th><th>Title</th><th>Link</th><th>Icon</th><th>Price</th><th>Note</th></tr></thead>
                            <tbody>
                            <?php foreach ($preview['rows'] as $r):
                                $cls  = $r['verdict'] === 'error' ? 'err' : ($r['verdict'] === 'dup' ? 'dup' : '');
                                $pill = $r['verdict'] === 'error' ? '<span class="ipill ier">Error</span>'
                                      : ($r['verdict'] === 'dup' ? '<span class="ipill idp">Duplicate</span>' : '<span class="ipill iok">Ready</span>');
                            ?>
                                <tr class="<?php echo $cls; ?>">
                                    <td class="text-slate-400"><?php echo (int)$r['line']; ?></td>
                                    <td><?php echo $pill; ?></td>
                                    <td class="font-bold text-slate-700" style="max-width:220px"><?php echo esc($r['title']); ?></td>
                                    <td style="max-width:200px;word-break:break-all"><?php echo $r['web_url'] !== '' ? '<span class="icode">' . esc($r['web_url']) . '</span>' : '<span class="text-slate-300">—</span>'; ?></td>
                                    <td><span class="icode"><?php echo esc($r['icon_f']); ?></span></td>
                                    <td><?php echo $r['price_f'] > 0 ? '₹' . number_format($r['price_f'], 2) : '<span class="text-emerald-600 font-bold">Free</span>'; ?></td>
                                    <td class="text-slate-500" style="max-width:230px"><?php echo esc($r['note']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </form>
                <?php endif; ?>

            </main>
        </div>
    </div>
</body>
</html>
