<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
ob_start();

// Load configuration and database
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/functions.php';
// Legacy function compatibility
function gsSanitize($str) { return sanitize($str); }
function gsGenId($prefix='GS') { return generateId($prefix); }
function gsSlug($text) {
    $slug = strtolower(trim((string)$text));
    $slug = preg_replace('/[^a-z0-9]+/i', '-', $slug);
    return trim($slug, '-');
}
function gsRedirect($url) { redirect($url); }
function gsImgUrl($path) { return imgUrl($path); }
function gsLog($action, $detail='') {
    $adminId = $_SESSION['gs_admin']['admin_id'] ?? null;
    logActivity($action, $detail, null, $adminId);
}

// FIX: image handling used raw GD functions with no check that the GD
// extension is even installed. On any host without GD, imagecreatefromstring()
// is an undefined function and PHP throws a fatal error the instant someone
// uploads a product image or (previously) a banner — killing the whole request
// before it could return JSON. This helper falls back to a plain file copy
// when GD isn't available, so uploads always succeed.
// FIX (image bug continued): now returns a RELATIVE path ("uploads/products/xxx.jpg")
// instead of the absolute filesystem path, so it can be used directly as an <img src>.
function gsProcessImage($tmpPath, $origName, $subfolder) {
    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    if(!in_array($ext, ['jpg','jpeg','png','gif','webp'])) return null;
    $fname = $subfolder.'/'.gsGenId('IMG').'.'.$ext;
    $dest = GS_UPLOADS.'/'.$fname;
    $relPath = 'uploads/'.$fname;

    if(function_exists('imagecreatefromstring') && function_exists('imagecreatetruecolor')) {
        $raw = @file_get_contents($tmpPath);
        $src = $raw !== false ? @imagecreatefromstring($raw) : false;
        if($src) {
            $w = imagesx($src); $h = imagesy($src);
            $maxW = 800; $maxH = 800;
            $ratio = min($maxW/$w, $maxH/$h, 1);
            $nw = max(1, (int)round($w*$ratio));
            $nh = max(1, (int)round($h*$ratio));
            $dst = imagecreatetruecolor($nw, $nh);
            if($ext==='png' || $ext==='gif') {
                imagealphablending($dst, false);
                imagesavealpha($dst, true);
                $transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                imagefilledrectangle($dst, 0, 0, $nw, $nh, $transparent);
            }
            imagecopyresampled($dst, $src, 0, 0, 0, 0, $nw, $nh, $w, $h);
            $ok = imagejpeg($dst, $dest, 85);
            imagedestroy($src); imagedestroy($dst);
            if($ok) return $relPath;
        }
    }
    // Fallback: GD missing or failed to read image — just store the original file
    if(@move_uploaded_file($tmpPath, $dest)) return $relPath;
    if(@copy($tmpPath, $dest)) return $relPath;
    return null;
}

// ===================================================================
// LANDING PAGE SYSTEM (additive — does not modify product/order logic)
// ===================================================================
if(!is_dir(GS_UPLOADS.'/landing')) mkdir(GS_UPLOADS.'/landing', 0777, true);

function gsBaseUrl() {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || ($_SERVER['SERVER_PORT']??'')==443 ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $dir = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'] ?? '/admin.php')), '/');
    return $scheme.'://'.$host.$dir;
}
function gsLandingUrl($slug) { return gsBaseUrl().'/landing.php?slug='.rawurlencode($slug); }

function gsLandingDefault($product) {
    $now = date('Y-m-d H:i:s');
    return [
        'product_id'=>$product['id'], 'slug'=>gsSlug($product['title'] ?? 'product'),
        'enabled'=>true, 'headline'=>$product['title'] ?? '', 'description'=>$product['subtitle'] ?? '',
        'banner_image'=>'', 'promo_video_url'=>'', 'countdown_enabled'=>false, 'countdown_end'=>'',
        'benefits'=>[], 'before_image'=>'', 'after_image'=>'',
        'testimonials'=>[], 'feature_icons'=>[], 'faq'=>[], 'cta_text'=>'Order Now',
        'delivery_info'=>"Delivery within 24-72 hours nationwide.\nCash on Delivery available.\nFree delivery on orders over ৳2000.",
        'return_policy'=>"7-day easy return if the product is unused and in original packaging.\nContact support to start a return.",
        'fb_pixel'=>'', 'tiktok_pixel'=>'', 'ga_id'=>'', 'meta_tags'=>'',
        'seo_title'=>$product['title'] ?? '', 'seo_description'=>$product['subtitle'] ?? ($product['description'] ?? ''),
        'seo_keywords'=>'', 'og_image'=>'', 'canonical_url'=>'',
        'views'=>0, 'clicks'=>0, 'add_to_cart'=>0, 'orders'=>0,
        'created'=>$now, 'updated'=>$now
    ];
}

function gsUniqueLandingSlug($base, $excludeProductId, $existingList) {
    $base = $base !== '' ? $base : 'product';
    $slug = $base; $i = 2;
    $taken = function($s) use ($existingList, $excludeProductId) {
        foreach($existingList as $l) { if($l['slug']===$s && $l['product_id']!==$excludeProductId) return true; }
        return false;
    };
    while($taken($slug)) { $slug = $base.'-'.$i; $i++; }
    return $slug;
}

// ===== LOGIN REMOVED — Auto-set admin session =====
if(!isset($_SESSION['gs_admin'])) {
    $_SESSION['gs_admin'] = ['username'=>'admin', 'admin_id'=>'ADM-00000001', 'login_time'=>date('Y-m-d H:i:s')];
}
// ===== END LOGIN REMOVED =====

// CSRF
if(!empty($_COOKIE['gs_csrf']) && preg_match('/^[a-f0-9]{64}$/', $_COOKIE['gs_csrf'])) {
    $csrf = $_COOKIE['gs_csrf'];
} elseif(!empty($_SESSION['gs_csrf'])) {
    $csrf = $_SESSION['gs_csrf'];
} else {
    $csrf = bin2hex(random_bytes(32));
}
setcookie('gs_csrf', $csrf, time()+60*60*24*90, '/', '', false, true);
$_SESSION['gs_csrf'] = $csrf;

// Load data from database
$settings = getSettings();
$categories = getCategories();
$products = getProducts();
$banners = getBanners();
$coupons = getCoupons();
$landingPages = getLandingPages();

// Handle POST actions
if($_SERVER['REQUEST_METHOD']==='POST') {
    header('Content-Type: application/json');

    // FIX: turn PHP warnings/errors during an AJAX request into a clean JSON
    // response instead of raw HTML — this is what used to show up client-side
    // as a broken "card error" (the browser couldn't parse the response as JSON).
    set_error_handler(function($errno, $errstr, $errfile, $errline) {
        if(in_array($errno, [E_WARNING, E_ERROR, E_USER_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_RECOVERABLE_ERROR])) {
            throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
        }
        return true; // swallow notices/deprecations, keep output clean
    });

    try {
        $rawInput = json_decode(file_get_contents('php://input'), true);
        $input = (is_array($rawInput) && !empty($rawInput)) ? $rawInput : $_POST;
        // FIX: $action MUST come from $input, not $_POST directly. $_POST is only
        // populated for multipart/form-encoded requests. Every plain-JSON request
        // (all deletes, status updates, settings save, bulk actions, etc.) left
        // $_POST empty, so $action was always '', and the switch below always fell
        // through to "Invalid action" no matter what was actually requested.
        $action = $input['action'] ?? '';

        if(($input['csrf_token']??'') !== $csrf) { echo json_encode(['success'=>false,'msg'=>'CSRF error - please refresh the page and try again']); exit; }

        switch($action) {
            case 'logout':
                // Logout করলেও আবার admin হিসেবে সেট হবে
                $_SESSION['gs_admin'] = ['username'=>'admin', 'login_time'=>date('Y-m-d H:i:s')];
                echo json_encode(['success'=>true,'redirect'=>'admin.php']);
                exit;

            case 'save_settings':
                $fields = ['site_name','tagline','primary_color','secondary_color','accent_color','currency','currency_code','facebook','tiktok','instagram','whatsapp','messenger','telegram','youtube','linkedin','google_analytics','facebook_pixel','seo_title','seo_description','seo_keywords','promo_text'];
                foreach($fields as $f) { 
                    if(isset($input[$f])) {
                        updateSetting($f, gsSanitize($input[$f]));
                    }
                }
                updateSetting('maintenance', ($input['maintenance']??'0')==='1', 'boolean');
                updateSetting('promo_popup', ($input['promo_popup']??'0')==='1', 'boolean');
                updateSetting('cookie_notice', ($input['cookie_notice']??'0')==='1', 'boolean');
                gsLog('Settings Updated');
                echo json_encode(['success'=>true,'msg'=>'Settings saved']);
                exit;

            case 'add_category':
                if(empty(trim($input['name']??''))) { echo json_encode(['success'=>false,'msg'=>'Category name is required']); exit; }
                $categoryId = gsGenId('CAT');
                Database::getInstance()->insert('categories', [
                    'category_id' => $categoryId,
                    'name' => gsSanitize($input['name']),
                    'icon' => gsSanitize($input['icon']??'fa-box'),
                    'status' => 1
                ]);
                gsLog('Category Added', gsSanitize($input['name']));
                echo json_encode(['success'=>true,'msg'=>'Category added']);
                exit;

            case 'delete_category':
                db()->query("DELETE FROM categories WHERE category_id = ?", [$input['id']]);
                echo json_encode(['success'=>true,'msg'=>'Deleted']);
                exit;

            case 'add_product':
                if(empty(trim($input['title']??''))) { echo json_encode(['success'=>false,'msg'=>'Product title is required']); exit; }
                $images = [];
                if(!empty($_FILES['images'])) {
                    foreach($_FILES['images']['tmp_name'] as $i=>$tmp) {
                        if(($_FILES['images']['error'][$i]??1)===0) {
                            $saved = gsProcessImage($tmp, $_FILES['images']['name'][$i], 'products');
                            if($saved) $images[] = $saved;
                        }
                    }
                }
                $offerPrice = floatval($input['offer_price']??0);
                $price = floatval($input['price']??0);
                $discPct = ($offerPrice > 0 && $offerPrice < $price) ? round((1-$offerPrice/$price)*100) : 0;
                $specs = [];
                if(!empty($input['spec_keys'])) {
                    foreach($input['spec_keys'] as $si=>$sk) {
                        if(!empty($sk) && !empty($input['spec_values'][$si])) $specs[gsSanitize($sk)] = gsSanitize($input['spec_values'][$si]);
                    }
                }
                $productId = gsGenId('PRD');
                $productData = [
                    'product_id' => $productId,
                    'title' => gsSanitize($input['title']),
                    'subtitle' => gsSanitize($input['subtitle']??''),
                    'slug' => gsSlug($input['title']),
                    'brand' => gsSanitize($input['brand']??''),
                    'category_id' => gsSanitize($input['category']??''),
                    'sub_category' => gsSanitize($input['sub_category']??''),
                    'description' => gsSanitize($input['description']??''),
                    'features' => $input['features']??'',
                    'specifications' => json_encode($specs),
                    'price' => $price,
                    'offer_price' => $offerPrice,
                    'discount' => $discPct,
                    'stock' => intval($input['stock']??0),
                    'warranty' => gsSanitize($input['warranty']??''),
                    'color' => gsSanitize($input['color']??''),
                    'sizes' => gsSanitize($input['sizes']??''),
                    'size_unit' => gsSanitize($input['size_unit']??''),
                    'featured' => ($input['featured']??0)==1,
                    'trending' => ($input['trending']??0)==1,
                    'best_seller' => ($input['best_seller']??0)==1,
                    'flash_sale' => ($input['flash_sale']??0)==1,
                    'new_arrival' => ($input['new_arrival']??0)==1,
                    'recommended' => ($input['recommended']??0)==1,
                    'status' => ($input['status']??1)==1,
                    'views' => 0,
                    'rating' => 0,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                Database::getInstance()->insert('products', $productData);
                
                // Insert product images
                foreach($images as $index => $image) {
                    Database::getInstance()->insert('product_images', [
                        'product_id' => $productId,
                        'image_path' => $image,
                        'image_order' => $index
                    ]);
                }
                
                gsLog('Product Added', $productData['title']);
                echo json_encode(['success'=>true,'msg'=>'Product added','id'=>$productId]);
                exit;

            case 'update_product':
                $products = gsRead('products');
                $idx = array_search($input['id'], array_column($products, 'id'));
                if($idx===false) { echo json_encode(['success'=>false,'msg'=>'Not found']); exit; }
                $p = $products[$idx];
                $fields = ['title','subtitle','brand','category','sub_category','description','features','warranty','color','sizes','size_unit'];
                foreach($fields as $f) { if(isset($input[$f])) $p[$f] = gsSanitize($input[$f]); }
                $p['slug'] = gsSlug($input['title'] ?? $p['title']);
                $p['price'] = floatval($input['price'] ?? $p['price']);
                $p['offer_price'] = floatval($input['offer_price'] ?? $p['offer_price']);
                $p['discount'] = ($p['offer_price']>0&&$p['offer_price']<$p['price']) ? round((1-$p['offer_price']/$p['price'])*100) : 0;
                $p['stock'] = intval($input['stock'] ?? $p['stock']);
                $p['featured'] = ($input['featured']??0)==1;
                $p['trending'] = ($input['trending']??0)==1;
                $p['best_seller'] = ($input['best_seller']??0)==1;
                $p['flash_sale'] = ($input['flash_sale']??0)==1;
                $p['new_arrival'] = ($input['new_arrival']??0)==1;
                $p['recommended'] = ($input['recommended']??0)==1;
                $p['status'] = ($input['status']??1)==1;
                if(!empty($input['spec_keys'])) {
                    $specs = [];
                    foreach($input['spec_keys'] as $si=>$sk) { if(!empty($sk)&&!empty($input['spec_values'][$si])) $specs[gsSanitize($sk)]=gsSanitize($input['spec_values'][$si]); }
                    $p['specifications'] = $specs;
                }
                if(!empty($_FILES['new_images'])) {
                    foreach($_FILES['new_images']['tmp_name'] as $i=>$tmp) {
                        if(($_FILES['new_images']['error'][$i]??1)===0) {
                            $saved = gsProcessImage($tmp, $_FILES['new_images']['name'][$i], 'products');
                            if($saved) $p['images'][] = $saved;
                        }
                    }
                }
                // FIX: filter out empty entries — the edit form used to emit one
                // hidden "remove_images[]" field per image regardless of whether
                // it was actually marked for removal.
                if(!empty($input['remove_images'])) {
                    $toRemove = array_filter((array)$input['remove_images'], fn($v)=>trim((string)$v)!=='');
                    foreach($toRemove as $ri) {
                        $p['images'] = array_values(array_filter($p['images'], fn($img)=>$img!==$ri));
                        // FIX: unlink must use a real filesystem path, not the
                        // web-relative path now stored/displayed — prepend GS_ROOT.
                        $fsPath = GS_ROOT.'/'.gsImgUrl($ri);
                        if(file_exists($fsPath)) @unlink($fsPath);
                    }
                }
                $products[$idx] = $p;
                gsWrite('products', $products);
                gsLog('Product Updated', $p['title']);
                echo json_encode(['success'=>true,'msg'=>'Product updated']);
                exit;

            case 'delete_product':
                db()->query("DELETE FROM products WHERE product_id = ?", [$input['id']]);
                db()->query("DELETE FROM product_images WHERE product_id = ?", [$input['id']]);
                gsLog('Product Deleted', $input['id']);
                echo json_encode(['success'=>true,'msg'=>'Deleted']);
                exit;

            case 'bulk_delete':
                $ids = $input['ids'] ?? [];
                if(is_string($ids)) $ids = json_decode($ids, true) ?: [];
                foreach($ids as $id) {
                    db()->query("DELETE FROM products WHERE product_id = ?", [$id]);
                    db()->query("DELETE FROM product_images WHERE product_id = ?", [$id]);
                }
                gsLog('Bulk Delete', count($ids).' products');
                echo json_encode(['success'=>true,'msg'=>count($ids).' products deleted']);
                exit;

            case 'add_banner':
                $image = '';
                if(!empty($_FILES['banner_image']) && ($_FILES['banner_image']['error']??1)===0) {
                    $saved = gsProcessImage($_FILES['banner_image']['tmp_name'], $_FILES['banner_image']['name'], 'banners');
                    if($saved) $image = $saved;
                }
                $bannerId = gsGenId('BNR');
                Database::getInstance()->insert('banners', [
                    'banner_id' => $bannerId,
                    'title' => gsSanitize($input['title']??''),
                    'subtitle' => gsSanitize($input['subtitle']??''),
                    'image' => $image,
                    'link' => gsSanitize($input['link']??''),
                    'position' => 'home',
                    'display_order' => 0,
                    'status' => 1
                ]);
                gsLog('Banner Added', $bannerId);
                echo json_encode(['success'=>true,'msg'=>'Banner added']);
                exit;

            case 'delete_banner':
                db()->query("DELETE FROM banners WHERE banner_id = ?", [$input['id']]);
                echo json_encode(['success'=>true,'msg'=>'Deleted']);
                exit;

            case 'add_coupon':
                if(empty(trim($input['code']??''))) { echo json_encode(['success'=>false,'msg'=>'Coupon code is required']); exit; }
                $couponId = gsGenId('CPN');
                Database::getInstance()->insert('coupons', [
                    'coupon_id' => $couponId,
                    'code' => strtoupper(gsSanitize($input['code'])),
                    'discount' => floatval($input['discount']),
                    'type' => gsSanitize($input['type']??'percent'),
                    'expiry_date' => gsSanitize($input['expiry']??''),
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                gsLog('Coupon Added', gsSanitize($input['code']));
                echo json_encode(['success'=>true,'msg'=>'Coupon added']);
                exit;

            case 'delete_coupon':
                db()->query("DELETE FROM coupons WHERE coupon_id = ?", [$input['id']]);
                echo json_encode(['success'=>true,'msg'=>'Deleted']);
                exit;

            case 'update_order_status':
                updateOrderStatus($input['order_id'], gsSanitize($input['status']));
                gsLog('Order Status', $input['order_id'].' → '.$input['status']);
                echo json_encode(['success'=>true,'msg'=>'Status updated']);
                exit;

            case 'delete_review':
                db()->query("DELETE FROM reviews WHERE review_id = ?", [$input['id']]);
                echo json_encode(['success'=>true,'msg'=>'Deleted']);
                exit;

            case 'approve_review':
                db()->query("UPDATE reviews SET status = 1 WHERE review_id = ?", [$input['id']]);
                echo json_encode(['success'=>true,'msg'=>'Approved']);
                exit;

            case 'change_password':
                echo json_encode(['success'=>false,'msg'=>'Login is disabled — password change not available']);
                exit;

            case 'upload_logo':
            case 'upload_favicon':
                $type = $action==='upload_logo'?'logo':'favicon';
                if(!empty($_FILES['file']) && ($_FILES['file']['error']??1)===0) {
                    $ext=strtolower(pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION));
                    if(in_array($ext,['jpg','jpeg','png','gif','webp','ico','svg'])) {
                        $fname='settings/'.$type.'.'.$ext;
                        if(move_uploaded_file($_FILES['file']['tmp_name'],GS_UPLOADS.'/'.$fname)) {
                            // FIX: store the relative web path, not the absolute filesystem path
                            $relPath = 'uploads/'.$fname;
                            $settings=gsRead('settings');
                            $settings[$type.'_path']=$relPath;
                            gsWrite('settings',$settings);
                            echo json_encode(['success'=>true,'msg'=>'Uploaded','path'=>$relPath]);
                        } else { echo json_encode(['success'=>false,'msg'=>'Upload failed']); }
                    } else { echo json_encode(['success'=>false,'msg'=>'Invalid file']); }
                } else { echo json_encode(['success'=>false,'msg'=>'No file']); }
                exit;

            case 'backup':
                $backup = [];
                foreach(['products','orders','settings','banners','categories','customers','admins','reviews','coupons','logs'] as $f) {
                    $backup[$f] = gsRead($f);
                }
                $filename = 'backup_'.date('Y-m-d_His').'.json';
                file_put_contents(GS_DATA.'/'.$filename, json_encode($backup, JSON_PRETTY_PRINT));
                echo json_encode(['success'=>true,'msg'=>$filename]);
                exit;

            case 'restore':
                // FIX: only allow known data keys to be written — prevents a
                // crafted backup file from writing to an arbitrary path.
                $allowedKeys = ['products','orders','settings','banners','categories','customers','admins','reviews','coupons','logs'];
                if(!empty($_FILES['backup_file']) && ($_FILES['backup_file']['error']??1)===0) {
                    $data = json_decode(file_get_contents($_FILES['backup_file']['tmp_name']),true);
                    if(is_array($data)) {
                        foreach($data as $key=>$val) {
                            if(in_array($key, $allowedKeys, true)) gsWrite($key, $val);
                        }
                        gsLog('Data Restored');
                        echo json_encode(['success'=>true,'msg'=>'Data restored successfully']);
                    } else { echo json_encode(['success'=>false,'msg'=>'Invalid backup file']); }
                } else { echo json_encode(['success'=>false,'msg'=>'No file uploaded']); }
                exit;

            case 'export_products':
                $products = gsRead('products');
                echo json_encode(['success'=>true,'data'=>$products]);
                exit;

            case 'import_products':
                $importData = json_decode($input['json_data']??'[]', true);
                if(is_array($importData)) {
                    $products = gsRead('products');
                    foreach($importData as $ip) {
                        if(empty($ip['id'])) $ip['id'] = gsGenId('PRD');
                        if(empty($ip['slug'])) $ip['slug'] = gsSlug($ip['title']??'product');
                        if(empty($ip['created'])) $ip['created'] = date('Y-m-d H:i:s');
                        $products[] = $ip;
                    }
                    gsWrite('products', $products);
                    echo json_encode(['success'=>true,'msg'=>count($importData).' products imported']);
                } else { echo json_encode(['success'=>false,'msg'=>'Invalid JSON']); }
                exit;

            case 'clear_logs':
                gsWrite('logs', []);
                echo json_encode(['success'=>true,'msg'=>'Logs cleared']);
                exit;

            case 'track_steadfast':
                $tracking = gsSanitize($input['tracking']??'');
                $ch = curl_init('https://portal.packzy.com/api/v1/status_by_tracking?tracking_code='.urlencode($tracking));
                curl_setopt_array($ch, [
                    CURLOPT_HTTPHEADER => ['Api-Key: wic9quaga555oyy2bgwecy0wmztxvyhd','Secret-Key: llqran7jwrzyk74gyolvelob'],
                    CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_TIMEOUT => 10
                ]);
                $resp = curl_exec($ch); curl_close($ch);
                echo $resp ?: json_encode(['error'=>'Failed to fetch']);
                exit;

            case 'save_landing':
                $products = gsRead('products');
                $pid = gsSanitize($input['product_id'] ?? '');
                if(!$pid || !in_array($pid, array_column($products,'id'), true)) { echo json_encode(['success'=>false,'msg'=>'Product not found']); exit; }
                $list = gsEnsureLandingEntries($products);
                $idx = array_search($pid, array_column($list, 'product_id'));
                if($idx===false) { echo json_encode(['success'=>false,'msg'=>'Landing page not found']); exit; }
                $l = $list[$idx];

                $newSlug = gsSlug($input['slug'] ?? $l['slug']);
                if($newSlug === '') $newSlug = $l['slug'];
                if($newSlug !== $l['slug']) $newSlug = gsUniqueLandingSlug($newSlug, $pid, $list);
                $l['slug'] = $newSlug;

                $l['enabled'] = ($input['enabled']??'0')==='1';
                $textFields = ['headline','description','promo_video_url','cta_text','delivery_info','return_policy',
                    'fb_pixel','tiktok_pixel','ga_id','meta_tags','seo_title','seo_description','seo_keywords','canonical_url','countdown_end'];
                foreach($textFields as $f) { if(isset($input[$f])) $l[$f] = gsSanitize($input[$f]); }
                $l['countdown_enabled'] = ($input['countdown_enabled']??'0')==='1';

                if(isset($input['benefits'])) {
                    $lines = preg_split('/\r\n|\r|\n/', (string)$input['benefits']);
                    $l['benefits'] = array_values(array_filter(array_map('gsSanitize', $lines), fn($v)=>$v!==''));
                }

                // Repeatable rows: testimonials / feature icons / FAQ
                if(!empty($input['testi_name']) || !empty($input['testi_text'])) {
                    $names = (array)($input['testi_name'] ?? []); $texts = (array)($input['testi_text'] ?? []);
                    $ratings = (array)($input['testi_rating'] ?? []); $existingImgs = (array)($input['testi_existing_image'] ?? []);
                    $testimonials = [];
                    foreach($names as $i=>$n) {
                        if(trim($n)==='' && trim($texts[$i]??'')==='') continue;
                        $testimonials[] = ['name'=>gsSanitize($n), 'text'=>gsSanitize($texts[$i]??''),
                            'rating'=>max(1,min(5,intval($ratings[$i]??5))), 'image'=>gsSanitize($existingImgs[$i]??'')];
                    }
                    if(!empty($_FILES['testi_images'])) {
                        foreach($_FILES['testi_images']['tmp_name'] as $i=>$tmp) {
                            if(($_FILES['testi_images']['error'][$i]??1)===0 && isset($testimonials[$i])) {
                                $saved = gsProcessImage($tmp, $_FILES['testi_images']['name'][$i], 'landing');
                                if($saved) $testimonials[$i]['image'] = $saved;
                            }
                        }
                    }
                    $l['testimonials'] = $testimonials;
                }
                if(!empty($input['feat_title'])) {
                    $icons = (array)($input['feat_icon'] ?? []); $titles = (array)($input['feat_title'] ?? []); $descs = (array)($input['feat_desc'] ?? []);
                    $feats = [];
                    foreach($titles as $i=>$t) {
                        if(trim($t)==='') continue;
                        $feats[] = ['icon'=>gsSanitize($icons[$i]??'fa-solid fa-check'), 'title'=>gsSanitize($t), 'desc'=>gsSanitize($descs[$i]??'')];
                    }
                    $l['feature_icons'] = $feats;
                }
                if(!empty($input['faq_q'])) {
                    $qs = (array)($input['faq_q'] ?? []); $as = (array)($input['faq_a'] ?? []);
                    $faqs = [];
                    foreach($qs as $i=>$q) {
                        if(trim($q)==='') continue;
                        $faqs[] = ['q'=>gsSanitize($q), 'a'=>gsSanitize($as[$i]??'')];
                    }
                    $l['faq'] = $faqs;
                }

                // Single image uploads
                foreach(['banner_image'=>'banner_image','before_image'=>'before_image','after_image'=>'after_image','og_image'=>'og_image'] as $field=>$fkey) {
                    if(!empty($_FILES[$fkey]) && ($_FILES[$fkey]['error']??1)===0) {
                        $saved = gsProcessImage($_FILES[$fkey]['tmp_name'], $_FILES[$fkey]['name'], 'landing');
                        if($saved) $l[$field] = $saved;
                    }
                }

                $l['updated'] = date('Y-m-d H:i:s');
                $list[$idx] = $l;
                gsWrite('landing_pages', $list);
                gsLog('Landing Page Saved', $l['slug']);
                echo json_encode(['success'=>true,'msg'=>'Landing page saved','slug'=>$l['slug'],'url'=>gsLandingUrl($l['slug'])]);
                exit;

            case 'regenerate_landing':
                $products = gsRead('products');
                $pid = gsSanitize($input['product_id'] ?? '');
                $list = gsEnsureLandingEntries($products);
                $idx = array_search($pid, array_column($list, 'product_id'));
                if($idx===false) { echo json_encode(['success'=>false,'msg'=>'Landing page not found']); exit; }
                $prodTitle = $products[array_search($pid, array_column($products,'id'))]['title'] ?? 'product';
                $base = gsSlug($prodTitle).'-'.strtolower(substr(bin2hex(random_bytes(2)),0,4));
                $list[$idx]['slug'] = gsUniqueLandingSlug($base, $pid, $list);
                $list[$idx]['updated'] = date('Y-m-d H:i:s');
                gsWrite('landing_pages', $list);
                gsLog('Landing Page Regenerated', $list[$idx]['slug']);
                echo json_encode(['success'=>true,'msg'=>'New link generated','slug'=>$list[$idx]['slug'],'url'=>gsLandingUrl($list[$idx]['slug'])]);
                exit;

            case 'toggle_landing_status':
                $products = gsRead('products');
                $pid = gsSanitize($input['product_id'] ?? '');
                $list = gsEnsureLandingEntries($products);
                $idx = array_search($pid, array_column($list, 'product_id'));
                if($idx===false) { echo json_encode(['success'=>false,'msg'=>'Landing page not found']); exit; }
                $list[$idx]['enabled'] = !$list[$idx]['enabled'];
                gsWrite('landing_pages', $list);
                echo json_encode(['success'=>true,'msg'=>$list[$idx]['enabled']?'Landing page enabled':'Landing page disabled','enabled'=>$list[$idx]['enabled']]);
                exit;

            case 'reset_landing_analytics':
                $list = gsRead('landing_pages');
                $pid = gsSanitize($input['product_id'] ?? '');
                $idx = array_search($pid, array_column($list, 'product_id'));
                if($idx===false) { echo json_encode(['success'=>false,'msg'=>'Not found']); exit; }
                foreach(['views','clicks','add_to_cart','orders'] as $k) $list[$idx][$k] = 0;
                gsWrite('landing_pages', $list);
                echo json_encode(['success'=>true,'msg'=>'Analytics reset']);
                exit;

            default:
                echo json_encode(['success'=>false,'msg'=>'Invalid action']);
                exit;
        }
    } catch(\Throwable $e) {
        // Any unexpected error is now returned as clean JSON instead of a
        // broken/blank response that the front-end couldn't parse.
        echo json_encode(['success'=>false,'msg'=>'Server error: '.$e->getMessage()]);
        exit;
    } finally {
        restore_error_handler();
    }
}

// GET data for pages
 $tab = gsSanitize($_GET['tab'] ?? 'dashboard');
 $editId = gsSanitize($_GET['edit'] ?? '');
 $settings = gsRead('settings');
 $products = gsRead('products');
 $orders = gsRead('orders');
 $banners = gsRead('banners');
 $categories = gsRead('categories');
 $customers = gsRead('customers');
 $reviews = gsRead('reviews');
 $coupons = gsRead('coupons');
 $logs = gsRead('logs');

// Dashboard stats
 $today = date('Y-m-d');
 $todayOrders = array_filter($orders, fn($o)=>strpos($o['date']??'',$today)!==false);
 $pendingOrders = array_filter($orders, fn($o)=>($o['status']??'')==='pending');
 $confirmedOrders = array_filter($orders, fn($o)=>($o['status']??'')==='confirmed');
 $processingOrders = array_filter($orders, fn($o)=>($o['status']??'')==='processing');
 $shippedOrders = array_filter($orders, fn($o)=>($o['status']??'')==='shipped');
 $deliveredOrders = array_filter($orders, fn($o)=>($o['status']??'')==='delivered');
 $cancelledOrders = array_filter($orders, fn($o)=>($o['status']??'')==='cancelled');
 $totalRevenue = array_sum(array_map(fn($o)=>floatval($o['total']??0), array_filter($orders, fn($o)=>($o['status']??'')==='delivered')));
 $lowStock = array_filter($products, fn($p)=>intval($p['stock']??0)<=5 && intval($p['stock']??0)>0);
 $activeProducts = array_filter($products, fn($p)=>($p['status']??1)==1);
 $pendingReviews = array_filter($reviews, fn($r)=>($r['status']??0)==0);

// Edit product
 $editProduct = null;
if($tab==='products' && $editId) {
    foreach($products as $p) { if($p['id']===$editId) { $editProduct=$p; break; } }
}

// ============ INVOICE (standalone, printable, own branding) ============
if(!empty($_GET['invoice'])) {
    $invId = gsSanitize($_GET['invoice']);
    $invOrder = null;
    foreach($orders as $o) { if($o['id']===$invId) { $invOrder=$o; break; } }
    if(!$invOrder) { http_response_code(404); echo 'Order not found.'; exit; }
    $curr = $settings['currency'] ?? '৳';
    $items = $invOrder['items'] ?? [];
    $subtotal = 0; foreach($items as $it) { $subtotal += floatval($it['price']??0) * intval($it['qty']??1); }
    $discountAmt = max(0, $subtotal - floatval($invOrder['total']??$subtotal));
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Invoice <?=gsSanitize($invOrder['id'])?> — <?=gsSanitize($settings['site_name']??'Invoice')?></title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
:root{--p:<?=gsSanitize($settings['primary_color']??'#6C63FF')?>;--s:<?=gsSanitize($settings['secondary_color']??'#00D4FF')?>;--a:<?=gsSanitize($settings['accent_color']??'#FF4D6D')?>}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:#F1F5F9;color:#0F172A;padding:30px}
.invoice{max-width:800px;margin:0 auto;background:#fff;border-radius:16px;box-shadow:0 10px 40px rgba(0,0,0,.08);overflow:hidden}
.inv-header{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;padding:36px 40px;display:flex;justify-content:space-between;align-items:flex-start;gap:20px}
.inv-brand{display:flex;align-items:center;gap:14px}
.inv-brand img{height:44px;border-radius:8px;background:#fff;padding:4px}
.inv-brand h1{font-size:1.5rem;font-weight:900}
.inv-brand p{font-size:.8rem;opacity:.9;margin-top:2px}
.inv-meta{text-align:right}
.inv-meta h2{font-size:1.4rem;font-weight:900;letter-spacing:1px}
.inv-meta p{font-size:.85rem;opacity:.9;margin-top:4px}
.inv-body{padding:36px 40px}
.inv-parties{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:32px}
.inv-parties h3{font-size:.72rem;text-transform:uppercase;letter-spacing:1px;color:#94A3B8;margin-bottom:8px;font-weight:700}
.inv-parties p{font-size:.92rem;line-height:1.6;font-weight:500}
.inv-parties strong{font-size:1rem}
table{width:100%;border-collapse:collapse;margin-bottom:24px}
th{text-align:left;padding:12px 14px;font-size:.72rem;text-transform:uppercase;letter-spacing:.5px;color:#94A3B8;background:#F8FAFC;font-weight:700;border-bottom:2px solid #E2E8F0}
td{padding:14px;font-size:.9rem;border-bottom:1px solid #F1F5F9}
.text-right{text-align:right}
.totals{margin-left:auto;width:280px}
.totals div{display:flex;justify-content:space-between;padding:8px 0;font-size:.92rem}
.totals .grand{border-top:2px solid #0F172A;margin-top:6px;padding-top:12px;font-size:1.25rem;font-weight:900;color:var(--p)}
.status-pill{display:inline-block;padding:5px 14px;border-radius:20px;font-size:.75rem;font-weight:700;background:rgba(108,99,255,.12);color:var(--p);text-transform:capitalize}
.inv-footer{padding:24px 40px;border-top:1px solid #F1F5F9;text-align:center;font-size:.8rem;color:#94A3B8}
.print-bar{max-width:800px;margin:0 auto 16px;display:flex;justify-content:flex-end;gap:10px}
.print-bar button{padding:10px 22px;border-radius:10px;border:none;font-weight:700;font-size:.88rem;cursor:pointer;background:linear-gradient(135deg,var(--p),var(--s));color:#fff}
@media print{ body{background:#fff;padding:0} .print-bar{display:none} .invoice{box-shadow:none;border-radius:0} }
</style>
</head>
<body>
<div class="print-bar"><button onclick="window.print()">🖨 Print / Save as PDF</button></div>
<div class="invoice">
    <div class="inv-header">
        <div class="inv-brand">
            <?php if(!empty($settings['logo_path'])):?><img src="<?=gsSanitize(gsImgUrl($settings['logo_path']))?>" alt="logo"><?php endif;?>
            <div>
                <h1><?=gsSanitize($settings['site_name']??'GlowSpace')?></h1>
                <p><?=gsSanitize($settings['tagline']??'')?></p>
            </div>
        </div>
        <div class="inv-meta">
            <h2>INVOICE</h2>
            <p>#<?=gsSanitize($invOrder['id'])?></p>
            <p><?=gsSanitize($invOrder['date']??date('Y-m-d'))?></p>
        </div>
    </div>
    <div class="inv-body">
        <div class="inv-parties">
            <div>
                <h3>Billed To</h3>
                <p><strong><?=gsSanitize($invOrder['customer']['name']??'')?></strong><br>
                <?=gsSanitize($invOrder['customer']['phone']??'')?><br>
                <?=gsSanitize($invOrder['customer']['address']??'')?></p>
            </div>
            <div style="text-align:right">
                <h3>Order Status</h3>
                <p><span class="status-pill"><?=gsSanitize($invOrder['status']??'pending')?></span></p>
                <?php if(!empty($invOrder['tracking'])):?><p style="margin-top:8px"><strong>Tracking:</strong> <?=gsSanitize($invOrder['tracking'])?></p><?php endif;?>
            </div>
        </div>
        <table>
            <thead><tr><th>Item</th><th class="text-right">Qty</th><th class="text-right">Price</th><th class="text-right">Total</th></tr></thead>
            <tbody>
            <?php foreach($items as $it):
                $lineTotal = floatval($it['price']??0) * intval($it['qty']??1);
            ?>
            <tr>
                <td><?=gsSanitize($it['title']??'')?></td>
                <td class="text-right"><?=intval($it['qty']??1)?></td>
                <td class="text-right"><?=$curr?><?=number_format(floatval($it['price']??0))?></td>
                <td class="text-right"><?=$curr?><?=number_format($lineTotal)?></td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($items)):?><tr><td colspan="4" style="text-align:center;color:#94A3B8">No items</td></tr><?php endif;?>
            </tbody>
        </table>
        <div class="totals">
            <div><span>Subtotal</span><span><?=$curr?><?=number_format($subtotal)?></span></div>
            <?php if($discountAmt>0):?><div><span>Discount</span><span>-<?=$curr?><?=number_format($discountAmt)?></span></div><?php endif;?>
            <div class="grand"><span>Total</span><span><?=$curr?><?=number_format(floatval($invOrder['total']??$subtotal))?></span></div>
        </div>
    </div>
    <div class="inv-footer">
        Thank you for shopping with <?=gsSanitize($settings['site_name']??'us')?>! · <?=gsSanitize($settings['whatsapp']??'')?><br>
        This is a system-generated invoice.
    </div>
</div>
</body>
</html>
    <?php
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>GlowSpace Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
:root{--p:#6C63FF;--s:#00D4FF;--a:#FF4D6D;--bg:#F8FAFC;--bg2:#FFFFFF;--bg3:#F1F5F9;--t:#0F172A;--t2:#475569;--t3:#94A3B8;--bd:#E2E8F0;--sh:0 1px 3px rgba(0,0,0,.08);--shl:0 10px 40px rgba(0,0,0,.1);--r:12px;--rl:20px;--g:linear-gradient(135deg,#6C63FF,#00D4FF)}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:var(--bg);color:var(--t);display:flex;min-height:100vh}
a{text-decoration:none;color:inherit;transition:all .3s}
button{cursor:pointer;border:none;background:none;font-family:inherit;transition:all .3s}
input,select,textarea{font-family:inherit;transition:all .3s}

.sidebar{width:260px;background:#0F172A;color:#fff;position:fixed;top:0;left:0;bottom:0;z-index:100;display:flex;flex-direction:column;overflow-y:auto;transition:transform .3s}
.sidebar-logo{padding:20px 24px;font-size:1.3rem;font-weight:900;background:var(--g);-webkit-background-clip:text;-webkit-text-fill-color:transparent;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.08)}
.sidebar-logo i{background:var(--g);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.sidebar-nav{padding:16px 12px;flex:1}
.sidebar-nav a{display:flex;align-items:center;gap:12px;padding:11px 16px;border-radius:10px;font-size:.9rem;font-weight:500;color:#94A3B8;margin-bottom:2px}
.sidebar-nav a:hover{background:rgba(108,99,255,.15);color:#fff}
.sidebar-nav a.active{background:rgba(108,99,255,.2);color:#fff;font-weight:600}
.sidebar-nav a i{width:20px;text-align:center;font-size:.95rem}
.sidebar-nav .nav-label{font-size:.7rem;text-transform:uppercase;letter-spacing:1.5px;color:#475569;padding:16px 16px 8px;font-weight:700}
.sidebar-footer{padding:16px 20px;border-top:1px solid rgba(255,255,255,.08)}
.sidebar-footer .admin-info{display:flex;align-items:center;gap:10px;margin-bottom:12px}
.sidebar-footer .admin-avatar{width:36px;height:36px;border-radius:10px;background:var(--g);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:.9rem}
.sidebar-footer .admin-name{font-size:.88rem;font-weight:600}
.sidebar-footer .admin-role{font-size:.72rem;color:#64748B}

.main{margin-left:260px;flex:1;min-height:100vh}
.topbar{background:var(--bg2);padding:16px 32px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--bd);position:sticky;top:0;z-index:50}
.topbar h1{font-size:1.2rem;font-weight:800}
.topbar-actions{display:flex;align-items:center;gap:12px}
.topbar-btn{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;color:var(--t2);font-size:1rem;background:var(--bg3)}
.topbar-btn:hover{background:var(--p);color:#fff}
.content{padding:32px}

.stats-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;margin-bottom:32px}
.stat-card{background:var(--bg2);border-radius:var(--rl);padding:20px;box-shadow:var(--sh);display:flex;align-items:center;gap:16px;transition:all .3s}
.stat-card:hover{transform:translateY(-2px);box-shadow:var(--shl)}
.stat-icon{width:48px;height:48px;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:1.2rem;color:#fff;flex-shrink:0}
.stat-icon.purple{background:linear-gradient(135deg,#6C63FF,#8B5CF6)}
.stat-icon.blue{background:linear-gradient(135deg,#00D4FF,#0EA5E9)}
.stat-icon.red{background:linear-gradient(135deg,#FF4D6D,#EF4444)}
.stat-icon.green{background:linear-gradient(135deg,#10B981,#059669)}
.stat-icon.orange{background:linear-gradient(135deg,#F59E0B,#D97706)}
.stat-icon.pink{background:linear-gradient(135deg,#EC4899,#DB2777)}
.stat-info h3{font-size:1.5rem;font-weight:900;line-height:1}
.stat-info p{font-size:.78rem;color:var(--t3);margin-top:2px;font-weight:500}

.card{background:var(--bg2);border-radius:var(--rl);box-shadow:var(--sh);overflow:hidden;margin-bottom:24px}
.card-header{padding:20px 24px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;border-bottom:1px solid var(--bd)}
.card-header h2{font-size:1.1rem;font-weight:800}
.card-body{overflow-x:auto}
table{width:100%;border-collapse:collapse}
th{text-align:left;padding:12px 16px;font-size:.78rem;text-transform:uppercase;letter-spacing:1px;color:var(--t3);background:var(--bg3);font-weight:700;white-space:nowrap}
td{padding:12px 16px;font-size:.88rem;border-bottom:1px solid var(--bd);vertical-align:middle}
tr:hover td{background:rgba(108,99,255,.02)}

.btn{padding:10px 20px;border-radius:10px;font-weight:600;font-size:.88rem;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-primary{background:var(--g);color:#fff}
.btn-primary:hover{opacity:.9}
.btn-sm{padding:6px 14px;font-size:.8rem;border-radius:8px}
.btn-danger{background:var(--a);color:#fff}
.btn-success{background:#10B981;color:#fff}
.btn-warning{background:#F59E0B;color:#fff}
.btn-outline{border:2px solid var(--bd);color:var(--t2);background:transparent}
.btn-outline:hover{border-color:var(--p);color:var(--p)}

.badge-status{padding:4px 12px;border-radius:20px;font-size:.75rem;font-weight:700;display:inline-block}
.badge-pending{background:rgba(245,158,11,.1);color:#F59E0B}
.badge-confirmed{background:rgba(108,99,255,.1);color:#6C63FF}
.badge-processing{background:rgba(0,212,255,.1);color:#00D4FF}
.badge-shipped{background:rgba(139,92,246,.1);color:#8B5CF6}
.badge-delivered{background:rgba(16,185,129,.1);color:#10B981}
.badge-cancelled{background:rgba(239,68,68,.1);color:#EF4444}
.badge-active{background:rgba(16,185,129,.1);color:#10B981}
.badge-inactive{background:rgba(239,68,68,.1);color:#EF4444}

.form-group{margin-bottom:16px}
.form-group label{display:block;font-weight:600;font-size:.85rem;margin-bottom:6px;color:var(--t2)}
.form-group input,.form-group select,.form-group textarea{width:100%;padding:10px 14px;border:2px solid var(--bd);border-radius:10px;background:var(--bg);color:var(--t);font-size:.9rem;outline:none}
.form-group input:focus,.form-group select:focus,.form-group textarea:focus{border-color:var(--p);box-shadow:0 0 0 3px rgba(108,99,255,.1)}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.form-check{display:flex;align-items:center;gap:8px;font-size:.88rem;cursor:pointer}
.form-check input[type="checkbox"]{width:18px;height:18px;accent-color:var(--p)}
.size-row{display:grid;grid-template-columns:2fr 1fr;gap:8px}

.modal-overlay{position:fixed;inset:0;z-index:200;background:rgba(0,0,0,.5);backdrop-filter:blur(4px);display:none;align-items:flex-start;justify-content:center;padding:40px 20px;overflow-y:auto}
.modal-overlay.show{display:flex}
.modal{background:var(--bg2);border-radius:var(--rl);width:100%;max-width:720px;box-shadow:0 25px 60px rgba(0,0,0,.3);animation:modalIn .3s ease}
@keyframes modalIn{from{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}
.modal-header{padding:20px 24px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--bd)}
.modal-header h2{font-size:1.1rem;font-weight:800}
.modal-close{width:36px;height:36px;border-radius:10px;background:var(--bg3);display:flex;align-items:center;justify-content:center;color:var(--t2)}
.modal-body{padding:24px;max-height:70vh;overflow-y:auto}
.modal-footer{padding:16px 24px;border-top:1px solid var(--bd);display:flex;justify-content:flex-end;gap:8px}

.alert{padding:14px 20px;border-radius:12px;font-size:.88rem;margin-bottom:16px;display:flex;align-items:center;gap:10px}
.alert-warning{background:rgba(245,158,11,.1);color:#D97706;border:1px solid rgba(245,158,11,.2)}
.alert-danger{background:rgba(239,68,68,.1);color:#EF4444;border:1px solid rgba(239,68,68,.2)}
.alert-success{background:rgba(16,185,129,.1);color:#059669;border:1px solid rgba(16,185,129,.2)}
.alert-info{background:rgba(108,99,255,.1);color:#6C63FF;border:1px solid rgba(108,99,255,.2)}

.hamburger-admin{display:none;position:fixed;top:16px;left:16px;z-index:150;width:40px;height:40px;border-radius:10px;background:var(--p);color:#fff;font-size:1.1rem;align-items:center;justify-content:center;box-shadow:var(--shl)}
.sidebar-overlay{display:none;position:fixed;inset:0;z-index:99;background:rgba(0,0,0,.5)}
@media(max-width:900px){
    .sidebar{transform:translateX(-100%)}
    .sidebar.open{transform:translateX(0)}
    .sidebar-overlay.show{display:block}
    .main{margin-left:0}
    .hamburger-admin{display:flex}
    .topbar{padding-left:64px}
    .content{padding:20px 16px}
    .stats-grid{grid-template-columns:repeat(2,1fr)}
    .form-row{grid-template-columns:1fr}
}

.toast-wrap{position:fixed;top:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:8px}
.toast{padding:14px 20px;border-radius:12px;background:var(--bg2);box-shadow:var(--shl);font-size:.88rem;font-weight:500;animation:toastSlide .3s ease;display:flex;align-items:center;gap:10px;border-left:4px solid var(--p);max-width:360px}
.toast.error{border-left-color:var(--a)}
@keyframes toastSlide{from{opacity:0;transform:translateX(30px)}to{opacity:1;transform:translateX(0)}}

.low-stock{color:var(--a);font-weight:700}
.empty-msg{text-align:center;padding:40px;color:var(--t3)}
.empty-msg i{font-size:3rem;margin-bottom:12px;display:block}
.spec-row{display:grid;grid-template-columns:1fr 1fr auto;gap:8px;margin-bottom:8px;align-items:end}
.spec-row .remove-spec{width:36px;height:36px;border-radius:8px;background:rgba(239,68,68,.1);color:var(--a);display:flex;align-items:center;justify-content:center;margin-bottom:1px}
</style>
</head>
<body>

<div class="toast-wrap" id="toastWrap"></div>
<button class="hamburger-admin" onclick="toggleSidebar()"><i class="fa-solid fa-bars"></i></button>
<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleSidebar()"></div>

<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
    <div class="sidebar-logo"><i class="fa-solid fa-bolt"></i> GlowSpace</div>
    <nav class="sidebar-nav">
        <div class="nav-label">Main</div>
        <a href="admin.php?tab=dashboard" class="<?=$tab==='dashboard'?'active':''?>"><i class="fa-solid fa-chart-pie"></i> Dashboard</a>
        <a href="admin.php?tab=products" class="<?=$tab==='products'?'active':''?>"><i class="fa-solid fa-box"></i> Products <span style="margin-left:auto;background:var(--p);padding:2px 8px;border-radius:6px;font-size:.72rem"><?=count($activeProducts)?></span></a>
        <a href="admin.php?tab=orders" class="<?=$tab==='orders'?'active':''?>"><i class="fa-solid fa-cart-shopping"></i> Orders <span style="margin-left:auto;background:var(--a);padding:2px 8px;border-radius:6px;font-size:.72rem"><?=count($pendingOrders)?></span></a>
        <a href="admin.php?tab=landing" class="<?=$tab==='landing'?'active':''?>"><i class="fa-solid fa-rocket"></i> Landing Pages</a>
        <div class="nav-label">Catalog</div>
        <a href="admin.php?tab=categories" class="<?=$tab==='categories'?'active':''?>"><i class="fa-solid fa-grip"></i> Categories</a>
        <a href="admin.php?tab=banners" class="<?=$tab==='banners'?'active':''?>"><i class="fa-solid fa-images"></i> Banners</a>
        <a href="admin.php?tab=coupons" class="<?=$tab==='coupons'?'active':''?>"><i class="fa-solid fa-ticket"></i> Coupons</a>
        <div class="nav-label">Management</div>
        <a href="admin.php?tab=reviews" class="<?=$tab==='reviews'?'active':''?>"><i class="fa-solid fa-star"></i> Reviews <?=count($pendingReviews)>0?'<span style="margin-left:auto;background:var(--a);padding:2px 8px;border-radius:6px;font-size:.72rem">'.count($pendingReviews).'</span>':''?></a>
        <a href="admin.php?tab=customers" class="<?=$tab==='customers'?'active':''?>"><i class="fa-solid fa-users"></i> Customers</a>
        <a href="admin.php?tab=settings" class="<?=$tab==='settings'?'active':''?>"><i class="fa-solid fa-gear"></i> Settings</a>
        <a href="admin.php?tab=logs" class="<?=$tab==='logs'?'active':''?>"><i class="fa-solid fa-clock-rotate-left"></i> Activity Logs</a>
    </nav>
    <div class="sidebar-footer">
        <div class="admin-info">
            <div class="admin-avatar"><?=strtoupper(substr($_SESSION['gs_admin']['username'],0,1))?></div>
            <div><div class="admin-name"><?=htmlspecialchars($_SESSION['gs_admin']['username'])?></div><div class="admin-role">Administrator</div></div>
        </div>
    </div>
</aside>

<!-- Main Content -->
<div class="main">
<div class="topbar">
    <h1 id="pageTitle"><?php
        $titles = ['dashboard'=>'Dashboard','products'=>'Products','orders'=>'Orders','categories'=>'Categories','banners'=>'Banners','coupons'=>'Coupons','reviews'=>'Reviews','customers'=>'Customers','settings'=>'Settings','logs'=>'Activity Logs'];
        echo $titles[$tab] ?? 'Dashboard';
        if($tab==='products'&&$editProduct) echo ' — Edit Product';
    ?></h1>
    <div class="topbar-actions">
        <a href="index.php" target="_blank" class="topbar-btn" title="View Store"><i class="fa-solid fa-external-link"></i></a>
    </div>
</div>
<div class="content">

<!-- Login Removed Notice -->
<div class="alert alert-info"><i class="fa-solid fa-shield-halved"></i> <strong>Login system is disabled.</strong> Admin panel is directly accessible. For security, re-enable login before going live.</div>

<?php if($tab==='dashboard'):?>
<div class="stats-grid">
    <div class="stat-card"><div class="stat-icon purple"><i class="fa-solid fa-box"></i></div><div class="stat-info"><h3><?=count($activeProducts)?></h3><p>Total Products</p></div></div>
    <div class="stat-card"><div class="stat-icon blue"><i class="fa-solid fa-cart-shopping"></i></div><div class="stat-info"><h3><?=count($todayOrders)?></h3><p>Today's Orders</p></div></div>
    <div class="stat-card"><div class="stat-icon orange"><i class="fa-solid fa-clock"></i></div><div class="stat-info"><h3><?=count($pendingOrders)?></h3><p>Pending</p></div></div>
    <div class="stat-card"><div class="stat-icon pink"><i class="fa-solid fa-check-circle"></i></div><div class="stat-info"><h3><?=count($confirmedOrders)?></h3><p>Confirmed</p></div></div>
    <div class="stat-card"><div class="stat-icon green"><i class="fa-solid fa-truck"></i></div><div class="stat-info"><h3><?=count($shippedOrders)?></h3><p>Shipped</p></div></div>
    <div class="stat-card"><div class="stat-icon green"><i class="fa-solid fa-circle-check"></i></div><div class="stat-info"><h3><?=count($deliveredOrders)?></h3><p>Delivered</p></div></div>
    <div class="stat-card"><div class="stat-icon red"><i class="fa-solid fa-circle-xmark"></i></div><div class="stat-info"><h3><?=count($cancelledOrders)?></h3><p>Cancelled</p></div></div>
    <div class="stat-card"><div class="stat-icon purple"><i class="fa-solid fa-taka-sign"></i></div><div class="stat-info"><h3>৳<?=number_format($totalRevenue)?></h3><p>Revenue</p></div></div>
</div>

<?php if(count($lowStock)>0):?>
<div class="alert alert-warning"><i class="fa-solid fa-triangle-exclamation"></i> <strong><?=count($lowStock)?> products</strong> have low stock (5 or fewer remaining)</div>
<?php endif;?>
<?php if(count($pendingReviews)>0):?>
<div class="alert alert-warning"><i class="fa-solid fa-star"></i> <strong><?=count($pendingReviews)?> reviews</strong> pending approval</div>
<?php endif;?>

<div class="card">
    <div class="card-header"><h2>Recent Orders</h2><a href="admin.php?tab=orders" class="btn btn-sm btn-outline">View All</a></div>
    <div class="card-body">
        <table>
            <thead><tr><th>Order ID</th><th>Customer</th><th>Total</th><th>Status</th><th>Date</th><th>Tracking</th></tr></thead>
            <tbody>
            <?php foreach(array_slice(array_reverse($orders),0,10) as $o):?>
            <tr>
                <td><strong><?=gsSanitize($o['id'])?></strong></td>
                <td><?=gsSanitize($o['customer']['name']??'')?></td>
                <td><strong>৳<?=number_format(floatval($o['total']??0))?></strong></td>
                <td><span class="badge-status badge-<?=gsSanitize($o['status']??'pending')?>"><?=ucfirst(gsSanitize($o['status']??'pending'))?></span></td>
                <td style="white-space:nowrap"><?=gsSanitize($o['date']??'')?></td>
                <td><?=!empty($o['tracking'])?'<span style="color:var(--p);font-weight:600">'.gsSanitize($o['tracking']).'</span>':'—'?></td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($orders)):?><tr><td colspan="6" class="empty-msg"><i class="fa-solid fa-inbox"></i>No orders yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>

<?php if(!empty($lowStock)):?>
<div class="card">
    <div class="card-header"><h2><i class="fa-solid fa-triangle-exclamation" style="color:var(--a)"></i> Low Stock Products</h2></div>
    <div class="card-body">
        <table><thead><tr><th>Product</th><th>Stock</th><th>Action</th></tr></thead><tbody>
        <?php foreach($lowStock as $ls):?>
        <tr><td><?=gsSanitize($ls['title'])?></td><td class="low-stock"><?=intval($ls['stock'])?></td><td><a href="admin.php?tab=products&edit=<?=$ls['id']?>" class="btn btn-sm btn-outline">Edit</a></td></tr>
        <?php endforeach;?>
        </tbody></table>
    </div>
</div>
<?php endif;?>

<div class="card">
    <div class="card-header"><h2>Recent Activity</h2><a href="admin.php?tab=logs" class="btn btn-sm btn-outline">View All</a></div>
    <div class="card-body">
        <table><thead><tr><th>Time</th><th>Action</th><th>Detail</th></tr></thead><tbody>
        <?php foreach(array_slice($logs,0,10) as $l):?>
        <tr><td style="white-space:nowrap"><?=gsSanitize($l['time'])?></td><td><?=gsSanitize($l['action'])?></td><td style="color:var(--t2)"><?=gsSanitize($l['detail']??'')?></td></tr>
        <?php endforeach;?>
        <?php if(empty($logs)):?><tr><td colspan="3" class="empty-msg">No activity yet</td></tr><?php endif;?>
        </tbody></table>
    </div>
</div>

<?php
// ============ PRODUCTS ============
elseif($tab==='products'):
    if($editProduct):
        $specs = $editProduct['specifications'] ?? [];
        if(!is_array($specs)) $specs = json_decode($specs, true) ?: [];
?>
<div class="card">
    <div class="card-header"><h2>Edit Product: <?=gsSanitize($editProduct['title'])?></h2><a href="admin.php?tab=products" class="btn btn-sm btn-outline"><i class="fa-solid fa-arrow-left"></i> Back</a></div>
    <div class="card-body">
        <form id="editProductForm" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_product">
            <input type="hidden" name="csrf_token" value="<?=$csrf?>">
            <input type="hidden" name="id" value="<?=$editProduct['id']?>">
            <div class="form-row">
                <div class="form-group"><label>Title *</label><input type="text" name="title" value="<?=gsSanitize($editProduct['title'])?>" required></div>
                <div class="form-group"><label>Subtitle</label><input type="text" name="subtitle" value="<?=gsSanitize($editProduct['subtitle']??'')?>"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>Brand</label><input type="text" name="brand" value="<?=gsSanitize($editProduct['brand']??'')?>" list="brandList">
                    <datalist id="brandList"><?=implode('',array_unique(array_map(fn($p)=>'<option value="'.gsSanitize($p['brand']??'').'">', $products)))?></datalist>
                </div>
                <div class="form-group"><label>Category</label><select name="category"><option value="">Select</option><?php foreach($categories as $c):?><option value="<?=gsSanitize($c['name'])?>" <?=($editProduct['category']??'')===$c['name']?'selected':''?>><?=gsSanitize($c['name'])?></option><?php endforeach;?></select></div>
            </div>
            <div class="form-group"><label>Description</label><textarea name="description" rows="4"><?=gsSanitize($editProduct['description']??'')?></textarea></div>
            <div class="form-group"><label>Features (one per line)</label><textarea name="features" rows="3"><?=gsSanitize(is_array($editProduct['features']??'')?implode("\n",$editProduct['features']):($editProduct['features']??''))?></textarea></div>
            <div class="form-row">
                <div class="form-group"><label>Regular Price *</label><input type="number" name="price" value="<?=floatval($editProduct['price'])?>" required step="0.01"></div>
                <div class="form-group"><label>Offer Price</label><input type="number" name="offer_price" value="<?=floatval($editProduct['offer_price']??0)?>" step="0.01"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>Stock *</label><input type="number" name="stock" value="<?=intval($editProduct['stock'])?>" required></div>
                <div class="form-group"><label>Warranty</label><input type="text" name="warranty" value="<?=gsSanitize($editProduct['warranty']??'')?>" placeholder="e.g. 1 Year"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>Color</label><input type="text" name="color" value="<?=gsSanitize($editProduct['color']??'')?>"></div>
                <div class="form-group"><label>Sizes &amp; Unit</label>
                    <div class="size-row">
                        <input type="text" name="sizes" value="<?=gsSanitize($editProduct['sizes']??'')?>" placeholder='e.g. 24, 27, 32'>
                        <select name="size_unit">
                            <?php $curUnit = $editProduct['size_unit']??''; foreach(['' => 'No unit','inch'=>'Inch (")','feet'=>'Feet (ft)','cm'=>'Centimeter (cm)','mm'=>'Millimeter (mm)','meter'=>'Meter (m)'] as $uv=>$ul):?>
                            <option value="<?=$uv?>" <?=$curUnit===$uv?'selected':''?>><?=$ul?></option>
                            <?php endforeach;?>
                        </select>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label>Specifications</label>
                <div id="specContainer">
                    <?php foreach($specs as $sk=>$sv):?>
                    <div class="spec-row"><input type="text" name="spec_keys[]" value="<?=gsSanitize($sk)?>" placeholder="Key"><input type="text" name="spec_values[]" value="<?=gsSanitize($sv)?>" placeholder="Value"><button type="button" class="remove-spec" onclick="this.parentElement.remove()"><i class="fa-solid fa-xmark"></i></button></div>
                    <?php endforeach;?>
                </div>
                <button type="button" class="btn btn-sm btn-outline" style="margin-top:8px" onclick="addSpecRow()"><i class="fa-solid fa-plus"></i> Add Spec</button>
            </div>
            <div class="form-group">
                <label>Current Images</label>
                <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:12px">
                    <?php foreach($editProduct['images']??[] as $img):?>
                    <div style="position:relative;width:100px;height:100px;border-radius:10px;overflow:hidden;border:2px solid var(--bd)">
                        <img src="<?=gsSanitize(gsImgUrl($img))?>" style="width:100%;height:100%;object-fit:cover" onerror="this.src='https://placehold.co/100x100?text=No+Image'">
                        <button type="button" onclick="removeEditImage(this,'<?=gsSanitize($img)?>')" style="position:absolute;top:2px;right:2px;width:22px;height:22px;border-radius:50%;background:var(--a);color:#fff;font-size:.7rem;display:flex;align-items:center;justify-content:center"><i class="fa-solid fa-xmark"></i></button>
                    </div>
                    <?php endforeach;?>
                </div>
            </div>
            <div class="form-group"><label>Add New Images</label><input type="file" name="new_images[]" multiple accept="image/*"></div>
            <div class="form-row">
                <div class="form-group"><label>Flags</label>
                    <div style="display:flex;flex-wrap:wrap;gap:12px;margin-top:4px">
                        <label class="form-check"><input type="checkbox" name="featured" value="1" <?=($editProduct['featured']??false)?'checked':''?>> Featured</label>
                        <label class="form-check"><input type="checkbox" name="trending" value="1" <?=($editProduct['trending']??false)?'checked':''?>> Trending</label>
                        <label class="form-check"><input type="checkbox" name="best_seller" value="1" <?=($editProduct['best_seller']??false)?'checked':''?>> Best Seller</label>
                        <label class="form-check"><input type="checkbox" name="flash_sale" value="1" <?=($editProduct['flash_sale']??false)?'checked':''?>> Flash Sale</label>
                        <label class="form-check"><input type="checkbox" name="new_arrival" value="1" <?=($editProduct['new_arrival']??false)?'checked':''?>> New Arrival</label>
                        <label class="form-check"><input type="checkbox" name="recommended" value="1" <?=($editProduct['recommended']??false)?'checked':''?>> Recommended</label>
                        <label class="form-check"><input type="checkbox" name="status" value="1" <?=($editProduct['status']??true)?'checked':''?>> Active</label>
                    </div>
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="fa-solid fa-save"></i> Update Product</button>
        </form>
    </div>
</div>
<?php else:?>
<!-- Product List -->
<div class="card">
    <div class="card-header">
        <h2>All Products (<?=count($products)?>)</h2>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <input type="text" id="productSearch" placeholder="Search products..." style="padding:8px 14px;border:2px solid var(--bd);border-radius:8px;font-size:.85rem;width:200px">
            <button class="btn btn-sm btn-danger" id="bulkDeleteBtn" style="display:none" onclick="bulkDeleteProducts()"><i class="fa-solid fa-trash"></i> Delete Selected</button>
            <button class="btn btn-sm btn-primary" onclick="openAddProduct()"><i class="fa-solid fa-plus"></i> Add Product</button>
        </div>
    </div>
    <div class="card-body">
        <table id="productsTable">
            <thead><tr><th><input type="checkbox" id="selectAllProducts"></th><th>Image</th><th>Product</th><th>Category</th><th>Price</th><th>Stock</th><th>Flags</th><th>Status</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($products as $p):?>
            <tr data-search="<?=strtolower(gsSanitize($p['title'].' '.$p['category'].' '.$p['brand']))?>">
                <td><input type="checkbox" class="product-check" value="<?=$p['id']?>"></td>
                <td><?php if(!empty($p['images'][0])):?><img src="<?=gsSanitize(gsImgUrl($p['images'][0]))?>" style="width:50px;height:50px;object-fit:cover;border-radius:8px" onerror="this.onerror=null;this.src='https://placehold.co/50x50?text=No+Image'"><?php else:?><div style="width:50px;height:50px;border-radius:8px;background:var(--bg3);display:flex;align-items:center;justify-content:center;color:var(--t3)"><i class="fa-solid fa-image"></i></div><?php endif;?></td>
                <td><strong><?=gsSanitize($p['title'])?></strong></td>
                <td><?=gsSanitize($p['category']??'—')?></td>
                <td><strong>৳<?=number_format(floatval($p['price']))?></strong><?php if(floatval($p['offer_price']??0)>0):?><br><span style="color:var(--a);text-decoration:line-through;font-size:.8rem">৳<?=number_format(floatval($p['offer_price']))?></span> <span class="badge-status badge-delivered" style="font-size:.7rem">-<?=$p['discount']?>%</span><?php endif;?></td>
                <td><span class="<?=intval($p['stock']??0)<=5?'low-stock':''?>"><?=intval($p['stock']??0)?></span></td>
                <td><?php
                    $flags = [];
                    if(!empty($p['featured'])) $flags[]='<span style="font-size:.7rem;background:rgba(108,99,255,.1);color:#6C63FF;padding:2px 6px;border-radius:4px">Featured</span>';
                    if(!empty($p['trending'])) $flags[]='<span style="font-size:.7rem;background:rgba(0,212,255,.1);color:#00D4FF;padding:2px 6px;border-radius:4px">Trending</span>';
                    if(!empty($p['best_seller'])) $flags[]='<span style="font-size:.7rem;background:rgba(16,185,129,.1);color:#10B981;padding:2px 6px;border-radius:4px">Best</span>';
                    if(!empty($p['flash_sale'])) $flags[]='<span style="font-size:.7rem;background:rgba(255,77,109,.1);color:#FF4D6D;padding:2px 6px;border-radius:4px">Flash</span>';
                    echo implode(' ',$flags);
                ?></td>
                <td><span class="badge-status badge-<?=($p['status']??1)?'active':'inactive'?>"><?=($p['status']??1)?'Active':'Inactive'?></span></td>
                <td>
                    <a href="admin.php?tab=products&edit=<?=$p['id']?>" class="btn btn-sm btn-outline"><i class="fa-solid fa-pen"></i></a>
                    <button class="btn btn-sm btn-danger" onclick="deleteProduct('<?=$p['id']?>')"><i class="fa-solid fa-trash"></i></button>
                </td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($products)):?><tr><td colspan="9" class="empty-msg"><i class="fa-solid fa-box-open"></i>No products yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>
<?php endif;?>

<?php
// ============ LANDING PAGES ============
elseif($tab==='landing'):
    $landingList = gsEnsureLandingEntries($products);
    $prodById = [];
    foreach($products as $p) { $prodById[$p['id']] = $p; }
?>
<div class="card">
    <div class="card-header">
        <h2>Product Landing Pages (<?=count($landingList)?>)</h2>
        <input type="text" id="landingSearch" placeholder="Search landing pages..." style="padding:8px 14px;border:2px solid var(--bd);border-radius:8px;font-size:.85rem;width:220px">
    </div>
    <div class="card-body">
        <table id="landingTable">
            <thead><tr><th>Image</th><th>Product</th><th>Landing URL</th><th>Views</th><th>Clicks</th><th>Add to Cart</th><th>Orders</th><th>Conv.</th><th>Status</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($landingList as $l):
                $p = $prodById[$l['product_id']] ?? null;
                if(!$p) continue;
                $conv = $l['views']>0 ? round(($l['orders']/$l['views'])*100,1) : 0;
                $url = gsLandingUrl($l['slug']);
            ?>
            <tr data-search="<?=strtolower(gsSanitize($p['title'].' '.$l['slug']))?>">
                <td><?php if(!empty($p['images'][0])):?><img src="<?=gsSanitize(gsImgUrl($p['images'][0]))?>" style="width:46px;height:46px;object-fit:cover;border-radius:8px" onerror="this.onerror=null;this.src='https://placehold.co/46x46?text=No+Image'"><?php else:?><div style="width:46px;height:46px;border-radius:8px;background:var(--bg3);display:flex;align-items:center;justify-content:center;color:var(--t3)"><i class="fa-solid fa-image"></i></div><?php endif;?></td>
                <td><strong><?=gsSanitize($p['title'])?></strong></td>
                <td>
                    <div style="display:flex;gap:6px;align-items:center">
                        <input type="text" readonly value="<?=gsSanitize($url)?>" style="width:180px;font-size:.75rem;padding:6px 8px;border:1px solid var(--bd);border-radius:6px;background:var(--bg3)" onclick="this.select()">
                        <button class="btn btn-sm btn-outline" title="Copy Link" onclick="copyLandingLink('<?=gsSanitize($url)?>')"><i class="fa-solid fa-copy"></i></button>
                    </div>
                </td>
                <td><?=intval($l['views'])?></td>
                <td><?=intval($l['clicks'])?></td>
                <td><?=intval($l['add_to_cart'])?></td>
                <td><?=intval($l['orders'])?></td>
                <td><?=$conv?>%</td>
                <td><span class="badge-status badge-<?=$l['enabled']?'active':'inactive'?>" style="cursor:pointer" onclick="toggleLandingStatus('<?=$p['id']?>')"><?=$l['enabled']?'Active':'Disabled'?></span></td>
                <td style="white-space:nowrap">
                    <a class="btn btn-sm btn-outline" href="<?=gsSanitize($url)?>" target="_blank" title="Open Landing Page"><i class="fa-solid fa-arrow-up-right-from-square"></i></a>
                    <button class="btn btn-sm btn-primary" title="Customize" onclick="openLandingEditor('<?=$p['id']?>')"><i class="fa-solid fa-pen"></i></button>
                    <button class="btn btn-sm btn-outline" title="Regenerate Link" onclick="regenerateLanding('<?=$p['id']?>')"><i class="fa-solid fa-rotate"></i></button>
                </td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($landingList)):?><tr><td colspan="10" class="empty-msg"><i class="fa-solid fa-rocket"></i>No products yet — add a product to get its landing page</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>

<?php
// ============ ORDERS ============
elseif($tab==='orders'):
?>
<div class="card">
    <div class="card-header">
        <h2>All Orders (<?=count($orders)?>)</h2>
        <input type="text" id="orderSearch" placeholder="Search orders..." style="padding:8px 14px;border:2px solid var(--bd);border-radius:8px;font-size:.85rem;width:200px">
    </div>
    <div class="card-body">
        <table id="ordersTable">
            <thead><tr><th>Order ID</th><th>Customer</th><th>Phone</th><th>Items</th><th>Total</th><th>Status</th><th>Date</th><th>Tracking</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach(array_reverse($orders) as $o):
                $itemCount = count($o['items']??[]);
            ?>
            <tr data-search="<?=strtolower(gsSanitize($o['id'].' '.$o['customer']['name'].' '.$o['customer']['phone'].' '.$o['tracking'].' '.$o['status']))?>">
                <td><strong><?=gsSanitize($o['id'])?></strong></td>
                <td><?=gsSanitize($o['customer']['name']??'')?></td>
                <td><?=gsSanitize($o['customer']['phone']??'')?></td>
                <td><?=$itemCount?> item(s)</td>
                <td><strong>৳<?=number_format(floatval($o['total']??0))?></strong></td>
                <td>
                    <select onchange="updateOrderStatus('<?=gsSanitize($o['id'])?>',this.value)" style="padding:6px 10px;border-radius:8px;border:2px solid var(--bd);font-size:.82rem;font-weight:600;color:inherit;background:var(--bg)">
                        <?php foreach(['pending','confirmed','processing','shipped','delivered','cancelled'] as $st):?>
                        <option value="<?=$st?>" <?=($o['status']??'pending')===$st?'selected':''?>><?=ucfirst($st)?></option>
                        <?php endforeach;?>
                    </select>
                </td>
                <td style="white-space:nowrap;font-size:.82rem"><?=gsSanitize($o['date']??'')?></td>
                <td>
                    <?php if(!empty($o['tracking'])):?>
                    <span style="color:var(--p);font-weight:600;cursor:pointer" onclick="trackOrder('<?=gsSanitize($o['tracking'])?>')"><?=gsSanitize($o['tracking'])?></span>
                    <?php else:?>—<?php endif;?>
                </td>
                <td>
                    <button class="btn btn-sm btn-outline" onclick='viewOrder(<?=json_encode($o)?>)'><i class="fa-solid fa-eye"></i></button>
                    <a href="admin.php?invoice=<?=urlencode($o['id'])?>" target="_blank" class="btn btn-sm btn-outline" title="Download Invoice"><i class="fa-solid fa-file-invoice"></i></a>
                </td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($orders)):?><tr><td colspan="9" class="empty-msg"><i class="fa-solid fa-inbox"></i>No orders yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>

<!-- Order View Modal -->
<div class="modal-overlay" id="orderModal">
    <div class="modal" style="max-width:800px">
        <div class="modal-header"><h2>Order Details</h2><button class="modal-close" onclick="closeModal('orderModal')"><i class="fa-solid fa-xmark"></i></button></div>
        <div class="modal-body" id="orderModalBody"></div>
    </div>
</div>

<!-- Tracking Modal -->
<div class="modal-overlay" id="trackModal">
    <div class="modal" style="max-width:600px">
        <div class="modal-header"><h2>Tracking Info</h2><button class="modal-close" onclick="closeModal('trackModal')"><i class="fa-solid fa-xmark"></i></button></div>
        <div class="modal-body" id="trackModalBody"><p style="text-align:center;color:var(--t3)"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</p></div>
    </div>
</div>

<?php
// ============ CATEGORIES ============
elseif($tab==='categories'):
?>
<div class="card">
    <div class="card-header"><h2>Categories (<?=count($categories)?>)</h2></div>
    <div class="card-body">
        <table>
            <thead><tr><th>Icon</th><th>Name</th><th>Products</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($categories as $c):
                $catProducts = array_filter($products, fn($p)=>($p['category']??'')===($c['name']??''));
            ?>
            <tr>
                <td><i class="fa-solid <?=gsSanitize($c['icon']??'fa-box')?>" style="font-size:1.2rem;color:var(--p)"></i></td>
                <td><strong><?=gsSanitize($c['name'])?></strong></td>
                <td><?=count($catProducts)?></td>
                <td><button class="btn btn-sm btn-danger" onclick="deleteCategory('<?=$c['id']?>')"><i class="fa-solid fa-trash"></i></button></td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($categories)):?><tr><td colspan="4" class="empty-msg"><i class="fa-solid fa-grip"></i>No categories yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>
<div class="card">
    <div class="card-header"><h2>Add Category</h2></div>
    <div class="card-body" style="padding:24px">
        <form id="addCategoryForm" style="display:flex;gap:12px;align-items:end;flex-wrap:wrap">
            <div class="form-group" style="margin:0;flex:1;min-width:150px"><label>Icon Class</label><input type="text" name="icon" value="fa-box" placeholder="fa-box" list="iconList">
                <datalist id="iconList">
                    <option value="fa-box"><option value="fa-laptop"><option value="fa-mobile"><option value="fa-headphones"><option value="fa-keyboard"><option value="fa-mouse"><option value="fa-monitor"><option value="fa-camera"><option value="fa-gamepad"><option value="fa-tv"><option value="fa-print"><option value="fa-tablet"><option value="fa-hard-drive"><option value="fa-microchip"><option value="fa-memory"><option value="fa-plug"><option value="fa-battery-full"><option value="fa-speaker"><option value="fa-watch">
                </datalist>
            </div>
            <div class="form-group" style="margin:0;flex:2;min-width:200px"><label>Name *</label><input type="text" name="name" required placeholder="Category name"></div>
            <input type="hidden" name="action" value="add_category">
            <input type="hidden" name="csrf_token" value="<?=$csrf?>">
            <button type="submit" class="btn btn-primary"><i class="fa-solid fa-plus"></i> Add</button>
        </form>
    </div>
</div>

<?php
// ============ BANNERS ============
elseif($tab==='banners'):
?>
<div class="card">
    <div class="card-header"><h2>Banners (<?=count($banners)?>)</h2></div>
    <div class="card-body">
        <table>
            <thead><tr><th>Image</th><th>Title</th><th>Link</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($banners as $b):?>
            <tr>
                <td><?php if(!empty($b['image'])):?><img src="<?=gsSanitize(gsImgUrl($b['image']))?>" style="width:120px;height:50px;object-fit:cover;border-radius:8px" onerror="this.onerror=null;this.src='https://placehold.co/120x50?text=No+Image'"><?php else:?>—<?php endif;?></td>
                <td><strong><?=gsSanitize($b['title']?:'(no title)')?></strong><br><small style="color:var(--t3)"><?=gsSanitize($b['subtitle']??'')?></small></td>
                <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?=gsSanitize($b['link']??'—')?></td>
                <td><button class="btn btn-sm btn-danger" onclick="deleteBanner('<?=$b['id']?>')"><i class="fa-solid fa-trash"></i></button></td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($banners)):?><tr><td colspan="4" class="empty-msg"><i class="fa-solid fa-images"></i>No banners yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>
<div class="card">
    <div class="card-header"><h2>Add Banner</h2></div>
    <div class="card-body" style="padding:24px">
        <form id="addBannerForm" enctype="multipart/form-data">
            <input type="hidden" name="action" value="add_banner">
            <input type="hidden" name="csrf_token" value="<?=$csrf?>">
            <div class="form-row">
                <div class="form-group"><label>Title (optional)</label><input type="text" name="title"></div>
                <div class="form-group"><label>Subtitle (optional)</label><input type="text" name="subtitle"></div>
            </div>
            <div class="form-group"><label>Banner Image *</label><input type="file" name="banner_image" accept="image/*" required></div>
            <div class="form-group"><label>Link URL (optional)</label><input type="text" name="link" placeholder="https://..."></div>
            <button type="submit" class="btn btn-primary"><i class="fa-solid fa-plus"></i> Add Banner</button>
        </form>
    </div>
</div>

<?php
// ============ COUPONS ============
elseif($tab==='coupons'):
?>
<div class="card">
    <div class="card-header"><h2>Coupons (<?=count($coupons)?>)</h2></div>
    <div class="card-body">
        <table>
            <thead><tr><th>Code</th><th>Discount</th><th>Type</th><th>Expiry</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($coupons as $c):?>
            <tr>
                <td><strong style="color:var(--p);font-size:1rem"><?=gsSanitize($c['code'])?></strong></td>
                <td><?=floatval($c['discount'])?><?=$c['type']==='percent'?'%':' ৳'?></td>
                <td><?=ucfirst(gsSanitize($c['type']??'percent'))?></td>
                <td><?=gsSanitize($c['expiry']??'No expiry')?></td>
                <td><button class="btn btn-sm btn-danger" onclick="deleteCoupon('<?=$c['id']?>')"><i class="fa-solid fa-trash"></i></button></td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($coupons)):?><tr><td colspan="5" class="empty-msg"><i class="fa-solid fa-ticket"></i>No coupons yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>
<div class="card">
    <div class="card-header"><h2>Add Coupon</h2></div>
    <div class="card-body" style="padding:24px">
        <form id="addCouponForm">
            <input type="hidden" name="action" value="add_coupon">
            <input type="hidden" name="csrf_token" value="<?=$csrf?>">
            <div class="form-row">
                <div class="form-group"><label>Code *</label><input type="text" name="code" required placeholder="GLOW10"></div>
                <div class="form-group"><label>Discount *</label><input type="number" name="discount" required step="0.01"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>Type</label><select name="type"><option value="percent">Percentage (%)</option><option value="fixed">Fixed Amount (৳)</option></select></div>
                <div class="form-group"><label>Expiry Date</label><input type="date" name="expiry"></div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="fa-solid fa-plus"></i> Add Coupon</button>
        </form>
    </div>
</div>

<?php
// ============ REVIEWS ============
elseif($tab==='reviews'):
?>
<div class="card">
    <div class="card-header"><h2>Reviews (<?=count($reviews)?>)</h2></div>
    <div class="card-body">
        <table>
            <thead><tr><th>Product</th><th>Customer</th><th>Rating</th><th>Review</th><th>Status</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($reviews as $r):
                $stars = str_repeat('<i class="fa-solid fa-star" style="color:#F59E0B"></i>', intval($r['rating']??0)) . str_repeat('<i class="fa-regular fa-star" style="color:#CBD5E1"></i>', 5-intval($r['rating']??0));
                $prodName = 'Unknown';
                foreach($products as $p) { if($p['id']===($r['product_id']??'')) { $prodName=$p['title']; break; } }
            ?>
            <tr>
                <td><strong><?=gsSanitize($prodName)?></strong></td>
                <td><?=gsSanitize($r['customer_name']??'Anonymous')?></td>
                <td><?=$stars?></td>
                <td style="max-width:250px"><?=gsSanitize($r['review']??'')?></td>
                <td><span class="badge-status badge-<?=($r['status']??0)?'active':'pending'?>"><?=($r['status']??0)?'Approved':'Pending'?></span></td>
                <td>
                    <?php if(!($r['status']??0)):?><button class="btn btn-sm btn-success" onclick="approveReview('<?=$r['id']?>')"><i class="fa-solid fa-check"></i></button><?php endif;?>
                    <button class="btn btn-sm btn-danger" onclick="deleteReview('<?=$r['id']?>')"><i class="fa-solid fa-trash"></i></button>
                </td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($reviews)):?><tr><td colspan="6" class="empty-msg"><i class="fa-solid fa-star"></i>No reviews yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>

<?php
// ============ CUSTOMERS ============
elseif($tab==='customers'):
?>
<div class="card">
    <div class="card-header"><h2>Customers (<?=count($customers)?>)</h2></div>
    <div class="card-body">
        <table>
            <thead><tr><th>Name</th><th>Phone</th><th>Address</th><th>Orders</th><th>Total Spent</th><th>Joined</th></tr></thead>
            <tbody>
            <?php foreach($customers as $c):
                $custOrders = array_filter($orders, fn($o)=>($o['customer']['phone']??'')===($c['phone']??''));
                $custTotal = array_sum(array_map(fn($o)=>floatval($o['total']??0), $custOrders));
            ?>
            <tr>
                <td><strong><?=gsSanitize($c['name']??'')?></strong></td>
                <td><?=gsSanitize($c['phone']??'')?></td>
                <td style="max-width:250px"><?=gsSanitize($c['address']??'—')?></td>
                <td><?=count($custOrders)?></td>
                <td><strong>৳<?=number_format($custTotal)?></strong></td>
                <td style="white-space:nowrap"><?=gsSanitize($c['created']??'')?></td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($customers)):?><tr><td colspan="6" class="empty-msg"><i class="fa-solid fa-users"></i>No customers yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>

<?php
// ============ SETTINGS ============
elseif($tab==='settings'):
?>
<form id="settingsForm">
<input type="hidden" name="action" value="save_settings">
<input type="hidden" name="csrf_token" value="<?=$csrf?>">

<!-- General -->
<div class="card">
    <div class="card-header"><h2><i class="fa-solid fa-store"></i> General Settings</h2></div>
    <div class="card-body" style="padding:24px">
        <div class="form-row">
            <div class="form-group"><label>Site Name</label><input type="text" name="site_name" value="<?=gsSanitize($settings['site_name']??'')?>"></div>
            <div class="form-group"><label>Tagline</label><input type="text" name="tagline" value="<?=gsSanitize($settings['tagline']??'')?>"></div>
        </div>
        <div class="form-row">
            <div class="form-group"><label>Currency Symbol</label><input type="text" name="currency" value="<?=gsSanitize($settings['currency']??'৳')?>"></div>
            <div class="form-group"><label>Currency Code</label><input type="text" name="currency_code" value="<?=gsSanitize($settings['currency_code']??'BDT')?>"></div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>Logo</label>
                <?php if(!empty($settings['logo_path'])):?><img src="<?=gsSanitize(gsImgUrl($settings['logo_path']))?>" style="height:40px;margin-bottom:8px;border-radius:8px" onerror="this.style.display='none'"><br><?php endif;?>
                <input type="file" id="logoFile" accept="image/*" onchange="uploadFile(this,'upload_logo')">
            </div>
            <div class="form-group">
                <label>Favicon</label>
                <?php if(!empty($settings['favicon_path'])):?><img src="<?=gsSanitize(gsImgUrl($settings['favicon_path']))?>" style="height:32px;margin-bottom:8px;border-radius:4px" onerror="this.style.display='none'"><br><?php endif;?>
                <input type="file" id="faviconFile" accept="image/*" onchange="uploadFile(this,'upload_favicon')">
            </div>
        </div>
    </div>
</div>

<!-- Colors -->
<div class="card">
    <div class="card-header"><h2><i class="fa-solid fa-palette"></i> Theme Colors</h2></div>
    <div class="card-body" style="padding:24px">
        <div class="form-row">
            <div class="form-group"><label>Primary Color</label><input type="color" name="primary_color" value="<?=gsSanitize($settings['primary_color']??'#6C63FF')?>" style="height:44px"></div>
            <div class="form-group"><label>Secondary Color</label><input type="color" name="secondary_color" value="<?=gsSanitize($settings['secondary_color']??'#00D4FF')?>" style="height:44px"></div>
            <div class="form-group"><label>Accent Color</label><input type="color" name="accent_color" value="<?=gsSanitize($settings['accent_color']??'#FF4D6D')?>" style="height:44px"></div>
        </div>
    </div>
</div>

<!-- Social -->
<div class="card">
    <div class="card-header"><h2><i class="fa-solid fa-share-nodes"></i> Social Links</h2></div>
    <div class="card-body" style="padding:24px">
        <div class="form-row">
            <div class="form-group"><label><i class="fa-brands fa-facebook"></i> Facebook</label><input type="text" name="facebook" value="<?=gsSanitize($settings['facebook']??'')?>" placeholder="https://..."></div>
            <div class="form-group"><label><i class="fa-brands fa-tiktok"></i> TikTok</label><input type="text" name="tiktok" value="<?=gsSanitize($settings['tiktok']??'')?>" placeholder="https://..."></div>
        </div>
        <div class="form-row">
            <div class="form-group"><label><i class="fa-brands fa-instagram"></i> Instagram</label><input type="text" name="instagram" value="<?=gsSanitize($settings['instagram']??'')?>" placeholder="https://..."></div>
            <div class="form-group"><label><i class="fa-brands fa-whatsapp"></i> WhatsApp</label><input type="text" name="whatsapp" value="<?=gsSanitize($settings['whatsapp']??'')?>" placeholder="https://..."></div>
        </div>
        <div class="form-row">
            <div class="form-group"><label><i class="fa-brands fa-facebook-messenger"></i> Messenger</label><input type="text" name="messenger" value="<?=gsSanitize($settings['messenger']??'')?>" placeholder="https://..."></div>
            <div class="form-group"><label><i class="fa-brands fa-telegram"></i> Telegram</label><input type="text" name="telegram" value="<?=gsSanitize($settings['telegram']??'')?>" placeholder="https://..."></div>
        </div>
        <div class="form-row">
            <div class="form-group"><label><i class="fa-brands fa-youtube"></i> YouTube</label><input type="text" name="youtube" value="<?=gsSanitize($settings['youtube']??'')?>" placeholder="https://..."></div>
            <div class="form-group"><label><i class="fa-brands fa-linkedin"></i> LinkedIn</label><input type="text" name="linkedin" value="<?=gsSanitize($settings['linkedin']??'')?>" placeholder="https://..."></div>
        </div>
    </div>
</div>

<!-- SEO -->
<div class="card">
    <div class="card-header"><h2><i class="fa-solid fa-magnifying-glass"></i> SEO</h2></div>
    <div class="card-body" style="padding:24px">
        <div class="form-group"><label>SEO Title</label><input type="text" name="seo_title" value="<?=gsSanitize($settings['seo_title']??'')?>"></div>
        <div class="form-group"><label>SEO Description</label><textarea name="seo_description" rows="2"><?=gsSanitize($settings['seo_description']??'')?></textarea></div>
        <div class="form-group"><label>SEO Keywords</label><input type="text" name="seo_keywords" value="<?=gsSanitize($settings['seo_keywords']??'')?>"></div>
        <div class="form-group"><label>Google Analytics ID</label><input type="text" name="google_analytics" value="<?=gsSanitize($settings['google_analytics']??'')?>"></div>
        <div class="form-group"><label>Facebook Pixel ID</label><input type="text" name="facebook_pixel" value="<?=gsSanitize($settings['facebook_pixel']??'')?>"></div>
    </div>
</div>

<!-- Toggles -->
<div class="card">
    <div class="card-header"><h2><i class="fa-solid fa-sliders"></i> Feature Toggles</h2></div>
    <div class="card-body" style="padding:24px">
        <div style="display:flex;flex-direction:column;gap:16px">
            <label class="form-check"><input type="checkbox" name="maintenance" value="1" <?=($settings['maintenance']??false)?'checked':''?>> <strong>Maintenance Mode</strong> — Hide store from visitors</label>
            <label class="form-check"><input type="checkbox" name="promo_popup" value="1" <?=($settings['promo_popup']??true)?'checked':''?>> <strong>Promo Popup</strong> — Show welcome popup</label>
            <label class="form-check"><input type="checkbox" name="cookie_notice" value="1" <?=($settings['cookie_notice']??true)?'checked':''?>> <strong>Cookie Notice</strong> — Show cookie bar</label>
        </div>
        <div class="form-group" style="margin-top:16px"><label>Promo Popup Text</label><textarea name="promo_text" rows="2"><?=gsSanitize($settings['promo_text']??'')?></textarea></div>
    </div>
</div>

<!-- Data Management -->
<div class="card">
    <div class="card-header"><h2><i class="fa-solid fa-database"></i> Data Management</h2></div>
    <div class="card-body" style="padding:24px">
        <div style="display:flex;gap:12px;flex-wrap:wrap">
            <button type="button" class="btn btn-primary" onclick="backupData()"><i class="fa-solid fa-download"></i> Backup All Data</button>
            <label class="btn btn-outline" style="cursor:pointer"><i class="fa-solid fa-upload"></i> Restore Backup<input type="file" name="backup_file" accept=".json" style="display:none" onchange="restoreData(this)"></label>
            <button type="button" class="btn btn-outline" onclick="exportProducts()"><i class="fa-solid fa-file-export"></i> Export Products</button>
            <button type="button" class="btn btn-outline" onclick="document.getElementById('importFile').click()"><i class="fa-solid fa-file-import"></i> Import Products</button>
            <input type="file" id="importFile" accept=".json" style="display:none" onchange="importProducts(this)">
        </div>
    </div>
</div>

<button type="submit" class="btn btn-primary" style="padding:14px 32px;font-size:1rem"><i class="fa-solid fa-save"></i> Save All Settings</button>
</form>

<?php
// ============ LOGS ============
elseif($tab==='logs'):
?>
<div class="card">
    <div class="card-header">
        <h2>Activity Logs (<?=count($logs)?>)</h2>
        <button class="btn btn-sm btn-danger" onclick="clearLogs()"><i class="fa-solid fa-trash"></i> Clear All</button>
    </div>
    <div class="card-body">
        <table>
            <thead><tr><th>Time</th><th>Admin</th><th>Action</th><th>Detail</th></tr></thead>
            <tbody>
            <?php foreach($logs as $l):?>
            <tr>
                <td style="white-space:nowrap"><?=gsSanitize($l['time'])?></td>
                <td><strong><?=gsSanitize($l['admin']??'')?></strong></td>
                <td><?=gsSanitize($l['action'])?></td>
                <td style="color:var(--t2)"><?=gsSanitize($l['detail']??'')?></td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($logs)):?><tr><td colspan="4" class="empty-msg"><i class="fa-solid fa-clock-rotate-left"></i>No logs yet</td></tr><?php endif;?>
            </tbody>
        </table>
    </div>
</div>

<?php endif;?>

</div><!-- /content -->
</div><!-- /main -->

<!-- Add Product Modal -->
<div class="modal-overlay" id="addProductModal">
    <div class="modal" style="max-width:800px">
        <div class="modal-header"><h2>Add New Product</h2><button class="modal-close" onclick="closeModal('addProductModal')"><i class="fa-solid fa-xmark"></i></button></div>
        <div class="modal-body">
            <form id="addProductForm" enctype="multipart/form-data">
                <input type="hidden" name="action" value="add_product">
                <input type="hidden" name="csrf_token" value="<?=$csrf?>">
                <div class="form-row">
                    <div class="form-group"><label>Title *</label><input type="text" name="title" required></div>
                    <div class="form-group"><label>Subtitle</label><input type="text" name="subtitle"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Brand</label><input type="text" name="brand" list="brandList2">
                        <datalist id="brandList2"><?=implode('',array_unique(array_map(fn($p)=>'<option value="'.gsSanitize($p['brand']??'').'">', $products)))?></datalist>
                    </div>
                    <div class="form-group"><label>Category</label><select name="category"><option value="">Select</option><?php foreach($categories as $c):?><option value="<?=gsSanitize($c['name'])?>"><?=gsSanitize($c['name'])?></option><?php endforeach;?></select></div>
                </div>
                <div class="form-group"><label>Description</label><textarea name="description" rows="3"></textarea></div>
                <div class="form-group"><label>Features (one per line)</label><textarea name="features" rows="2"></textarea></div>
                <div class="form-row">
                    <div class="form-group"><label>Regular Price *</label><input type="number" name="price" required step="0.01"></div>
                    <div class="form-group"><label>Offer Price</label><input type="number" name="offer_price" step="0.01"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Stock *</label><input type="number" name="stock" required></div>
                    <div class="form-group"><label>Warranty</label><input type="text" name="warranty" placeholder="e.g. 1 Year"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Color</label><input type="text" name="color"></div>
                    <div class="form-group"><label>Sizes &amp; Unit</label>
                        <div class="size-row">
                            <input type="text" name="sizes" placeholder='e.g. 24, 27, 32'>
                            <select name="size_unit">
                                <option value="">No unit</option>
                                <option value="inch">Inch (")</option>
                                <option value="feet">Feet (ft)</option>
                                <option value="cm">Centimeter (cm)</option>
                                <option value="mm">Millimeter (mm)</option>
                                <option value="meter">Meter (m)</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Specifications</label>
                    <div id="addSpecContainer"></div>
                    <button type="button" class="btn btn-sm btn-outline" style="margin-top:8px" onclick="addSpecRow('addSpecContainer')"><i class="fa-solid fa-plus"></i> Add Spec</button>
                </div>
                <div class="form-group"><label>Images *</label><input type="file" name="images[]" multiple accept="image/*" required></div>
                <div class="form-group"><label>Flags</label>
                    <div style="display:flex;flex-wrap:wrap;gap:12px;margin-top:4px">
                        <label class="form-check"><input type="checkbox" name="featured" value="1"> Featured</label>
                        <label class="form-check"><input type="checkbox" name="trending" value="1"> Trending</label>
                        <label class="form-check"><input type="checkbox" name="best_seller" value="1"> Best Seller</label>
                        <label class="form-check"><input type="checkbox" name="flash_sale" value="1"> Flash Sale</label>
                        <label class="form-check"><input type="checkbox" name="new_arrival" value="1"> New Arrival</label>
                        <label class="form-check"><input type="checkbox" name="recommended" value="1"> Recommended</label>
                        <label class="form-check"><input type="checkbox" name="status" value="1" checked> Active</label>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-plus"></i> Add Product</button>
            </form>
        </div>
    </div>
</div>

<!-- Landing Page Customize Modal -->
<div class="modal-overlay" id="landingModal">
    <div class="modal" style="max-width:900px">
        <div class="modal-header"><h2 id="landingModalTitle">Customize Landing Page</h2><button class="modal-close" onclick="closeModal('landingModal')"><i class="fa-solid fa-xmark"></i></button></div>
        <div class="modal-body">
            <form id="landingForm" enctype="multipart/form-data">
                <input type="hidden" name="action" value="save_landing">
                <input type="hidden" name="csrf_token" value="<?=$csrf?>">
                <input type="hidden" name="product_id" id="lp_product_id">

                <div class="form-group"><label>Landing Page URL</label>
                    <div style="display:flex;gap:8px;align-items:center">
                        <span id="lp_url_prefix" style="color:var(--t3);font-size:.82rem"><?=gsSanitize(gsBaseUrl())?>/landing.php?slug=</span>
                        <input type="text" name="slug" id="lp_slug" placeholder="product-slug" style="flex:1">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label class="form-check"><input type="checkbox" name="enabled" id="lp_enabled" value="1"> Landing Page Enabled</label></div>
                    <div class="form-group"><label>CTA Button Text</label><input type="text" name="cta_text" id="lp_cta_text" placeholder="Order Now"></div>
                </div>

                <h3 style="margin:18px 0 8px;font-size:1rem;color:var(--p)"><i class="fa-solid fa-pen-nib"></i> Content</h3>
                <div class="form-group"><label>Custom Headline</label><input type="text" name="headline" id="lp_headline"></div>
                <div class="form-group"><label>Custom Description</label><textarea name="description" id="lp_description" rows="3"></textarea></div>
                <div class="form-group"><label>Benefits (one per line)</label><textarea name="benefits" id="lp_benefits" rows="3" placeholder="Fast charging&#10;1 year warranty&#10;Free delivery"></textarea></div>
                <div class="form-row">
                    <div class="form-group"><label>Banner Image</label><input type="file" name="banner_image" accept="image/*"><div id="lp_banner_preview"></div></div>
                    <div class="form-group"><label>Promotional Video URL</label><input type="text" name="promo_video_url" id="lp_video" placeholder="https://youtube.com/watch?v=..."></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label class="form-check"><input type="checkbox" name="countdown_enabled" id="lp_countdown_enabled" value="1"> Enable Countdown Timer</label></div>
                    <div class="form-group"><label>Countdown End</label><input type="datetime-local" name="countdown_end" id="lp_countdown_end"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Before Image</label><input type="file" name="before_image" accept="image/*"><div id="lp_before_preview"></div></div>
                    <div class="form-group"><label>After Image</label><input type="file" name="after_image" accept="image/*"><div id="lp_after_preview"></div></div>
                </div>

                <h3 style="margin:18px 0 8px;font-size:1rem;color:var(--p)"><i class="fa-solid fa-award"></i> Feature Icons</h3>
                <div id="lp_featContainer"></div>
                <button type="button" class="btn btn-sm btn-outline" onclick="addFeatRow()"><i class="fa-solid fa-plus"></i> Add Feature</button>

                <h3 style="margin:18px 0 8px;font-size:1rem;color:var(--p)"><i class="fa-solid fa-quote-left"></i> Testimonials</h3>
                <div id="lp_testiContainer"></div>
                <button type="button" class="btn btn-sm btn-outline" onclick="addTestiRow()"><i class="fa-solid fa-plus"></i> Add Testimonial</button>

                <h3 style="margin:18px 0 8px;font-size:1rem;color:var(--p)"><i class="fa-solid fa-circle-question"></i> FAQ</h3>
                <div id="lp_faqContainer"></div>
                <button type="button" class="btn btn-sm btn-outline" onclick="addFaqRow()"><i class="fa-solid fa-plus"></i> Add FAQ</button>

                <h3 style="margin:18px 0 8px;font-size:1rem;color:var(--p)"><i class="fa-solid fa-truck"></i> Delivery &amp; Returns</h3>
                <div class="form-row">
                    <div class="form-group"><label>Delivery Information</label><textarea name="delivery_info" id="lp_delivery" rows="3"></textarea></div>
                    <div class="form-group"><label>Return Policy</label><textarea name="return_policy" id="lp_return" rows="3"></textarea></div>
                </div>

                <h3 style="margin:18px 0 8px;font-size:1rem;color:var(--p)"><i class="fa-solid fa-bullhorn"></i> Marketing &amp; SEO</h3>
                <div class="form-row">
                    <div class="form-group"><label>Facebook Pixel ID</label><input type="text" name="fb_pixel" id="lp_fb_pixel"></div>
                    <div class="form-group"><label>TikTok Pixel ID</label><input type="text" name="tiktok_pixel" id="lp_tiktok_pixel"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Google Analytics ID</label><input type="text" name="ga_id" id="lp_ga_id"></div>
                    <div class="form-group"><label>Canonical URL (optional)</label><input type="text" name="canonical_url" id="lp_canonical"></div>
                </div>
                <div class="form-group"><label>SEO Title</label><input type="text" name="seo_title" id="lp_seo_title"></div>
                <div class="form-group"><label>SEO Description</label><textarea name="seo_description" id="lp_seo_description" rows="2"></textarea></div>
                <div class="form-row">
                    <div class="form-group"><label>SEO Keywords</label><input type="text" name="seo_keywords" id="lp_seo_keywords" placeholder="comma, separated, keywords"></div>
                    <div class="form-group"><label>Open Graph Image</label><input type="file" name="og_image" accept="image/*"></div>
                </div>
                <div class="form-group"><label>Extra Meta Tags (raw HTML, optional)</label><textarea name="meta_tags" id="lp_meta_tags" rows="2"></textarea></div>

                <button type="submit" class="btn btn-primary" style="margin-top:8px"><i class="fa-solid fa-save"></i> Save Landing Page</button>
            </form>
        </div>
    </div>
</div>

<script>
const CSRF = '<?=$csrf?>';
const LANDING_DATA = <?=json_encode(array_column($landingList ?? [], null, 'product_id'), JSON_UNESCAPED_UNICODE)?>;
const LANDING_BASE_URL = '<?=gsSanitize(gsBaseUrl())?>';

// Toast notification
function toast(msg, isError=false) {
    const wrap = document.getElementById('toastWrap');
    const t = document.createElement('div');
    t.className = 'toast' + (isError?' error':'');
    t.innerHTML = '<i class="fa-solid '+(isError?'fa-circle-xmark':'fa-circle-check')+'"></i> ' + msg;
    wrap.appendChild(t);
    setTimeout(()=>{ t.style.opacity='0'; t.style.transform='translateX(30px)'; setTimeout(()=>t.remove(),300); }, 4000);
}

// Modal
function openModal(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow='hidden'; }
function closeModal(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow=''; }

// Sidebar
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('open');
    document.getElementById('sidebarOverlay').classList.toggle('show');
}

// API call helper — now also surfaces a clear message if the server
// ever returns something that isn't valid JSON (e.g. a hosting-level error page)
async function apiCall(formData, isFile=false) {
    let res;
    if(isFile) {
        res = await fetch('admin.php', { method:'POST', body: formData });
    } else {
        res = await fetch('admin.php', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body: JSON.stringify(Object.fromEntries(formData))
        });
    }
    return res;
}
async function safeJson(res) {
    const text = await res.text();
    try { return JSON.parse(text); }
    catch(e) { return { success:false, msg: 'Unexpected server response (HTTP '+res.status+'). Check server error logs.' }; }
}

// Add Product
function openAddProduct() { openModal('addProductModal'); }
document.getElementById('addProductForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const res = await apiCall(fd, true);
    const data = await safeJson(res);
    if(data.success) { toast(data.msg); closeModal('addProductModal'); this.reset(); setTimeout(()=>location.reload(), 800); }
    else toast(data.msg||'Error', true);
});

// Edit Product
document.getElementById('editProductForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const res = await apiCall(fd, true);
    const data = await safeJson(res);
    if(data.success) { toast(data.msg); setTimeout(()=>location.href='admin.php?tab=products', 800); }
    else toast(data.msg||'Error', true);
});

function removeEditImage(btn, imgPath) {
    const wrap = btn.closest('div');
    wrap.style.display='none';
    const form = document.getElementById('editProductForm');
    const hidden = document.createElement('input');
    hidden.type='hidden'; hidden.name='remove_images[]'; hidden.value=imgPath;
    form.appendChild(hidden);
}

// ===================== Landing Pages =====================
function copyLandingLink(url) {
    navigator.clipboard.writeText(url).then(()=>toast('Link copied to clipboard')).catch(()=>toast('Could not copy link', true));
}

function toggleLandingStatus(productId) {
    const fd = new FormData(); fd.append('action','toggle_landing_status'); fd.append('product_id',productId); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

function regenerateLanding(productId) {
    if(!confirm('Generate a new landing page link for this product? The old link will stop working.')) return;
    const fd = new FormData(); fd.append('action','regenerate_landing'); fd.append('product_id',productId); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),600);}else toast(d.msg||'Error',true); });
}

function lpImgTag(path) {
    if(!path) return '';
    return '<img src="'+path+'" style="width:70px;height:70px;object-fit:cover;border-radius:8px;margin-top:8px" onerror="this.style.display=\'none\'">';
}

function addFeatRow(icon,title,desc) {
    const c = document.getElementById('lp_featContainer');
    const row = document.createElement('div');
    row.className = 'spec-row';
    row.innerHTML = '<input type="text" name="feat_icon[]" placeholder="fa-solid fa-bolt" value="'+(icon||'')+'">'
        + '<input type="text" name="feat_title[]" placeholder="Title" value="'+(title||'')+'">'
        + '<input type="text" name="feat_desc[]" placeholder="Short description" value="'+(desc||'')+'">'
        + '<button type="button" class="remove-spec" onclick="this.parentElement.remove()"><i class="fa-solid fa-xmark"></i></button>';
    c.appendChild(row);
}

function addTestiRow(name,text,rating,image) {
    const c = document.getElementById('lp_testiContainer');
    const row = document.createElement('div');
    row.className = 'spec-row';
    row.style.alignItems = 'center';
    row.innerHTML = '<input type="text" name="testi_name[]" placeholder="Customer name" value="'+(name||'')+'">'
        + '<input type="text" name="testi_text[]" placeholder="Review text" value="'+(text||'')+'">'
        + '<input type="number" name="testi_rating[]" min="1" max="5" placeholder="5" style="width:60px" value="'+(rating||5)+'">'
        + '<input type="hidden" name="testi_existing_image[]" value="'+(image||'')+'">'
        + '<input type="file" name="testi_images[]" accept="image/*" style="width:120px">'
        + '<button type="button" class="remove-spec" onclick="this.parentElement.remove()"><i class="fa-solid fa-xmark"></i></button>';
    c.appendChild(row);
}

function addFaqRow(q,a) {
    const c = document.getElementById('lp_faqContainer');
    const row = document.createElement('div');
    row.className = 'spec-row';
    row.innerHTML = '<input type="text" name="faq_q[]" placeholder="Question" value="'+(q||'')+'">'
        + '<input type="text" name="faq_a[]" placeholder="Answer" value="'+(a||'')+'">'
        + '<button type="button" class="remove-spec" onclick="this.parentElement.remove()"><i class="fa-solid fa-xmark"></i></button>';
    c.appendChild(row);
}

function openLandingEditor(productId) {
    const l = LANDING_DATA[productId];
    if(!l) { toast('Landing page data not found', true); return; }
    document.getElementById('lp_product_id').value = productId;
    document.getElementById('lp_slug').value = l.slug || '';
    document.getElementById('lp_enabled').checked = !!l.enabled;
    document.getElementById('lp_cta_text').value = l.cta_text || 'Order Now';
    document.getElementById('lp_headline').value = l.headline || '';
    document.getElementById('lp_description').value = l.description || '';
    document.getElementById('lp_benefits').value = (l.benefits||[]).join('\n');
    document.getElementById('lp_video').value = l.promo_video_url || '';
    document.getElementById('lp_countdown_enabled').checked = !!l.countdown_enabled;
    document.getElementById('lp_countdown_end').value = l.countdown_end || '';
    document.getElementById('lp_delivery').value = l.delivery_info || '';
    document.getElementById('lp_return').value = l.return_policy || '';
    document.getElementById('lp_fb_pixel').value = l.fb_pixel || '';
    document.getElementById('lp_tiktok_pixel').value = l.tiktok_pixel || '';
    document.getElementById('lp_ga_id').value = l.ga_id || '';
    document.getElementById('lp_canonical').value = l.canonical_url || '';
    document.getElementById('lp_seo_title').value = l.seo_title || '';
    document.getElementById('lp_seo_description').value = l.seo_description || '';
    document.getElementById('lp_seo_keywords').value = l.seo_keywords || '';
    document.getElementById('lp_meta_tags').value = l.meta_tags || '';
    document.getElementById('lp_banner_preview').innerHTML = lpImgTag(l.banner_image);
    document.getElementById('lp_before_preview').innerHTML = lpImgTag(l.before_image);
    document.getElementById('lp_after_preview').innerHTML = lpImgTag(l.after_image);

    document.getElementById('lp_featContainer').innerHTML = '';
    (l.feature_icons||[]).forEach(f=>addFeatRow(f.icon,f.title,f.desc));
    document.getElementById('lp_testiContainer').innerHTML = '';
    (l.testimonials||[]).forEach(t=>addTestiRow(t.name,t.text,t.rating,t.image));
    document.getElementById('lp_faqContainer').innerHTML = '';
    (l.faq||[]).forEach(f=>addFaqRow(f.q,f.a));

    document.getElementById('landingModalTitle').textContent = 'Customize Landing Page';
    openModal('landingModal');
}

document.getElementById('landingForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const res = await apiCall(fd, true);
    const data = await safeJson(res);
    if(data.success) { toast(data.msg); closeModal('landingModal'); setTimeout(()=>location.reload(), 700); }
    else toast(data.msg||'Error', true);
});

document.getElementById('landingSearch')?.addEventListener('input', function() {
    const q = this.value.toLowerCase();
    document.querySelectorAll('#landingTable tbody tr').forEach(tr => {
        tr.style.display = tr.dataset.search?.includes(q) ? '' : 'none';
    });
});

// Delete Product
function deleteProduct(id) {
    if(!confirm('Delete this product?')) return;
    const fd = new FormData(); fd.append('action','delete_product'); fd.append('id',id); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

// Bulk Delete
document.getElementById('selectAllProducts')?.addEventListener('change', function() {
    document.querySelectorAll('.product-check').forEach(c=>c.checked=this.checked);
    document.getElementById('bulkDeleteBtn').style.display = this.checked?'inline-flex':'none';
});
document.addEventListener('change', function(e) {
    if(e.target.classList.contains('product-check')) {
        const checked = document.querySelectorAll('.product-check:checked').length;
        document.getElementById('bulkDeleteBtn').style.display = checked>0?'inline-flex':'none';
        document.getElementById('selectAllProducts').checked = checked===document.querySelectorAll('.product-check').length;
    }
});
function bulkDeleteProducts() {
    const ids = Array.from(document.querySelectorAll('.product-check:checked')).map(c=>c.value);
    if(!ids.length||!confirm('Delete '+ids.length+' products?')) return;
    const fd = new FormData(); fd.append('action','bulk_delete'); fd.append('csrf_token',CSRF); fd.append('ids',JSON.stringify(ids));
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

// Category
document.getElementById('addCategoryForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const res = await apiCall(fd); const data = await safeJson(res);
    if(data.success){toast(data.msg);this.reset();setTimeout(()=>location.reload(),500);}else toast(data.msg||'Error',true);
});
function deleteCategory(id) {
    if(!confirm('Delete this category?')) return;
    const fd = new FormData(); fd.append('action','delete_category'); fd.append('id',id); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

// Banner
document.getElementById('addBannerForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const res = await apiCall(fd, true); const data = await safeJson(res);
    if(data.success){toast(data.msg);this.reset();setTimeout(()=>location.reload(),500);}else toast(data.msg||'Error',true);
});
function deleteBanner(id) {
    if(!confirm('Delete this banner?')) return;
    const fd = new FormData(); fd.append('action','delete_banner'); fd.append('id',id); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

// Coupon
document.getElementById('addCouponForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const res = await apiCall(fd); const data = await safeJson(res);
    if(data.success){toast(data.msg);this.reset();setTimeout(()=>location.reload(),500);}else toast(data.msg||'Error',true);
});
function deleteCoupon(id) {
    if(!confirm('Delete this coupon?')) return;
    const fd = new FormData(); fd.append('action','delete_coupon'); fd.append('id',id); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

// Orders
function updateOrderStatus(orderId, status) {
    const fd = new FormData(); fd.append('action','update_order_status'); fd.append('order_id',orderId); fd.append('status',status); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success) toast(d.msg); else toast(d.msg||'Error',true); });
}
function viewOrder(order) {
    let html = '<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">';
    html += '<div><strong>Order:</strong> '+order.id+'</div>';
    html += '<div><strong>Date:</strong> '+order.date+'</div>';
    html += '<div><strong>Name:</strong> '+(order.customer?.name||'')+'</div>';
    html += '<div><strong>Phone:</strong> '+(order.customer?.phone||'')+'</div>';
    html += '<div style="grid-column:1/-1"><strong>Address:</strong> '+(order.customer?.address||'')+'</div>';
    if(order.note) html += '<div style="grid-column:1/-1"><strong>Note:</strong> '+order.note+'</div>';
    html += '</div>';
    html += '<table><thead><tr><th>Product</th><th>Qty</th><th>Price</th></tr></thead><tbody>';
    (order.items||[]).forEach(item => {
        html += '<tr><td>'+(item.title||'')+'</td><td>'+item.qty+'</td><td>৳'+Number(item.price).toLocaleString()+'</td></tr>';
    });
    html += '</tbody></table>';
    html += '<div style="text-align:right;margin-top:16px;font-size:1.2rem;font-weight:900">Total: ৳'+Number(order.total).toLocaleString()+'</div>';
    html += '<div style="text-align:right;margin-top:12px"><a class="btn btn-sm btn-primary" href="admin.php?invoice='+encodeURIComponent(order.id)+'" target="_blank"><i class="fa-solid fa-file-invoice"></i> Download Invoice</a></div>';
    document.getElementById('orderModalBody').innerHTML = html;
    openModal('orderModal');
}
function trackOrder(code) {
    document.getElementById('trackModalBody').innerHTML = '<p style="text-align:center;color:var(--t3)"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</p>';
    openModal('trackModal');
    fetch('admin.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'track_steadfast',tracking:code,csrf_token:CSRF})})
    .then(safeJson).then(d=>{
        if(d.error) { document.getElementById('trackModalBody').innerHTML='<p style="color:var(--a)">'+d.error+'</p>'; return; }
        if(d.delivery_status) {
            let html = '<div style="margin-bottom:16px"><strong>Status:</strong> <span class="badge-status badge-'+(d.delivery_status==='delivered'?'delivered':'pending')+'">'+d.delivery_status+'</span></div>';
            html += '<div style="border-left:3px solid var(--p);padding-left:16px">';
            (d.status||[]).forEach(s => {
                html += '<div style="margin-bottom:12px"><strong style="color:var(--t)">'+s.status+'</strong><br><small style="color:var(--t3)">'+s.timestamp+'</small></div>';
            });
            html += '</div>';
            document.getElementById('trackModalBody').innerHTML = html;
        } else {
            document.getElementById('trackModalBody').innerHTML = '<pre>'+JSON.stringify(d,null,2)+'</pre>';
        }
    }).catch(()=>{ document.getElementById('trackModalBody').innerHTML='<p style="color:var(--a)">Failed to fetch tracking info</p>'; });
}

// Reviews
function approveReview(id) {
    const fd = new FormData(); fd.append('action','approve_review'); fd.append('id',id); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}
function deleteReview(id) {
    if(!confirm('Delete this review?')) return;
    const fd = new FormData(); fd.append('action','delete_review'); fd.append('id',id); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

// Settings
document.getElementById('settingsForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const res = await apiCall(fd); const data = await safeJson(res);
    if(data.success) toast(data.msg); else toast(data.msg||'Error',true);
});

// File upload (logo/favicon)
async function uploadFile(input, action) {
    if(!input.files[0]) return;
    const fd = new FormData(); fd.append('action',action); fd.append('file',input.files[0]); fd.append('csrf_token',CSRF);
    const res = await fetch('admin.php',{method:'POST',body:fd});
    const data = await safeJson(res);
    if(data.success) { toast(data.msg); setTimeout(()=>location.reload(),800); }
    else toast(data.msg||'Error',true);
}

// Backup/Restore
function backupData() {
    const fd = new FormData(); fd.append('action','backup'); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{
        if(d.success) {
            const a = document.createElement('a');
            a.href = 'data/'+d.msg; a.download = d.msg; a.click();
            toast('Backup downloaded');
        } else toast(d.msg||'Error',true);
    });
}
function restoreData(input) {
    if(!input.files[0]||!confirm('This will overwrite ALL data. Continue?')) return;
    const fd = new FormData(); fd.append('action','restore'); fd.append('backup_file',input.files[0]); fd.append('csrf_token',CSRF);
    fetch('admin.php',{method:'POST',body:fd}).then(safeJson).then(d=>{
        if(d.success){toast(d.msg);setTimeout(()=>location.reload(),1000);}else toast(d.msg||'Error',true);
    });
}
function exportProducts() {
    const fd = new FormData(); fd.append('action','export_products'); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{
        if(d.success) {
            const blob = new Blob([JSON.stringify(d.data,null,2)],{type:'application/json'});
            const a = document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='products_export.json'; a.click();
            toast('Products exported');
        } else toast(d.msg||'Error', true);
    });
}
function importProducts(input) {
    if(!input.files[0]) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        const fd = new FormData(); fd.append('action','import_products'); fd.append('json_data',e.target.result); fd.append('csrf_token',CSRF);
        apiCall(fd).then(safeJson).then(d=>{
            if(d.success){toast(d.msg);setTimeout(()=>location.reload(),800);}else toast(d.msg||'Error',true);
        });
    };
    reader.readAsText(input.files[0]);
}

// Clear Logs
function clearLogs() {
    if(!confirm('Clear all activity logs?')) return;
    const fd = new FormData(); fd.append('action','clear_logs'); fd.append('csrf_token',CSRF);
    apiCall(fd).then(safeJson).then(d=>{ if(d.success){toast(d.msg);setTimeout(()=>location.reload(),500);}else toast(d.msg||'Error',true); });
}

// Spec rows
function addSpecRow(containerId) {
    const container = document.getElementById(containerId || 'specContainer');
    const row = document.createElement('div');
    row.className = 'spec-row';
    row.innerHTML = '<input type="text" name="spec_keys[]" placeholder="Key"><input type="text" name="spec_values[]" placeholder="Value"><button type="button" class="remove-spec" onclick="this.parentElement.remove()"><i class="fa-solid fa-xmark"></i></button>';
    container.appendChild(row);
}

// Search
document.getElementById('productSearch')?.addEventListener('input', function() {
    const q = this.value.toLowerCase();
    document.querySelectorAll('#productsTable tbody tr').forEach(tr => {
        tr.style.display = tr.dataset.search?.includes(q) ? '' : 'none';
    });
});
document.getElementById('orderSearch')?.addEventListener('input', function() {
    const q = this.value.toLowerCase();
    document.querySelectorAll('#ordersTable tbody tr').forEach(tr => {
        tr.style.display = tr.dataset.search?.includes(q) ? '' : 'none';
    });
});

// Close modals on overlay click
document.querySelectorAll('.modal-overlay').forEach(m => {
    m.addEventListener('click', function(e) { if(e.target===this) closeModal(this.id); });
});
</script>
</body>
</html>