<?php
require_once '../config/database.php';
require_once '../includes/functions.php';

/* ── Session + Auth ─────────────────────────────────────────────────────────── */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['admin_id'])) { header('Location: login.php'); exit; }

$conn       = getConnection();
$themeColor = getSetting('theme_color', '#5B77F5');
$editId     = isset($_GET['id']) ? intval($_GET['id']) : 0;
$isEdit     = $editId > 0;
$pageTitle  = $isEdit ? 'Edit Product' : 'Add Product';

function hexToRgbPf($hex) {
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $r = hexdec(str_repeat(substr($hex,0,1),2));
        $g = hexdec(str_repeat(substr($hex,1,1),2));
        $b = hexdec(str_repeat(substr($hex,2,1),2));
    } else {
        $r = hexdec(substr($hex,0,2));
        $g = hexdec(substr($hex,2,2));
        $b = hexdec(substr($hex,4,2));
    }
    return "$r,$g,$b";
}
$rgbColor = hexToRgbPf($themeColor);

/* ── Resolve upload directories ─────────────────────────────────────────────── */
$rootDir   = dirname(dirname(__FILE__));
$uploadDir = $rootDir . '/secure_uploads/products/';
$coverDir  = $rootDir . '/uploads/covers/';

if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
if (!is_dir($coverDir))  mkdir($coverDir,  0755, true);

$htaccessFile = $uploadDir . '.htaccess';
if (!file_exists($htaccessFile)) {
    file_put_contents($htaccessFile, "Options -Indexes\nDeny from all\n");
}

/* ══════════════════════════════════════════════════════════════════════════════
   CHUNKED UPLOAD HANDLER — called via AJAX
   POST ?action=chunk_upload
══════════════════════════════════════════════════════════════════════════════ */
if (isset($_GET['action']) && $_GET['action'] === 'chunk_upload') {
    header('Content-Type: application/json');
    if (!isset($_SESSION['admin_id'])) { echo json_encode(['error'=>'Unauthorized']); exit; }

    $chunkIndex  = intval($_POST['chunk_index']  ?? 0);
    $totalChunks = intval($_POST['total_chunks'] ?? 1);
    $uploadId    = preg_replace('/[^a-zA-Z0-9_]/', '', $_POST['upload_id'] ?? '');
    $origName    = basename($_POST['file_name']  ?? 'upload');
    $safeExt     = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    $allowedExts = ['pdf','zip','rar','tar','gz','epub','docx','doc','txt','mp4','mp3','exe','apk'];

    if (!$uploadId) { echo json_encode(['error'=>'Missing upload ID']); exit; }
    if (!in_array($safeExt, $allowedExts)) { echo json_encode(['error'=>"File type .$safeExt not allowed"]); exit; }

    if (!isset($_FILES['chunk']) || $_FILES['chunk']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['error'=>'Chunk upload failed: code '.($_FILES['chunk']['error']??'?')]); exit;
    }

    $tmpDir  = sys_get_temp_dir() . '/prod_chunks_' . session_id() . '/';
    if (!is_dir($tmpDir)) mkdir($tmpDir, 0755, true);

    $chunkFile = $tmpDir . $uploadId . '_' . $chunkIndex . '.part';
    if (!move_uploaded_file($_FILES['chunk']['tmp_name'], $chunkFile)) {
        echo json_encode(['error'=>'Could not save chunk']); exit;
    }

    // All chunks received — assemble
    if ($chunkIndex === $totalChunks - 1) {
        $newFilename = 'prod_' . time() . '_' . mt_rand(1000,9999) . '.' . $safeExt;
        $destPath    = $uploadDir . $newFilename;
        $out = fopen($destPath, 'wb');
        if (!$out) { echo json_encode(['error'=>'Cannot write to upload directory']); exit; }

        for ($i = 0; $i < $totalChunks; $i++) {
            $part = $tmpDir . $uploadId . '_' . $i . '.part';
            if (!file_exists($part)) { fclose($out); echo json_encode(['error'=>"Missing chunk $i"]); exit; }
            $in = fopen($part, 'rb');
            while (!feof($in)) fwrite($out, fread($in, 8192));
            fclose($in);
            @unlink($part);
        }
        fclose($out);
        @rmdir($tmpDir);

        $finfo    = finfo_open(FILEINFO_MIME_TYPE);
        $fileType = finfo_file($finfo, $destPath);
        finfo_close($finfo);
        $fileSize = filesize($destPath);

        echo json_encode([
            'done'      => true,
            'file_path' => $newFilename,
            'file_name' => $origName,
            'file_size' => $fileSize,
            'file_type' => $fileType,
        ]);
        exit;
    }

    echo json_encode(['done'=>false,'chunk'=>$chunkIndex]); exit;
}


/* ══════════════════════════════════════════════════════════════════════════════
   COMMISSION SPLIT SAVE — POST ?action=save_split
   Saves l1_pct / l2_pct / l3_pct for a country to product_commission_splits
══════════════════════════════════════════════════════════════════════════════ */
if (isset($_GET['action']) && $_GET['action'] === 'save_split') {
    header('Content-Type: application/json');
    if (!isset($_SESSION['admin_id'])) { echo json_encode(['error'=>'Unauthorized']); exit; }
    $cid  = intval($_POST['country_id'] ?? 0);
    $l1   = max(0, min(100, floatval($_POST['l1_pct'] ?? 60)));
    $l2   = max(0, min(100, floatval($_POST['l2_pct'] ?? 30)));
    $l3   = max(0, min(100, floatval($_POST['l3_pct'] ?? 10)));
    if (!$cid) { echo json_encode(['error'=>'No country selected']); exit; }
    $s = $conn->prepare("
        INSERT INTO product_commission_splits (country_id, l1_pct, l2_pct, l3_pct)
        VALUES (?,?,?,?)
        ON DUPLICATE KEY UPDATE l1_pct=?, l2_pct=?, l3_pct=?, updated_at=NOW()
    ");
    $s->bind_param("idddddd", $cid, $l1, $l2, $l3, $l1, $l2, $l3);
    if ($s->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['error' => $s->error]);
    }
    exit;
}

/* ── Load existing product ──────────────────────────────────────────────────── */
$product = [];
if ($isEdit) {
    $stmt = $conn->prepare("SELECT * FROM digital_products WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $product = $stmt->get_result()->fetch_assoc() ?? [];
    if (!$product) { header('Location: admin_products.php'); exit; }
}

/* ══════════════════════════════════════════════════════════════════════════════
   HANDLE POST (text fields + cover — product file handled via AJAX chunk upload)
══════════════════════════════════════════════════════════════════════════════ */
$errors  = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_GET['action'])) {

    $title        = trim($_POST['title']        ?? '');
    $description  = trim($_POST['description']  ?? '');
    $category     = trim($_POST['category']     ?? 'other');
    $price        = floatval($_POST['price']    ?? 0);
    $origPrice    = floatval($_POST['original_price'] ?? 0);
    $commPct      = max(0, min(100, floatval($_POST['commission_percent'] ?? 10)));
    $status       = trim($_POST['status']       ?? 'active');
    $featured     = isset($_POST['featured'])   ? 1 : 0;
    $previewText  = trim($_POST['preview_text'] ?? '');
    $maxDl        = max(1, intval($_POST['max_downloads'] ?? 10));
    $deliveryType = trim($_POST['delivery_type'] ?? 'file');
    if (!in_array($deliveryType, ['file', 'link'])) $deliveryType = 'file';
    $deliveryLink = trim($_POST['delivery_link'] ?? '');

    if ($title === '') $errors[] = 'Product title is required.';
    if ($price <= 0)   $errors[] = 'Price must be greater than 0.';

    $validCats   = ['ebook','source_code','template','software','course','other'];
    $validStatus = ['active','inactive','draft'];
    if (!in_array($category, $validCats))   $errors[] = 'Invalid category.';
    if (!in_array($status,   $validStatus)) $status   = 'active';

    if ($deliveryType === 'link') {
        if (empty($deliveryLink))                                               $errors[] = 'A delivery link is required.';
        elseif (!filter_var($deliveryLink, FILTER_VALIDATE_URL))                $errors[] = 'Please enter a valid URL.';
    }

    // ── Product file — from AJAX chunk upload (stored in hidden fields) ──
    $filePath = $product['file_path'] ?? '';
    $fileName = $product['file_name'] ?? '';
    $fileSize = intval($product['file_size'] ?? 0);
    $fileType = $product['file_type'] ?? '';

    if ($deliveryType === 'file') {
        // If AJAX upload completed, hidden fields will be set
        $ajaxFilePath = trim($_POST['ajax_file_path'] ?? '');
        $ajaxFileName = trim($_POST['ajax_file_name'] ?? '');
        $ajaxFileSize = intval($_POST['ajax_file_size'] ?? 0);
        $ajaxFileType = trim($_POST['ajax_file_type'] ?? '');

        if (!empty($ajaxFilePath)) {
            // Verify the file actually exists on disk
            if (file_exists($uploadDir . $ajaxFilePath)) {
                // Delete old file if replacing
                if ($isEdit && !empty($product['file_path']) && $product['file_path'] !== $ajaxFilePath) {
                    $old = $uploadDir . basename($product['file_path']);
                    if (file_exists($old)) @unlink($old);
                }
                $filePath = $ajaxFilePath;
                $fileName = $ajaxFileName ?: $ajaxFilePath;
                $fileSize = $ajaxFileSize;
                $fileType = $ajaxFileType;
            } else {
                $errors[] = 'Uploaded file not found on server. Please re-upload.';
            }
        } elseif (!$isEdit && empty($filePath)) {
            $errors[] = 'A product file is required for new file-delivery products.';
        }
        $deliveryLink = '';
    } else {
        $filePath = $product['file_path'] ?? '';
        $fileName = $product['file_name'] ?? '';
        $fileSize = intval($product['file_size'] ?? 0);
        $fileType = $product['file_type'] ?? '';
    }

    // ── Cover image ──
    $coverPath   = $product['cover_image'] ?? '';
    $removeCover = (($_POST['remove_cover'] ?? '0') === '1');
    $hasNewCover = isset($_FILES['cover_image'])
                && $_FILES['cover_image']['error'] !== UPLOAD_ERR_NO_FILE
                && $_FILES['cover_image']['error'] !== 4;

    if ($removeCover && !$hasNewCover) {
        if ($coverPath !== '') {
            $old = $rootDir . '/' . ltrim($coverPath, '/');
            if (file_exists($old)) @unlink($old);
        }
        $coverPath = '';
    } elseif ($hasNewCover) {
        $coverErr = $_FILES['cover_image']['error'];
        if ($coverErr !== UPLOAD_ERR_OK) {
            $errors[] = 'Cover image upload error (code ' . $coverErr . ').';
        } elseif ($_FILES['cover_image']['size'] > 5 * 1024 * 1024) {
            $errors[] = 'Cover image must be under 5 MB.';
        } else {
            $finfo  = finfo_open(FILEINFO_MIME_TYPE);
            $cMime  = finfo_file($finfo, $_FILES['cover_image']['tmp_name']);
            finfo_close($finfo);
            $allowedMimes = ['image/jpeg','image/jpg','image/png','image/webp','image/gif'];
            if (!in_array($cMime, $allowedMimes)) {
                $errors[] = 'Cover must be JPG, PNG, WebP or GIF.';
            } else {
                $cExt  = strtolower(pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION));
                $cName = 'cover_' . time() . '_' . mt_rand(100,999) . '.' . $cExt;
                $cDest = $coverDir . $cName;
                if (move_uploaded_file($_FILES['cover_image']['tmp_name'], $cDest)) {
                    if ($coverPath !== '') {
                        $old = $rootDir . '/' . ltrim($coverPath, '/');
                        if (file_exists($old)) @unlink($old);
                    }
                    $coverPath = 'uploads/covers/' . $cName;
                } else {
                    $errors[] = 'Could not save cover — check folder permissions.';
                }
            }
        }
    }

    /* ── Save to DB ── */
    if (empty($errors)) {
        $op      = ($origPrice > 0 && $origPrice > $price) ? $origPrice : null;
        $adminId = intval($_SESSION['admin_id']);

        if ($isEdit) {
            $sql = "UPDATE digital_products SET
                        title=?,description=?,category=?,price=?,original_price=?,
                        commission_percent=?,delivery_type=?,delivery_link=?,
                        file_path=?,file_name=?,file_size=?,file_type=?,
                        cover_image=?,preview_text=?,status=?,featured=?,max_downloads=?,
                        updated_at=NOW()
                    WHERE id=?";
            $s = $conn->prepare($sql);
            $s->bind_param("sssddssssssssssiii",
                $title,$description,$category,$price,$op,
                $commPct,$deliveryType,$deliveryLink,
                $filePath,$fileName,$fileSize,$fileType,
                $coverPath,$previewText,$status,$featured,$maxDl,$editId);
            if ($s->execute()) {
                $success = 'Product updated successfully!';
                $r2 = $conn->prepare("SELECT * FROM digital_products WHERE id=? LIMIT 1");
                $r2->bind_param("i",$editId); $r2->execute();
                $product = $r2->get_result()->fetch_assoc();
            } else { $errors[] = 'Database error: '.$s->error; }
        } else {
            $sql = "INSERT INTO digital_products
                        (title,description,category,price,original_price,
                         commission_percent,delivery_type,delivery_link,
                         file_path,file_name,file_size,file_type,
                         cover_image,preview_text,status,featured,max_downloads,
                         created_by,created_at)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())";
            $s = $conn->prepare($sql);
            $s->bind_param("sssddssssssssssiii",
                $title,$description,$category,$price,$op,
                $commPct,$deliveryType,$deliveryLink,
                $filePath,$fileName,$fileSize,$fileType,
                $coverPath,$previewText,$status,$featured,$maxDl,$adminId);
            if ($s->execute()) {
                if (function_exists('setFlash')) setFlash('success','Product published! ID #'.$conn->insert_id);
                header('Location: admin_products.php?msg=saved'); exit;
            } else { $errors[] = 'Database error: '.$s->error; }
        }
    }
}

function fmtSzPf($b) {
    if (!$b) return '—';
    if ($b < 1024)    return $b.'B';
    if ($b < 1048576) return round($b/1024,1).'KB';
    return round($b/1048576,1).'MB';
}

$catEmojis = ['ebook'=>'📖','source_code'=>'💻','template'=>'🎨','software'=>'⚙️','course'=>'🎓','other'=>'📦'];
$catLabels = ['ebook'=>'eBook','source_code'=>'Source Code','template'=>'Template','software'=>'Software','course'=>'Course','other'=>'Other'];
$hasCover  = !empty($product['cover_image']) && file_exists($rootDir.'/'.ltrim($product['cover_image'],'/'));
$curDeliveryType = $product['delivery_type'] ?? 'file';
if ($_SERVER['REQUEST_METHOD'] === 'POST') $curDeliveryType = $_POST['delivery_type'] ?? 'file';
$v = function($key,$default='') use ($product) {
    if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST[$key])) return htmlspecialchars($_POST[$key]);
    return htmlspecialchars($product[$key] ?? $default);
};

/* ── Load commission split config per country (L1%/L2%/L3% of total pool) ── */
// Uses product_commission_splits table: stores what % of the product's
// commission_percent pool goes to each level for each country.
// e.g. country sets L1=60%, L2=30%, L3=10% of pool
// If product price=1000 & commission_percent=10% → pool=100 → L1=60, L2=30, L3=10
$conn->query("
    CREATE TABLE IF NOT EXISTS product_commission_splits (
        id         INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        country_id INT NOT NULL,
        l1_pct     DECIMAL(5,2) NOT NULL DEFAULT 60.00 COMMENT '% of pool to L1',
        l2_pct     DECIMAL(5,2) NOT NULL DEFAULT 30.00 COMMENT '% of pool to L2, 0=disabled',
        l3_pct     DECIMAL(5,2) NOT NULL DEFAULT 10.00 COMMENT '% of pool to L3, 0=disabled',
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_country (country_id),
        INDEX idx_country_id (country_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

// Seed defaults for countries not yet configured
$conn->query("
    INSERT IGNORE INTO product_commission_splits (country_id, l1_pct, l2_pct, l3_pct)
    SELECT id, 60, 30, 10 FROM countries
");

// Load splits per country for JS preview
$splitRows = $conn->query("
    SELECT c.id, c.name, c.currency_symbol,
           COALESCE(s.l1_pct, 60) AS l1_pct,
           COALESCE(s.l2_pct, 30) AS l2_pct,
           COALESCE(s.l3_pct, 10) AS l3_pct
    FROM countries c
    LEFT JOIN product_commission_splits s ON s.country_id = c.id
    ORDER BY c.name ASC
")->fetch_all(MYSQLI_ASSOC);

$splitsJson = json_encode($splitRows, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT);

include 'side.php';
?>
<style>
.pf-wrap{--acc:<?php echo $themeColor;?>;--rgb:<?php echo $rgbColor;?>;--radius:12px;max-width:1020px;padding-bottom:40px}
.pf-hdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:26px;gap:14px;flex-wrap:wrap}
.pf-hdr-l{display:flex;align-items:center;gap:14px}
.pf-hdr-ico{width:50px;height:50px;border-radius:13px;flex-shrink:0;background:linear-gradient(135deg,var(--acc),#8b5cf6);display:flex;align-items:center;justify-content:center;box-shadow:0 6px 20px rgba(var(--rgb),.35)}
.pf-hdr-ico i{font-size:21px;color:#fff}
.pf-hdr-title{font-size:21px;font-weight:900;color:var(--text-primary,#f1f5f9);letter-spacing:-.4px}
.pf-hdr-sub{font-size:12px;color:var(--text-secondary,#94a3b8);margin-top:3px}
.pf-back{display:inline-flex;align-items:center;gap:7px;height:40px;padding:0 16px;border-radius:9px;background:var(--card-bg,#1a2035);border:1.5px solid var(--border-color,rgba(255,255,255,.1));color:var(--text-secondary,#94a3b8);font-size:12.5px;font-weight:600;text-decoration:none;transition:.2s;white-space:nowrap}
.pf-back:hover{border-color:var(--acc);color:var(--text-primary,#f1f5f9)}
.pf-alert{display:flex;align-items:flex-start;gap:12px;padding:14px 18px;border-radius:11px;margin-bottom:20px;font-size:13px;font-weight:500;border:1.5px solid}
.pf-alert i{margin-top:1px;flex-shrink:0;font-size:16px}
.pf-alert ul{margin:6px 0 0 16px}
.pf-alert li{font-size:12.5px;margin-bottom:3px}
.pf-alert.ok{background:rgba(16,185,129,.08);border-color:#10b981;color:#10b981}
.pf-alert.err{background:rgba(239,68,68,.08);border-color:#ef4444;color:#ef4444}
.pf-cols{display:grid;grid-template-columns:1fr 310px;gap:20px;align-items:start}
@media(max-width:900px){.pf-cols{grid-template-columns:1fr}}
.pfc{background:var(--card-bg,#1a2035);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:var(--radius);overflow:hidden;margin-bottom:18px}
.pfc-hdr{display:flex;align-items:center;gap:11px;padding:14px 18px;background:var(--darker-bg,#0e1525);border-bottom:1.5px solid var(--border-color,rgba(255,255,255,.1))}
html[data-theme=light] .pfc-hdr{background:#f0f2f5}
.pfc-ico{width:34px;height:34px;border-radius:8px;flex-shrink:0;display:flex;align-items:center;justify-content:center}
.pfc-ico i{font-size:14px;color:#fff}
.pfc-title{font-size:13.5px;font-weight:800;color:var(--text-primary,#f1f5f9)}
.pfc-sub{font-size:11px;color:var(--text-secondary,#94a3b8);margin-top:2px}
.pfc-body{padding:20px 18px}
.fg{margin-bottom:16px}
.fl{display:block;font-size:11.5px;font-weight:700;letter-spacing:.3px;text-transform:uppercase;color:var(--text-secondary,#94a3b8);margin-bottom:6px}
.req{color:#ef4444;margin-left:2px}
.hint{font-size:11.5px;color:var(--text-secondary,#64748b);margin-top:5px;display:block;line-height:1.5}
.fi-wrap{position:relative}
.fi,.fa,.fs{width:100%;background:var(--dark-bg,#07090f);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:9px;color:var(--text-primary,#f1f5f9);font-family:'Inter',sans-serif;font-size:13.5px;transition:.2s;outline:none}
html[data-theme=light] .fi,html[data-theme=light] .fa,html[data-theme=light] .fs{background:#f8fafc;color:#0f172a;border-color:#e2e8f0}
.fi{height:44px;padding:0 14px}
.fa{padding:12px 14px;resize:vertical;min-height:100px;line-height:1.6}
.fs{height:44px;padding:0 14px;appearance:none;cursor:pointer}
.fi:focus,.fa:focus,.fs:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(var(--rgb),.12)}
.fi::placeholder,.fa::placeholder{color:var(--text-secondary,#64748b);opacity:.6}
.fi-count{position:absolute;right:11px;top:50%;transform:translateY(-50%);font-size:10px;font-weight:700;color:var(--text-secondary,#64748b);background:var(--darker-bg,#0e1525);padding:1px 5px;border-radius:4px;pointer-events:none}
html[data-theme=light] .fi-count{background:#f0f2f5}
.fs-wrap{position:relative}
.fs-wrap::after{content:'\f078';font-family:'Font Awesome 6 Free';font-weight:900;position:absolute;right:13px;top:50%;transform:translateY(-50%);font-size:10px;color:var(--text-secondary,#64748b);pointer-events:none}
.g2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
@media(max-width:560px){.g2{grid-template-columns:1fr}}
.pfx-wrap{position:relative}
.pfx{position:absolute;left:0;top:0;bottom:0;width:42px;display:flex;align-items:center;justify-content:center;font-size:11.5px;font-weight:800;color:var(--text-secondary,#94a3b8);border-right:1.5px solid var(--border-color,rgba(255,255,255,.1));pointer-events:none}
.pfx-wrap .fi{padding-left:52px}
.tog-row{display:flex;align-items:center;justify-content:space-between;padding:13px 0;border-bottom:1.5px solid var(--border-color,rgba(255,255,255,.1))}
.tog-row:last-child{border-bottom:none}
.tog-l{flex:1}
.tog-name{font-size:13px;font-weight:700;color:var(--text-primary,#f1f5f9)}
.tog-desc{font-size:11.5px;color:var(--text-secondary,#94a3b8);margin-top:2px}
.tog{position:relative;width:42px;height:23px;flex-shrink:0;cursor:pointer}
.tog input{opacity:0;width:0;height:0}
.tog-sl{position:absolute;inset:0;border-radius:12px;background:var(--border-color,rgba(255,255,255,.2));transition:.3s}
.tog-sl::before{content:'';position:absolute;width:17px;height:17px;border-radius:9px;background:#fff;left:3px;top:3px;transition:.3s}
.tog input:checked+.tog-sl{background:var(--acc)}
.tog input:checked+.tog-sl::before{transform:translateX(19px)}
.status-tabs{display:flex;gap:8px;flex-wrap:wrap}
.stab input{display:none}
.stab-lbl{display:flex;align-items:center;gap:7px;padding:9px 14px;border-radius:9px;border:1.5px solid var(--border-color,rgba(255,255,255,.1));cursor:pointer;transition:.2s;font-size:12.5px;font-weight:600;color:var(--text-secondary,#94a3b8);background:var(--dark-bg,#07090f);user-select:none}
html[data-theme=light] .stab-lbl{background:#f8fafc}
.stab input:checked+.stab-lbl{border-color:var(--acc);color:var(--acc);background:rgba(var(--rgb),.1)}
.stab-live input:checked+.stab-lbl{border-color:#10b981;color:#10b981;background:rgba(16,185,129,.1)}
.stab-draft input:checked+.stab-lbl{border-color:#f59e0b;color:#f59e0b;background:rgba(245,158,11,.1)}
.stab-off input:checked+.stab-lbl{border-color:#ef4444;color:#ef4444;background:rgba(239,68,68,.1)}
.comm-box{display:none;margin-top:14px;padding:14px;background:rgba(16,185,129,.06);border:1.5px solid rgba(16,185,129,.2);border-radius:10px}
.comm-box-t{font-size:10.5px;font-weight:800;color:#10b981;text-transform:uppercase;letter-spacing:.7px;display:flex;align-items:center;gap:6px;margin-bottom:10px}
.comm-row{display:flex;justify-content:space-between;padding:7px 0;border-bottom:1px solid rgba(16,185,129,.1);font-size:12px}
.comm-row:last-child{border-bottom:none}
.comm-lbl{color:var(--text-secondary,#94a3b8)}
.comm-val{font-weight:700;color:var(--text-primary,#f1f5f9)}
.comm-val.green{color:#10b981}
.comm-val.acc{color:var(--acc)}
.disc-box{display:none;margin-top:10px;padding:10px 13px;background:rgba(245,158,11,.06);border:1.5px solid rgba(245,158,11,.2);border-radius:9px;font-size:12px;color:var(--text-secondary,#94a3b8)}
.disc-box b{color:#f59e0b}

/* DELIVERY TABS */
.del-tabs{display:flex;gap:8px;margin-bottom:18px}
.del-tab input{display:none}
.del-tab-lbl{display:flex;align-items:center;gap:8px;padding:11px 20px;border-radius:10px;border:1.5px solid var(--border-color,rgba(255,255,255,.1));cursor:pointer;transition:.2s;font-size:13px;font-weight:700;color:var(--text-secondary,#94a3b8);background:var(--dark-bg,#07090f);user-select:none;flex:1;justify-content:center}
html[data-theme=light] .del-tab-lbl{background:#f8fafc}
.del-tab input:checked+.del-tab-lbl{border-color:var(--acc);color:var(--acc);background:rgba(var(--rgb),.1)}
.del-tab-lbl i{font-size:15px}

/* LINK SECTION */
.link-input-wrap{position:relative}
.link-input-ico{position:absolute;left:13px;top:50%;transform:translateY(-50%);font-size:14px;color:var(--text-secondary,#64748b);pointer-events:none;z-index:1}
.link-input-wrap .fi{padding-left:40px}
.link-preview{display:none;align-items:center;gap:8px;margin-top:10px;padding:10px 13px;border-radius:9px;background:rgba(16,185,129,.08);border:1.5px solid rgba(16,185,129,.25);font-size:12px;font-weight:700;color:#10b981}
.link-preview.show{display:flex}
.link-warn{display:flex;align-items:flex-start;gap:9px;margin-top:10px;padding:11px 13px;border-radius:9px;background:rgba(245,158,11,.07);border:1.5px solid rgba(245,158,11,.25);font-size:12px;color:#d97706;line-height:1.6}
.link-warn i{margin-top:2px;flex-shrink:0}
.link-examples{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px}
.link-ex-pill{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:20px;font-size:10.5px;font-weight:700;cursor:pointer;border:1.5px solid var(--border-color,rgba(255,255,255,.1));color:var(--text-secondary,#94a3b8);background:var(--dark-bg,#07090f);transition:.15px;user-select:none}
html[data-theme=light] .link-ex-pill{background:#f8fafc}
.link-ex-pill:hover{border-color:var(--acc);color:var(--acc)}

/* FILE INFO BANNER */
.file-info-banner{display:flex;align-items:center;gap:13px;padding:13px 15px;background:rgba(var(--rgb),.07);border:1.5px solid rgba(var(--rgb),.22);border-radius:10px;margin-bottom:14px}
.file-info-banner .fib-icon{font-size:22px;color:var(--acc);flex-shrink:0}
.fib-body{flex:1;min-width:0}
.fib-name{font-size:13px;font-weight:700;color:var(--text-primary,#f1f5f9);word-break:break-all;margin-bottom:3px}
.fib-meta{font-size:11px;color:var(--text-secondary,#94a3b8)}
.fib-tag{display:inline-block;padding:2px 7px;border-radius:4px;font-size:10px;font-weight:700;background:rgba(16,185,129,.12);color:#10b981;margin-left:6px}

/* DROP ZONE */
.drop-zone{border:2px dashed var(--border-color,rgba(255,255,255,.2));border-radius:11px;padding:26px 18px;text-align:center;transition:.25s;position:relative;background:var(--darker-bg,#0e1525);cursor:pointer}
html[data-theme=light] .drop-zone{background:#f8fafc}
.drop-zone:hover{border-color:var(--acc);background:rgba(var(--rgb),.05)}
.drop-zone.drag{border-color:var(--acc);background:rgba(var(--rgb),.08)}
.drop-zone.filled{border-style:solid;border-color:#10b981;background:rgba(16,185,129,.05)}
.drop-zone input[type=file]{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer;z-index:2}
.drop-emoji{font-size:32px;display:block;margin-bottom:8px;pointer-events:none}
.drop-title{font-size:13px;font-weight:800;color:var(--text-primary,#f1f5f9);margin-bottom:4px;pointer-events:none}
.drop-sub{font-size:11.5px;color:var(--text-secondary,#94a3b8);line-height:1.5;pointer-events:none}
.drop-sub b{color:var(--acc)}
.drop-selected{display:none;align-items:center;gap:10px;margin-top:12px;padding:10px 13px;border-radius:9px;background:rgba(16,185,129,.1);border:1.5px solid rgba(16,185,129,.3);pointer-events:none}
.drop-selected.show{display:flex}
.drop-selected i{color:#10b981;font-size:16px;flex-shrink:0}
.drop-sel-name{font-size:12px;font-weight:700;color:var(--text-primary,#f1f5f9);word-break:break-all}
.drop-sel-size{font-size:11px;color:var(--text-secondary,#94a3b8);margin-top:2px}

/* ══ UPLOAD PROGRESS ══ */
.up-progress{
  display:none;margin-top:14px;
  padding:14px 16px;border-radius:11px;
  background:var(--darker-bg,#0e1525);
  border:1.5px solid var(--border-color,rgba(255,255,255,.1));
}
html[data-theme=light] .up-progress{background:#f4f6fb}
.up-progress.show{display:block}
.up-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;gap:8px;flex-wrap:wrap}
.up-filename{font-size:12px;font-weight:700;color:var(--text-primary,#f1f5f9);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:55%}
.up-pct{font-size:13px;font-weight:900;color:var(--acc)}
/* track */
.up-track{height:8px;border-radius:4px;background:var(--border-color,rgba(255,255,255,.1));overflow:hidden;margin-bottom:9px}
.up-bar{height:100%;width:0%;border-radius:4px;background:linear-gradient(90deg,var(--acc),#10b981);transition:width .25s ease;position:relative}
/* shimmer on bar */
.up-bar::after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,transparent 20%,rgba(255,255,255,.25) 50%,transparent 80%);background-size:200% 100%;animation:upShimmer 1.4s linear infinite}
@keyframes upShimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
/* stats row */
.up-stats{display:flex;gap:14px;font-size:11px;font-weight:600;color:var(--text-secondary,#94a3b8);flex-wrap:wrap}
.up-stat{display:flex;align-items:center;gap:4px}
.up-stat i{font-size:10px;color:var(--acc)}
/* done / error states */
.up-done{display:none;align-items:center;gap:9px;padding:10px 13px;border-radius:9px;background:rgba(16,185,129,.1);border:1.5px solid rgba(16,185,129,.3);font-size:12.5px;font-weight:700;color:#10b981;margin-top:10px}
.up-done.show{display:flex}
.up-done i{font-size:16px}
.up-err{display:none;align-items:center;gap:9px;padding:10px 13px;border-radius:9px;background:rgba(239,68,68,.08);border:1.5px solid rgba(239,68,68,.25);font-size:12.5px;font-weight:700;color:#ef4444;margin-top:10px}
.up-err.show{display:flex}
/* chunk counter */
.up-chunks{font-size:10px;color:var(--text-secondary,#64748b);font-family:'JetBrains Mono',monospace;margin-top:5px}

/* COVER */
.cover-box{aspect-ratio:16/9;border:2px dashed var(--border-color,rgba(255,255,255,.2));border-radius:11px;overflow:hidden;position:relative;background:var(--darker-bg,#0e1525);transition:.25s;display:flex;align-items:center;justify-content:center;cursor:pointer}
html[data-theme=light] .cover-box{background:#f8fafc}
.cover-box:hover{border-color:var(--acc)}
.cover-box.has-img{border-style:solid;border-color:rgba(var(--rgb),.3)}
.cover-box input[type=file]{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer;z-index:3}
#coverPreview{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:1;display:none}
.cover-ph{text-align:center;z-index:2;pointer-events:none;padding:16px}
.cover-ph i{font-size:32px;color:var(--text-secondary,#64748b);display:block;margin-bottom:8px}
.cover-ph-t{font-size:12.5px;font-weight:800;color:var(--text-primary,#f1f5f9)}
.cover-ph-s{font-size:11px;color:var(--text-secondary,#94a3b8);margin-top:4px;line-height:1.5}
.cover-ov{position:absolute;inset:0;background:rgba(0,0,0,.55);display:none;align-items:center;justify-content:center;flex-direction:column;gap:6px;z-index:2;pointer-events:none;font-size:12px;font-weight:800;color:#fff}
.cover-ov i{font-size:20px}
.cover-box.has-img:hover .cover-ov{display:flex}
.btn-rm-cover{display:none;align-items:center;gap:5px;margin-top:8px;padding:5px 12px;border-radius:7px;cursor:pointer;user-select:none;font-size:11.5px;font-weight:700;color:#ef4444;border:1.5px solid rgba(239,68,68,.25);background:rgba(239,68,68,.07);transition:.2s}
.btn-rm-cover:hover{background:rgba(239,68,68,.14)}
.btn-rm-cover.show{display:inline-flex}

/* SIDEBAR CARDS */
.sb-card{background:var(--card-bg,#1a2035);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:13px;overflow:hidden;margin-bottom:16px}
.sb-card-hdr{padding:12px 16px;background:var(--darker-bg,#0e1525);border-bottom:1.5px solid var(--border-color,rgba(255,255,255,.1));font-size:10.5px;font-weight:800;color:var(--text-secondary,#64748b);text-transform:uppercase;letter-spacing:.9px;display:flex;align-items:center;gap:7px}
html[data-theme=light] .sb-card-hdr{background:#f0f2f5}
.sb-card-hdr i{color:var(--acc);font-size:12px}
.sb-card-body{padding:16px}
.prev-cover{aspect-ratio:16/9;border-radius:9px;overflow:hidden;background:linear-gradient(135deg,rgba(var(--rgb),.3),rgba(139,92,246,.3));display:flex;align-items:center;justify-content:center;margin-bottom:12px;position:relative;font-size:46px}
.prev-cover img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.prev-cat{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;margin-bottom:7px;border-radius:20px;background:rgba(var(--rgb),.12);color:var(--acc);font-size:10px;font-weight:800}
.prev-title{font-size:13.5px;font-weight:900;color:var(--text-primary,#f1f5f9);line-height:1.35;margin-bottom:8px;min-height:18px}
.prev-price-row{display:flex;align-items:baseline;gap:7px}
.prev-price{font-size:20px;font-weight:900;color:var(--acc)}
.prev-orig{font-size:12px;color:var(--text-secondary,#94a3b8);text-decoration:line-through}
.prev-comm{display:none;margin-top:10px;padding:8px 11px;border-radius:7px;background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.2);font-size:11px;color:#10b981;font-weight:700}
.prev-hot{display:none;margin-top:8px;padding:7px 12px;border-radius:7px;background:linear-gradient(90deg,#f97316,#ef4444);font-size:11.5px;font-weight:900;color:#fff;text-align:center}
.prev-delivery-badge{display:inline-flex;align-items:center;gap:5px;margin-top:8px;padding:5px 10px;border-radius:6px;font-size:11px;font-weight:700}
.prev-delivery-badge.file{background:rgba(59,130,246,.1);color:#3b82f6;border:1px solid rgba(59,130,246,.2)}
.prev-delivery-badge.link{background:rgba(16,185,129,.1);color:#10b981;border:1px solid rgba(16,185,129,.2)}
.tip-item{display:flex;gap:11px;align-items:flex-start;padding:9px 0;border-bottom:1.5px solid var(--border-color,rgba(255,255,255,.07))}
.tip-item:last-child{border-bottom:none}
.tip-ico{width:30px;height:30px;border-radius:7px;display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:12px}
.tip-txt{font-size:11.5px;color:var(--text-secondary,#94a3b8);line-height:1.6;padding-top:6px}
.tip-txt b{color:var(--text-primary,#f1f5f9)}

/* COMMISSION SPLIT INLINE */
.spl-card{background:var(--card-bg,#1a2035);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:var(--radius);overflow:hidden;margin-bottom:18px}
.spl-hdr{display:flex;align-items:center;gap:11px;padding:14px 18px;background:var(--darker-bg,#0e1525);border-bottom:1.5px solid var(--border-color,rgba(255,255,255,.1))}
html[data-theme=light] .spl-hdr{background:#f0f2f5}
.spl-ico{width:34px;height:34px;border-radius:8px;background:linear-gradient(135deg,#10b981,#059669);display:flex;align-items:center;justify-content:center;flex-shrink:0}
.spl-ico i{font-size:14px;color:#fff}
.spl-title{font-size:13.5px;font-weight:800;color:var(--text-primary,#f1f5f9)}
.spl-sub{font-size:11px;color:var(--text-secondary,#94a3b8);margin-top:2px}
.spl-body{padding:18px}
.spl-info{background:rgba(16,185,129,.07);border:1.5px solid rgba(16,185,129,.2);border-radius:9px;padding:12px 14px;margin-bottom:16px;font-size:12px;color:var(--text-secondary,#94a3b8);line-height:1.7}
.spl-info strong{color:#10b981}
/* country selector */
.spl-csel-wrap{position:relative;margin-bottom:14px}
.spl-csel-wrap::after{content:'\f078';font-family:'Font Awesome 6 Free';font-weight:900;position:absolute;right:12px;top:50%;transform:translateY(-50%);font-size:10px;color:var(--text-secondary,#64748b);pointer-events:none}
.spl-csel{width:100%;height:42px;padding:0 32px 0 12px;background:var(--dark-bg,#07090f);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:9px;color:var(--text-primary,#f1f5f9);font-size:13px;outline:none;appearance:none;transition:.2s;cursor:pointer;box-sizing:border-box}
html[data-theme=light] .spl-csel{background:#f8fafc;color:#0f172a;border-color:#e2e8f0}
.spl-csel:focus{border-color:var(--acc)}
/* level rows */
.spl-rows{display:flex;flex-direction:column;gap:9px;margin-bottom:14px}
.spl-row{display:flex;align-items:center;gap:10px;padding:11px 13px;background:var(--darker-bg,#0e1525);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:9px;transition:.2s}
html[data-theme=light] .spl-row{background:#f4f6fb}
.spl-row.active{border-color:rgba(var(--rgb),.35)}
.spl-row.disabled{opacity:.5}
.spl-badge{width:28px;height:28px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:900;flex-shrink:0}
.spl-badge.l1{background:rgba(var(--rgb),.15);color:var(--acc)}
.spl-badge.l2{background:rgba(16,185,129,.15);color:#10b981}
.spl-badge.l3{background:rgba(245,158,11,.15);color:#f59e0b}
.spl-lbl{flex:1;font-size:12px;font-weight:700;color:var(--text-primary,#f1f5f9)}
.spl-lbl small{display:block;font-size:10px;font-weight:400;color:var(--text-secondary,#94a3b8);margin-top:1px}
.spl-pct-wrap{position:relative;width:90px;flex-shrink:0}
.spl-sfx{position:absolute;right:10px;top:50%;transform:translateY(-50%);font-size:11px;font-weight:800;color:var(--text-secondary,#94a3b8);pointer-events:none}
.spl-inp{width:100%;height:34px;padding:0 26px 0 10px;background:var(--dark-bg,#07090f);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:7px;color:var(--text-primary,#f1f5f9);font-size:13px;font-weight:700;outline:none;transition:.2s;box-sizing:border-box;text-align:right}
html[data-theme=light] .spl-inp{background:#fff;color:#0f172a;border-color:#e2e8f0}
.spl-inp:focus{border-color:var(--acc)}
.spl-ksh{width:90px;flex-shrink:0;font-size:12px;font-weight:700;color:#10b981;text-align:right}
.spl-ksh.zero{color:var(--text-secondary,#64748b)}
.spl-ksh.off{color:#ef4444;font-size:10px}
/* total check */
.spl-total{display:flex;align-items:center;justify-content:space-between;padding:9px 13px;border-radius:8px;font-size:12px;font-weight:700;margin-bottom:14px}
.spl-total.ok{background:rgba(16,185,129,.08);border:1.5px solid rgba(16,185,129,.25);color:#10b981}
.spl-total.warn{background:rgba(245,158,11,.08);border:1.5px solid rgba(245,158,11,.25);color:#f59e0b}
.spl-total.err{background:rgba(239,68,68,.08);border:1.5px solid rgba(239,68,68,.25);color:#ef4444}
/* save */
.spl-footer{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.btn-spl-save{height:36px;padding:0 18px;background:linear-gradient(135deg,var(--acc),#10b981);color:#fff;border:none;border-radius:8px;font-size:12.5px;font-weight:800;cursor:pointer;display:inline-flex;align-items:center;gap:6px;transition:.18s}
.btn-spl-save:hover{opacity:.9;transform:translateY(-1px)}
.spl-note{font-size:11px;color:var(--text-secondary,#64748b)}

.submit-bar{background:var(--card-bg,#1a2035);border:1.5px solid var(--border-color,rgba(255,255,255,.1));border-radius:13px;padding:16px 20px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:4px}
.btn-pub{height:46px;padding:0 26px;background:linear-gradient(135deg,#10b981,#059669);color:#fff;border:none;border-radius:10px;font-size:13.5px;font-weight:800;cursor:pointer;font-family:'Inter',sans-serif;display:inline-flex;align-items:center;gap:7px;transition:.2s;box-shadow:0 4px 16px rgba(16,185,129,.38)}
.btn-pub:hover{opacity:.9;transform:translateY(-1px)}
.btn-pub:disabled{opacity:.5;cursor:not-allowed;transform:none}
.btn-upd{height:46px;padding:0 26px;background:linear-gradient(135deg,var(--acc),#8b5cf6);color:#fff;border:none;border-radius:10px;font-size:13.5px;font-weight:800;cursor:pointer;font-family:'Inter',sans-serif;display:inline-flex;align-items:center;gap:7px;transition:.2s;box-shadow:0 4px 16px rgba(var(--rgb),.35)}
.btn-upd:hover{opacity:.9;transform:translateY(-1px)}
.btn-upd:disabled{opacity:.5;cursor:not-allowed;transform:none}
.btn-draft-save{height:46px;padding:0 20px;background:transparent;border:1.5px solid var(--border-color,rgba(255,255,255,.2));color:var(--text-secondary,#94a3b8);border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;font-family:'Inter',sans-serif;display:inline-flex;align-items:center;gap:7px;transition:.2s}
.btn-draft-save:hover{color:var(--text-primary,#f1f5f9);border-color:var(--text-secondary)}
.submit-note{font-size:11.5px;color:var(--text-secondary,#64748b);margin-left:auto;display:flex;align-items:center;gap:5px}
@media(max-width:520px){.submit-note{display:none}}
</style>

<div class="pf-wrap">

<div class="pf-hdr">
  <div class="pf-hdr-l">
    <div class="pf-hdr-ico"><i class="fas fa-<?php echo $isEdit?'pen-to-square':'circle-plus';?>"></i></div>
    <div>
      <div class="pf-hdr-title"><?php echo $isEdit?'Edit Product':'Add New Product';?></div>
      <div class="pf-hdr-sub"><?php echo $isEdit?'Update details, replace the file, cover image or delivery link':'Upload a file or provide an external link — publish immediately or save as draft';?></div>
    </div>
  </div>
  <a href="admin_products.php" class="pf-back"><i class="fas fa-arrow-left"></i> All Products</a>
</div>

<?php if ($success): ?>
<div class="pf-alert ok"><i class="fas fa-circle-check"></i><span><?php echo htmlspecialchars($success);?></span></div>
<?php endif; ?>
<?php if (!empty($errors)): ?>
<div class="pf-alert err">
  <i class="fas fa-circle-exclamation"></i>
  <div><strong>Please fix the following:</strong>
    <ul><?php foreach($errors as $e):?><li><?php echo htmlspecialchars($e);?></li><?php endforeach;?></ul>
  </div>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data" id="pfForm">
  <input type="hidden" name="remove_cover" id="removeCoverFlag" value="0">
  <!-- Hidden fields populated by AJAX chunk upload — MUST be inside <form> -->
  <input type="hidden" id="ajaxFilePath" name="ajax_file_path" value="">
  <input type="hidden" id="ajaxFileName" name="ajax_file_name" value="">
  <input type="hidden" id="ajaxFileSize" name="ajax_file_size" value="">
  <input type="hidden" id="ajaxFileType" name="ajax_file_type" value="">

<div class="pf-cols">
<div>

  <!-- PRODUCT INFO -->
  <div class="pfc">
    <div class="pfc-hdr">
      <div class="pfc-ico" style="background:linear-gradient(135deg,#6366f1,#8b5cf6)"><i class="fas fa-pen-nib"></i></div>
      <div><div class="pfc-title">Product Information</div><div class="pfc-sub">Name, category and description</div></div>
    </div>
    <div class="pfc-body">
      <div class="fg">
        <label class="fl">Title <span class="req">*</span></label>
        <div class="fi-wrap">
          <input type="text" name="title" id="titleInp" class="fi" maxlength="120" required
            placeholder="e.g. Complete PHP MLM System with M-Pesa Integration"
            value="<?php echo $v('title');?>"
            oninput="syncPrev();document.getElementById('tc').textContent=this.value.length">
          <span class="fi-count" id="tc"><?php echo strlen($product['title']??'');?></span>
        </div>
      </div>
      <div class="g2">
        <div class="fg">
          <label class="fl">Category <span class="req">*</span></label>
          <div class="fs-wrap">
            <select name="category" id="catInp" class="fs" onchange="syncPrev()">
              <?php foreach($catLabels as $k=>$lbl): $sel=($v('category','ebook')===$k)?'selected':'';?>
              <option value="<?php echo $k;?>" <?php echo $sel;?>><?php echo $catEmojis[$k].'  '.$lbl;?></option>
              <?php endforeach;?>
            </select>
          </div>
        </div>
        <div class="fg">
          <label class="fl">Max Downloads / Accesses <span class="req">*</span></label>
          <input type="number" name="max_downloads" class="fi" min="1" max="999"
            value="<?php echo $v('max_downloads','10');?>" required>
          <span class="hint">Limits re-downloads or link re-accesses per buyer.</span>
        </div>
      </div>
      <div class="fg">
        <label class="fl">Description</label>
        <textarea name="description" class="fa" rows="4"
          placeholder="What problem does this solve? Who is it for?"><?php echo $v('description');?></textarea>
      </div>
      <div class="fg" style="margin-bottom:0">
        <label class="fl">What's Included</label>
        <textarea name="preview_text" class="fa" rows="3"
          placeholder="• Full source code&#10;• Admin panel&#10;• M-Pesa integration"><?php echo $v('preview_text');?></textarea>
      </div>
    </div>
  </div>

  <!-- PRICING -->
  <div class="pfc">
    <div class="pfc-hdr">
      <div class="pfc-ico" style="background:linear-gradient(135deg,#f59e0b,#f97316)"><i class="fas fa-tag"></i></div>
      <div><div class="pfc-title">Pricing & Commission</div><div class="pfc-sub">Set price and affiliate commission split</div></div>
    </div>
    <div class="pfc-body">
      <div class="g2">
        <div class="fg">
          <label class="fl">Sale Price (KSh) <span class="req">*</span></label>
          <div class="pfx-wrap"><span class="pfx">KSh</span>
            <input type="number" name="price" id="priceInp" class="fi" min="1" step="1" required
              value="<?php echo $v('price');?>" oninput="syncPrev();updateComm();updateDisc()">
          </div>
        </div>
        <div class="fg">
          <label class="fl">Original Price <span style="text-transform:none;font-size:10.5px;font-weight:400">(optional)</span></label>
          <div class="pfx-wrap"><span class="pfx">KSh</span>
            <input type="number" name="original_price" id="origInp" class="fi" min="0" step="1"
              placeholder="0 = no discount" value="<?php echo $v('original_price');?>"
              oninput="syncPrev();updateDisc()">
          </div>
        </div>
      </div>
      <div class="disc-box" id="discBox">Showing <b id="discPct">0</b>% off</div>
      <div class="fg" style="margin-bottom:0">
        <label class="fl">Commission % <span class="req">*</span></label>
        <div class="pfx-wrap"><span class="pfx">%</span>
          <input type="number" name="commission_percent" id="commInp" class="fi" min="0" max="100" step="0.5"
            value="<?php echo $v('commission_percent','10');?>" oninput="updateComm()">
        </div>
        <span class="hint">This % determines the total commission pool paid out across levels. Exact per-level amounts are set in the <strong>Commission Levels</strong> card below.</span>
        <div class="comm-box" id="commBox">
          <div class="comm-box-t"><i class="fas fa-coins"></i> Commission Preview</div>
          <div class="comm-row"><span class="comm-lbl">Sale Price</span><span class="comm-val" id="cpPrice">—</span></div>
          <div class="comm-row"><span class="comm-lbl">Total Pool (<span id="cpPct">0</span>%)</span><span class="comm-val green" id="cpPool">—</span></div>
          <div id="cpLevelsWrap">
            <div class="comm-row" id="cpL1Row"><span class="comm-lbl">L1 · Direct upline</span><span class="comm-val acc" id="cpL1">—</span></div>
            <div class="comm-row" id="cpL2Row" style="display:none"><span class="comm-lbl">L2 upline</span><span class="comm-val" id="cpL2">—</span></div>
            <div class="comm-row" id="cpL3Row" style="display:none"><span class="comm-lbl">L3 upline</span><span class="comm-val" id="cpL3">—</span></div>
          </div>
          <div class="comm-row" style="display:none" id="cpNoCountry">
            <span class="comm-lbl" style="color:#f59e0b;font-size:11px"><i class="fas fa-triangle-exclamation"></i> Select a country in the Commission Levels card below to see exact amounts</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- COMMISSION SPLIT PER COUNTRY -->
  <div class="spl-card">
    <div class="spl-hdr">
      <div class="spl-ico"><i class="fas fa-coins"></i></div>
      <div>
        <div class="spl-title">Commission Split by Country</div>
        <div class="spl-sub">How the commission % above is split across L1 / L2 / L3. Set 0% to disable that level.</div>
      </div>
    </div>
    <div class="spl-body">
      <div class="spl-info">
        <strong>How it works:</strong> Each product has its own <strong>commission %</strong> above (e.g. 10%).
        The split below controls what fraction of that pool each upline level earns.<br>
        Example: Price KSh 1,000 · 10% = <strong>KSh 100 pool</strong> · L1 60% = <strong>KSh 60</strong> · L2 30% = <strong>KSh 30</strong> · L3 0% = <strong>disabled</strong>
      </div>

      <!-- Country picker -->
      <div class="spl-csel-wrap">
        <select id="splCountry" class="spl-csel" onchange="splLoad(this.value)">
          <option value="">— Select country to preview / configure —</option>
          <?php foreach($splitRows as $sr): ?>
          <option value="<?php echo $sr['id'];?>"
                  data-l1="<?php echo floatval($sr['l1_pct']);?>"
                  data-l2="<?php echo floatval($sr['l2_pct']);?>"
                  data-l3="<?php echo floatval($sr['l3_pct']);?>"
                  data-sym="<?php echo htmlspecialchars($sr['currency_symbol']?:'KSh');?>"
                  data-name="<?php echo htmlspecialchars($sr['name']);?>">
            <?php echo htmlspecialchars($sr['name']);?>
            (L1:<?php echo floatval($sr['l1_pct']);?>% / L2:<?php echo floatval($sr['l2_pct']);?>% / L3:<?php echo floatval($sr['l3_pct']);?>%)
          </option>
          <?php endforeach;?>
        </select>
      </div>

      <!-- Level rows -->
      <div class="spl-rows" id="splRows">
        <?php foreach([1=>['Direct upline','l1'],2=>['L2 upline','l2'],3=>['L3 upline','l3']] as $lvl=>[$lbl,$key]): ?>
        <div class="spl-row disabled" id="splRow<?php echo $lvl;?>">
          <div class="spl-badge l<?php echo $lvl;?>">L<?php echo $lvl;?></div>
          <div class="spl-lbl"><?php echo $lbl;?><small>0% = level disabled</small></div>
          <div class="spl-pct-wrap">
            <input type="number" class="spl-inp" id="splL<?php echo $lvl;?>" min="0" max="100" step="1" value="0"
                   oninput="splOnInput()">
            <span class="spl-sfx">%</span>
          </div>
          <div class="spl-ksh zero" id="splKsh<?php echo $lvl;?>">— KSh</div>
        </div>
        <?php endforeach;?>
      </div>

      <!-- Total check -->
      <div class="spl-total ok" id="splTotal">
        <span id="splTotalTxt">Select a country to configure</span>
        <span id="splTotalSum"></span>
      </div>

      <!-- Save -->
      <div class="spl-footer">
        <button type="button" class="btn-spl-save" id="splSaveBtn" onclick="splSave()" disabled>
          <i class="fas fa-floppy-disk"></i> Save Split for this Country
        </button>
        <span class="spl-note"><i class="fas fa-circle-info"></i> Each country can have different splits. Changes apply to future purchases.</span>
      </div>
    </div>
  </div>

  <!-- DELIVERY -->
  <div class="pfc">
    <div class="pfc-hdr">
      <div class="pfc-ico" style="background:linear-gradient(135deg,#3b82f6,#06b6d4)"><i class="fas fa-truck-fast"></i></div>
      <div><div class="pfc-title">Delivery Method</div><div class="pfc-sub">Upload a file OR use an external link</div></div>
    </div>
    <div class="pfc-body">
      <div class="del-tabs">
        <label class="del-tab">
          <input type="radio" name="delivery_type" value="file"
            <?php echo $curDeliveryType!=='link'?'checked':'';?> onchange="switchDelivery('file')">
          <span class="del-tab-lbl"><i class="fas fa-file-zipper"></i> File Upload</span>
        </label>
        <label class="del-tab">
          <input type="radio" name="delivery_type" value="link"
            <?php echo $curDeliveryType==='link'?'checked':'';?> onchange="switchDelivery('link')">
          <span class="del-tab-lbl"><i class="fas fa-link"></i> External Link</span>
        </label>
      </div>

      <!-- FILE SECTION -->
      <div id="secFile">
        <?php if($isEdit&&!empty($product['file_path'])&&$curDeliveryType!=='link'):?>
        <div class="file-info-banner" id="currFileBanner">
          <i class="fas fa-file-circle-check fib-icon"></i>
          <div class="fib-body">
            <div class="fib-name"><?php echo htmlspecialchars($product['file_name']?:$product['file_path']);?><span class="fib-tag">current file</span></div>
            <div class="fib-meta"><?php echo fmtSzPf($product['file_size']);?> · <?php echo htmlspecialchars($product['file_type']?:'—');?></div>
          </div>
        </div>
        <?php endif;?>

        <div class="drop-zone" id="dropZone"
             ondragover="event.preventDefault();this.classList.add('drag')"
             ondragleave="this.classList.remove('drag')"
             ondrop="handleFileDrop(event)">
          <input type="file" id="productFileInput"
                 accept=".pdf,.zip,.rar,.tar,.gz,.epub,.docx,.doc,.txt,.mp4,.mp3,.exe,.apk"
                 onchange="onFileSelected(this)">
          <span class="drop-emoji" id="dropEmoji">📦</span>
          <div class="drop-title" id="dropTitle"><?php echo $isEdit?'Drop new file here to replace':'Drag & drop your product file here';?></div>
          <div class="drop-sub">or <b>click to browse</b><br>PDF, ZIP, RAR, EPUB, DOCX, MP4, MP3, EXE, APK — max <b>100 MB</b></div>
          <div class="drop-selected" id="dropSelected">
            <i class="fas fa-circle-check"></i>
            <div>
              <div class="drop-sel-name" id="dropSelName">—</div>
              <div class="drop-sel-size" id="dropSelSize">—</div>
            </div>
          </div>
        </div>

        <!-- ══ UPLOAD PROGRESS PANEL ══ -->
        <div class="up-progress" id="upProgress">
          <div class="up-top">
            <div class="up-filename" id="upFilename">—</div>
            <div class="up-pct" id="upPct">0%</div>
          </div>
          <div class="up-track"><div class="up-bar" id="upBar"></div></div>
          <div class="up-stats">
            <div class="up-stat"><i class="fas fa-gauge-high"></i><span id="upSpeed">—</span></div>
            <div class="up-stat"><i class="fas fa-clock"></i><span id="upEta">—</span></div>
            <div class="up-stat"><i class="fas fa-database"></i><span id="upUploaded">—</span></div>
          </div>
          <div class="up-chunks" id="upChunks"></div>
          <div class="up-done" id="upDone"><i class="fas fa-circle-check"></i><span id="upDoneMsg">Upload complete!</span></div>
          <div class="up-err"  id="upErr" ><i class="fas fa-circle-xmark"></i><span id="upErrMsg">Upload failed.</span></div>
        </div>

      </div><!-- /secFile -->

      <!-- LINK SECTION -->
      <div id="secLink" style="display:none">
        <div class="fg">
          <label class="fl">Delivery URL <span class="req">*</span></label>
          <div class="link-input-wrap">
            <span class="link-input-ico"><i class="fas fa-link"></i></span>
            <input type="url" name="delivery_link" id="deliveryLinkInp" class="fi"
                   placeholder="https://chat.whatsapp.com/... or https://drive.google.com/..."
                   value="<?php echo htmlspecialchars($product['delivery_link']??'');?>"
                   oninput="detectLinkType(this.value)">
          </div>
          <div class="link-preview" id="linkPreview"><i class="fas fa-circle-check"></i><span id="linkPreviewTxt"></span></div>
          <div class="link-examples">
            <span class="link-ex-pill" onclick="setLinkPH('whatsapp')"><i class="fab fa-whatsapp" style="color:#25d366"></i> WhatsApp</span>
            <span class="link-ex-pill" onclick="setLinkPH('gdrive')"><i class="fab fa-google-drive" style="color:#4285f4"></i> Google Drive</span>
            <span class="link-ex-pill" onclick="setLinkPH('telegram')"><i class="fab fa-telegram" style="color:#26a5e4"></i> Telegram</span>
            <span class="link-ex-pill" onclick="setLinkPH('dropbox')"><i class="fab fa-dropbox" style="color:#0061ff"></i> Dropbox</span>
          </div>
          <span class="hint">Paste any invite or share link. Buyers are redirected here after payment.</span>
        </div>
        <div class="link-warn"><i class="fas fa-triangle-exclamation"></i><div>Make sure your link is set to <strong>"anyone with the link can access"</strong>.</div></div>
      </div>
    </div>
  </div>

  <!-- STATUS -->
  <div class="pfc">
    <div class="pfc-hdr">
      <div class="pfc-ico" style="background:linear-gradient(135deg,#10b981,#059669)"><i class="fas fa-rocket"></i></div>
      <div><div class="pfc-title">Status & Visibility</div><div class="pfc-sub">Control when this product appears in the store</div></div>
    </div>
    <div class="pfc-body">
      <div class="fg">
        <label class="fl">Product Status <span class="req">*</span></label>
        <div class="status-tabs">
          <?php
          $curStatus=$product['status']??($_POST['status']??'active');
          $stabs=['active'=>['fa-circle-check','Live','stab-live'],'draft'=>['fa-pen-ruler','Draft','stab-draft'],'inactive'=>['fa-circle-xmark','Inactive','stab-off']];
          foreach($stabs as $sv=>[$ico,$lbl,$cls]):?>
          <label class="stab <?php echo $cls;?>">
            <input type="radio" name="status" value="<?php echo $sv;?>" <?php echo $curStatus===$sv?'checked':'';?>>
            <span class="stab-lbl"><i class="fas <?php echo $ico;?>"></i> <?php echo $lbl;?></span>
          </label>
          <?php endforeach;?>
        </div>
        <span class="hint">Use <strong>Draft</strong> while preparing, <strong>Live</strong> to publish immediately.</span>
      </div>
      <div style="border-top:1.5px solid var(--border-color,rgba(255,255,255,.1));padding-top:14px">
        <div class="tog-row">
          <div class="tog-l">
            <div class="tog-name">🔥 Featured Product</div>
            <div class="tog-desc">Adds a "Hot" badge and pins to top of store</div>
          </div>
          <label class="tog"><input type="checkbox" name="featured" id="featInp" onchange="syncPrev()" <?php echo !empty($product['featured'])?'checked':'';?>><span class="tog-sl"></span></label>
        </div>
      </div>
    </div>
  </div>

  <!-- SUBMIT -->
  <div class="submit-bar">
    <?php if($isEdit):?>
      <button type="submit" class="btn-upd" id="submitBtn"><i class="fas fa-floppy-disk"></i> Save Changes</button>
    <?php else:?>
      <button type="submit" class="btn-pub" id="submitBtn" onclick="setStatus('active')"><i class="fas fa-rocket"></i> Publish Live</button>
      <button type="button" class="btn-draft-save" onclick="setStatus('draft');document.getElementById('pfForm').submit()"><i class="fas fa-pen-ruler"></i> Save as Draft</button>
    <?php endif;?>
    <span class="submit-note"><i class="fas fa-lock" style="color:#10b981"></i> Files stored outside web root</span>
  </div>

</div><!-- /left -->

<!-- RIGHT -->
<div>
  <div class="sb-card">
    <div class="sb-card-hdr"><i class="fas fa-eye"></i> Live Store Preview</div>
    <div class="sb-card-body">
      <div class="prev-cover" id="prevCover">
        <?php if($hasCover):?><img src="../<?php echo htmlspecialchars($product['cover_image']);?>" id="prevImg" alt="" style="display:block"><span id="prevEmoji" style="display:none">📦</span>
        <?php else:?><span id="prevEmoji">📦</span><img src="" id="prevImg" alt="" style="display:none"><?php endif;?>
      </div>
      <div class="prev-cat" id="prevCat">📦 Other</div>
      <div class="prev-title" id="prevTitle">Product title will appear here…</div>
      <div class="prev-price-row">
        <span class="prev-price" id="prevPrice">KSh 0</span>
        <span class="prev-orig" id="prevOrig" style="display:none"></span>
      </div>
      <div class="prev-comm" id="prevComm"></div>
      <div id="prevDeliveryBadge" class="prev-delivery-badge file"><i class="fas fa-file-zipper"></i> <span id="prevDeliveryTxt">File Download</span></div>
      <div class="prev-hot" id="prevHot"></div>
    </div>
  </div>

  <div class="sb-card">
    <div class="sb-card-hdr"><i class="fas fa-image"></i> Cover Image</div>
    <div class="sb-card-body">
      <div class="cover-box <?php echo $hasCover?'has-img':'';?>" id="coverBox">
        <input type="file" name="cover_image" id="coverInput" accept="image/jpeg,image/jpg,image/png,image/webp,image/gif" onchange="onCoverSelected(this)">
        <img id="coverPreview" src="<?php echo $hasCover?'../'.htmlspecialchars($product['cover_image']):'';?>" alt="" style="display:<?php echo $hasCover?'block':'none';?>">
        <div class="cover-ov" id="coverOv"><i class="fas fa-camera"></i> Change Cover</div>
        <div class="cover-ph" id="coverPh" style="display:<?php echo $hasCover?'none':'block';?>">
          <i class="fas fa-image"></i>
          <div class="cover-ph-t">Upload Cover Image</div>
          <div class="cover-ph-s">16:9 · JPG, PNG, WebP<br>Max 5 MB</div>
        </div>
      </div>
      <div class="btn-rm-cover <?php echo $hasCover?'show':'';?>" id="removeCoverBtn" onclick="removeCover()"><i class="fas fa-trash"></i> Remove Cover</div>
      <span class="hint" style="margin-top:8px;display:block">Optional but strongly recommended.</span>
    </div>
  </div>

  <div class="sb-card">
    <div class="sb-card-hdr"><i class="fas fa-lightbulb"></i> Tips</div>
    <div class="sb-card-body" style="padding:12px 16px">
      <div class="tip-item"><div class="tip-ico" style="background:rgba(16,185,129,.15)"><i class="fas fa-bolt" style="color:#10b981"></i></div><div class="tip-txt"><b>Chunked upload</b> — large files upload in 2 MB pieces with a live progress bar, speed meter and ETA.</div></div>
      <div class="tip-item"><div class="tip-ico" style="background:rgba(99,102,241,.15)"><i class="fas fa-image" style="color:#6366f1"></i></div><div class="tip-txt"><b>Cover image</b> increases click-throughs by up to 3×. Use 16:9, min 800px wide.</div></div>
      <div class="tip-item"><div class="tip-ico" style="background:rgba(245,158,11,.15)"><i class="fas fa-percent" style="color:#f59e0b"></i></div><div class="tip-txt"><b>Commission 10–20%</b> is the sweet spot to motivate affiliates.</div></div>
      <div class="tip-item"><div class="tip-ico" style="background:rgba(239,68,68,.15)"><i class="fas fa-lock" style="color:#ef4444"></i></div><div class="tip-txt"><b>Files are locked</b> outside the web root — only served after payment.</div></div>
    </div>
  </div>
</div>

</div><!-- /pf-cols -->
</form>
</div><!-- /pf-wrap -->

<script>
/* ─── category data ─── */
var CAT_EMOJI={ebook:'📖',source_code:'💻',template:'🎨',software:'⚙️',course:'🎓',other:'📦'};
var CAT_LABEL={ebook:'eBook',source_code:'Source Code',template:'Template',software:'Software',course:'Course',other:'Other'};

/* ─── live preview ─── */
function syncPrev(){
    var title=document.getElementById('titleInp').value.trim();
    var cat=document.getElementById('catInp').value;
    var price=parseFloat(document.getElementById('priceInp').value)||0;
    var orig=parseFloat(document.getElementById('origInp').value)||0;
    var pct=parseFloat(document.getElementById('commInp').value)||0;
    var feat=document.getElementById('featInp').checked;
    var delType=document.querySelector('input[name="delivery_type"]:checked')?.value||'file';

    document.getElementById('prevTitle').textContent=title||'Product title will appear here…';
    document.getElementById('prevCat').textContent=(CAT_EMOJI[cat]||'📦')+' '+(CAT_LABEL[cat]||cat);
    document.getElementById('prevEmoji').textContent=CAT_EMOJI[cat]||'📦';
    document.getElementById('prevPrice').textContent='KSh '+price.toLocaleString();

    var po=document.getElementById('prevOrig');
    po.style.display=(orig>price&&orig>0)?'inline':'none';
    po.textContent='KSh '+orig.toLocaleString();

    var pc=document.getElementById('prevComm');
    if(price>0&&pct>0){
        var pool=price*pct/100;
        pc.style.display='block';
        if(splCountry){
            var l1pct=parseFloat(document.getElementById('splL1').value)||0;
            var l1ksh=(pool*l1pct/100);
            var sym=splCountry.currency_symbol||'KSh';
            pc.textContent = l1ksh>0
                ? '💰 L1 earns '+sym+' '+l1ksh.toLocaleString(undefined,{maximumFractionDigits:2})+' · Pool '+sym+' '+pool.toFixed(2)
                : '💰 Commission pool: KSh '+pool.toFixed(2)+' (select country for split)';
        } else {
            pc.textContent='💰 Commission pool: KSh '+pool.toFixed(2)+' — select country below for split';
        }
    } else { pc.style.display='none'; }

    var ph=document.getElementById('prevHot');
    ph.style.display=feat?'block':'none'; ph.textContent=feat?'🔥 Featured':'';
    var badge=document.getElementById('prevDeliveryBadge');
    var badgeTxt=document.getElementById('prevDeliveryTxt');
    if(delType==='link'){badge.className='prev-delivery-badge link';badge.querySelector('i').className='fas fa-link';badgeTxt.textContent='External Link';}
    else{badge.className='prev-delivery-badge file';badge.querySelector('i').className='fas fa-file-zipper';badgeTxt.textContent='File Download';}
}

function updateComm(){
    var price=parseFloat(document.getElementById('priceInp').value)||0;
    var pct=parseFloat(document.getElementById('commInp').value)||0;
    var box=document.getElementById('commBox');

    if(price<=0||pct<=0){ box.style.display='none'; syncPrev(); return; }

    var pool=price*pct/100;
    box.style.display='block';
    document.getElementById('cpPrice').textContent='KSh '+price.toLocaleString();
    document.getElementById('cpPool').textContent='KSh '+pool.toFixed(2);
    document.getElementById('cpPct').textContent=pct;

    var noCountry=document.getElementById('cpNoCountry');
    var levelsWrap=document.getElementById('cpLevelsWrap');

    if(splCountry){
        noCountry.style.display='none';
        levelsWrap.style.display='block';
        var sym=splCountry.currency_symbol||'KSh';

        var lvls=[
            {id:'cpL1',rowId:'cpL1Row',pctEl:'splL1',lbl:'L1 · Direct upline'},
            {id:'cpL2',rowId:'cpL2Row',pctEl:'splL2',lbl:'L2 upline'},
            {id:'cpL3',rowId:'cpL3Row',pctEl:'splL3',lbl:'L3 upline'},
        ];

        lvls.forEach(function(lv){
            var row=document.getElementById(lv.rowId);
            var cell=document.getElementById(lv.id);
            var lvPct=parseFloat(document.getElementById(lv.pctEl).value)||0;
            var ksh=pool*lvPct/100;
            // Also update the KSh column in the split card
            var kshEl=document.getElementById('spl'+lv.pctEl.replace('spl','').toUpperCase().replace('SPL','')+'sh') || null;

            if(lvPct>0){
                row.style.display='flex';
                // update row label to show %
                row.querySelector('.comm-lbl').textContent=lv.lbl+' ('+lvPct+'%)';
                cell.textContent=sym+' '+ksh.toFixed(2);
                cell.style.color='';
            } else {
                row.style.display='flex';
                row.querySelector('.comm-lbl').textContent=lv.lbl+' (0% — disabled)';
                cell.textContent='—';
                cell.style.color='#64748b';
            }
        });

        // Update KSh amounts in the split card rows
        [1,2,3].forEach(function(l){
            var lvPct=parseFloat(document.getElementById('splL'+l).value)||0;
            var ksh=pool*lvPct/100;
            var kshEl=document.getElementById('splKsh'+l);
            if(kshEl){
                if(lvPct<=0){ kshEl.textContent='disabled'; kshEl.className='spl-ksh off'; }
                else { kshEl.textContent=sym+' '+ksh.toFixed(2); kshEl.className='spl-ksh'; }
                var row=document.getElementById('splRow'+l);
                if(row){ row.classList.toggle('active',lvPct>0); }
            }
        });

    } else {
        levelsWrap.style.display='none';
        noCountry.style.display='flex';
        // Reset KSh amounts in split card
        [1,2,3].forEach(function(l){
            var el=document.getElementById('splKsh'+l);
            if(el){ el.textContent='— KSh'; el.className='spl-ksh zero'; }
        });
    }
    syncPrev();
}
function updateDisc(){
    var price=parseFloat(document.getElementById('priceInp').value)||0;
    var orig=parseFloat(document.getElementById('origInp').value)||0;
    var db=document.getElementById('discBox');
    if(orig>price&&orig>0&&price>0){db.style.display='block';document.getElementById('discPct').textContent=Math.round((1-price/orig)*100);}else db.style.display='none';
}
function setStatus(s){document.querySelectorAll('input[name="status"]').forEach(function(r){r.checked=r.value===s;});}
function switchDelivery(type){
    document.getElementById('secFile').style.display=type==='link'?'none':'block';
    document.getElementById('secLink').style.display=type==='link'?'block':'none';
    syncPrev();
}

/* ─── link helpers ─── */
var LINK_TYPES=[
    {p:/chat\.whatsapp\.com/i,label:'🟢 WhatsApp Group Link detected'},
    {p:/drive\.google\.com/i, label:'🔵 Google Drive Link detected'},
    {p:/t\.me\//i,            label:'🔵 Telegram Link detected'},
    {p:/dropbox\.com/i,       label:'🔵 Dropbox Link detected'},
    {p:/mega\.nz/i,           label:'🔴 MEGA Link detected'},
    {p:/^https:\/\//i,        label:'✅ Secure HTTPS link'},
    {p:/^http:\/\//i,         label:'⚠️ Non-secure HTTP link'},
];
function detectLinkType(url){
    var prev=document.getElementById('linkPreview'),txt=document.getElementById('linkPreviewTxt');
    if(!url){prev.classList.remove('show');return;}
    for(var i=0;i<LINK_TYPES.length;i++){if(LINK_TYPES[i].p.test(url)){txt.textContent=LINK_TYPES[i].label;prev.classList.add('show');return;}}
    prev.classList.remove('show');
}
var LINK_PH={whatsapp:'https://chat.whatsapp.com/XXXXXXXXXXXXXXXXXXXXXXX',gdrive:'https://drive.google.com/drive/folders/XXXXXX?usp=sharing',telegram:'https://t.me/yourchannel',dropbox:'https://www.dropbox.com/sh/XXXXXX?dl=0'};
function setLinkPH(t){var inp=document.getElementById('deliveryLinkInp');inp.placeholder=LINK_PH[t]||'';inp.focus();}

/* ══════════════════════════════════════════════════
   CHUNKED UPLOAD ENGINE
   Splits file into 2 MB chunks, uploads sequentially,
   shows real-time progress, speed and ETA
══════════════════════════════════════════════════ */
var CHUNK_SIZE = 2 * 1024 * 1024; // 2 MB
var uploadState = null;

function fmtBytes(b){if(b<1024)return b+'B';if(b<1048576)return(b/1024).toFixed(1)+'KB';return(b/1048576).toFixed(1)+'MB';}
function fmtSpeed(bps){if(bps<1024)return bps.toFixed(0)+'B/s';if(bps<1048576)return(bps/1024).toFixed(1)+'KB/s';return(bps/1048576).toFixed(1)+'MB/s';}
function fmtEta(s){if(s<60)return Math.ceil(s)+'s';if(s<3600)return Math.floor(s/60)+'m '+Math.ceil(s%60)+'s';return Math.floor(s/3600)+'h '+Math.floor((s%3600)/60)+'m';}
function genUploadId(){return 'up_'+Date.now()+'_'+Math.random().toString(36).slice(2,9);}

function showProgress(filename){
    var p=document.getElementById('upProgress');
    p.classList.add('show');
    document.getElementById('upFilename').textContent=filename;
    document.getElementById('upPct').textContent='0%';
    document.getElementById('upBar').style.width='0%';
    document.getElementById('upSpeed').textContent='—';
    document.getElementById('upEta').textContent='—';
    document.getElementById('upUploaded').textContent='—';
    document.getElementById('upChunks').textContent='';
    document.getElementById('upDone').classList.remove('show');
    document.getElementById('upErr').classList.remove('show');
}
function updateProgress(uploaded, total, bps, chunkIdx, totalChunks){
    var pct=Math.round(uploaded/total*100);
    document.getElementById('upBar').style.width=pct+'%';
    document.getElementById('upPct').textContent=pct+'%';
    document.getElementById('upSpeed').textContent=fmtSpeed(bps);
    var remaining=(total-uploaded)/Math.max(bps,1);
    document.getElementById('upEta').textContent=bps>0?fmtEta(remaining):'—';
    document.getElementById('upUploaded').textContent=fmtBytes(uploaded)+' / '+fmtBytes(total);
    document.getElementById('upChunks').textContent='Chunk '+(chunkIdx+1)+' of '+totalChunks;
}
function finishProgress(filename, fileSize){
    document.getElementById('upBar').style.width='100%';
    document.getElementById('upPct').textContent='100%';
    document.getElementById('upChunks').textContent='All chunks received — assembling file…';
    document.getElementById('upDone').classList.add('show');
    document.getElementById('upDoneMsg').textContent='✅ '+filename+' ('+fmtBytes(fileSize)+') uploaded successfully!';
    document.getElementById('upSpeed').textContent='Done';
    document.getElementById('upEta').textContent='—';
}
function errorProgress(msg){
    document.getElementById('upErr').classList.add('show');
    document.getElementById('upErrMsg').textContent=msg;
    document.getElementById('upBar').style.width='0%';
    document.getElementById('upPct').textContent='0%';
    document.getElementById('upChunks').textContent='';
    // Re-enable submit
    setSubmitEnabled(true);
}

function setSubmitEnabled(enabled){
    var btn=document.getElementById('submitBtn');
    if(!btn)return;
    btn.disabled=!enabled;
}

function uploadChunks(file){
    var totalChunks=Math.ceil(file.size/CHUNK_SIZE);
    var uploadId=genUploadId();
    var startTime=Date.now();
    var bytesUploaded=0;
    var chunkIdx=0;

    showProgress(file.name);
    setSubmitEnabled(false);

    function sendChunk(idx){
        var start=idx*CHUNK_SIZE;
        var end=Math.min(start+CHUNK_SIZE, file.size);
        var chunk=file.slice(start,end);

        var fd=new FormData();
        fd.append('chunk',       chunk, file.name);
        fd.append('chunk_index', idx);
        fd.append('total_chunks',totalChunks);
        fd.append('upload_id',   uploadId);
        fd.append('file_name',   file.name);

        var xhr=new XMLHttpRequest();
        var chunkStart=Date.now();

        xhr.upload.onprogress=function(e){
            if(!e.lengthComputable)return;
            var soFar=idx*CHUNK_SIZE+e.loaded;
            var elapsed=(Date.now()-startTime)/1000;
            var bps=soFar/Math.max(elapsed,0.1);
            updateProgress(soFar,file.size,bps,idx,totalChunks);
        };

        xhr.onload=function(){
            if(xhr.status!==200){errorProgress('Server error '+xhr.status+' on chunk '+idx);return;}
            var res;
            try{res=JSON.parse(xhr.responseText);}catch(e){errorProgress('Invalid server response');return;}
            if(res.error){errorProgress(res.error);return;}

            bytesUploaded=Math.min((idx+1)*CHUNK_SIZE, file.size);
            var elapsed=(Date.now()-startTime)/1000;
            var bps=bytesUploaded/Math.max(elapsed,0.1);
            updateProgress(bytesUploaded,file.size,bps,idx,totalChunks);

            if(res.done){
                // Populate hidden fields for form submission
                document.getElementById('ajaxFilePath').value=res.file_path;
                document.getElementById('ajaxFileName').value=res.file_name;
                document.getElementById('ajaxFileSize').value=res.file_size;
                document.getElementById('ajaxFileType').value=res.file_type;
                finishProgress(file.name,res.file_size);
                setSubmitEnabled(true);
            } else {
                sendChunk(idx+1);
            }
        };

        xhr.onerror=function(){errorProgress('Network error uploading chunk '+idx+'. Please retry.');};
        xhr.open('POST','?action=chunk_upload',true);
        xhr.send(fd);
    }

    sendChunk(0);
}

/* ─── hook into file input ─── */
function onFileSelected(input){
    if(!input.files||!input.files[0])return;
    var file=input.files[0];
    // Show name in drop zone
    var zone=document.getElementById('dropZone');
    zone.classList.add('filled');zone.classList.remove('drag');
    document.getElementById('dropEmoji').textContent='⬆️';
    document.getElementById('dropTitle').textContent='Uploading…';
    document.getElementById('dropSelName').textContent=file.name;
    document.getElementById('dropSelSize').textContent=(file.size/1048576).toFixed(2)+' MB';
    document.getElementById('dropSelected').classList.add('show');
    // Start chunked upload immediately
    uploadChunks(file);
}
function handleFileDrop(e){
    e.preventDefault();
    document.getElementById('dropZone').classList.remove('drag');
    var files=e.dataTransfer?e.dataTransfer.files:null;
    if(!files||!files[0])return;
    // Inject into file input for visual consistency
    try{var dt=new DataTransfer();dt.items.add(files[0]);document.getElementById('productFileInput').files=dt.files;}catch(err){}
    onFileSelected({files:files});
}

/* ─── cover ─── */
function onCoverSelected(input){
    if(!input.files||!input.files[0])return;
    var reader=new FileReader();
    reader.onload=function(e){setCoverPreview(e.target.result);document.getElementById('removeCoverFlag').value='0';};
    reader.readAsDataURL(input.files[0]);
}
function setCoverPreview(src){
    var box=document.getElementById('coverBox'),img=document.getElementById('coverPreview'),ph=document.getElementById('coverPh'),btn=document.getElementById('removeCoverBtn');
    img.src=src;img.style.display='block';box.classList.add('has-img');
    if(ph)ph.style.display='none';if(btn)btn.classList.add('show');
    var pImg=document.getElementById('prevImg'),pEmo=document.getElementById('prevEmoji');
    pImg.src=src;pImg.style.display='block';if(pEmo)pEmo.style.display='none';
}
function removeCover(){
    if(!confirm('Remove cover image? It will be deleted when you save.'))return;
    var box=document.getElementById('coverBox'),img=document.getElementById('coverPreview'),ph=document.getElementById('coverPh'),btn=document.getElementById('removeCoverBtn');
    img.src='';img.style.display='none';box.classList.remove('has-img');
    if(ph)ph.style.display='block';if(btn)btn.classList.remove('show');
    document.getElementById('coverInput').value='';
    document.getElementById('removeCoverFlag').value='1';
    var pImg=document.getElementById('prevImg'),pEmo=document.getElementById('prevEmoji');
    if(pImg){pImg.src='';pImg.style.display='none';}if(pEmo)pEmo.style.display='';
}

/* ─── prevent form submit while uploading ─── */
document.getElementById('pfForm').addEventListener('submit',function(e){
    var delType=document.querySelector('input[name="delivery_type"]:checked')?.value||'file';
    if(delType==='file'){
        var ajaxPath=document.getElementById('ajaxFilePath').value;
        var isEdit=<?php echo $isEdit?'true':'false';?>;
        var hasExisting=<?php echo !empty($product['file_path'])?'true':'false';?>;
        // If file was chosen but upload not done yet
        var fileChosen=document.getElementById('productFileInput').files.length>0;
        if(fileChosen&&!ajaxPath){
            e.preventDefault();
            alert('Please wait for the file upload to complete before saving.');
            return;
        }
    }
});

/* ══════════════════════════════════════════════════
   COMMISSION SPLIT MANAGER
   Saves l1_pct / l2_pct / l3_pct per country to
   product_commission_splits table via AJAX.
   Preview box shows exact KSh amounts based on
   current price × commission% × level split.
══════════════════════════════════════════════════ */
var SPL_DATA  = <?php echo $splitsJson; ?>;
var splCountry = null; // currently selected country object

function splLoad(countryId) {
    splCountry = null;
    var btn = document.getElementById('splSaveBtn');
    btn.disabled = true;

    [1,2,3].forEach(function(l){
        document.getElementById('splRow'+l).classList.add('disabled');
        document.getElementById('splL'+l).value = 0;
        document.getElementById('splKsh'+l).textContent = '— KSh';
        document.getElementById('splKsh'+l).className = 'spl-ksh zero';
    });
    splUpdateTotal();
    if (!countryId) { updateComm(); return; }

    var found = SPL_DATA.find(function(d){ return parseInt(d.id)===parseInt(countryId); });
    if (!found) return;
    splCountry = found;

    [1,2,3].forEach(function(l){
        var val = parseFloat(found['l'+l+'_pct'])||0;
        document.getElementById('splL'+l).value = val;
        document.getElementById('splRow'+l).classList.remove('disabled');
    });

    btn.disabled = false;
    splOnInput();
}

function splOnInput() {
    splUpdateTotal();
    updateComm(); // live preview reacts immediately
}

function splUpdateTotal() {
    var sum = [1,2,3].reduce(function(a,l){ return a+(parseFloat(document.getElementById('splL'+l).value)||0); }, 0);
    var box = document.getElementById('splTotal');
    var txt = document.getElementById('splTotalTxt');
    var smm = document.getElementById('splTotalSum');
    smm.textContent = sum.toFixed(1) + '%';
    if (!splCountry) {
        box.className='spl-total ok'; txt.textContent='Select a country to configure'; smm.textContent='';
    } else if (sum === 100) {
        box.className='spl-total ok'; txt.textContent='✅ Total adds up correctly';
    } else if (sum < 100) {
        box.className='spl-total warn'; txt.textContent='⚠ Total is under 100% — '+( 100-sum).toFixed(1)+'% unallocated';
    } else {
        box.className='spl-total err'; txt.textContent='❌ Total exceeds 100% — reduce by '+(sum-100).toFixed(1)+'%';
    }
}

function splSave() {
    if (!splCountry) { alert('Select a country first.'); return; }
    var l1=parseFloat(document.getElementById('splL1').value)||0;
    var l2=parseFloat(document.getElementById('splL2').value)||0;
    var l3=parseFloat(document.getElementById('splL3').value)||0;
    if (l1+l2+l3 > 100) { alert('Total exceeds 100%. Please adjust.'); return; }

    var btn = document.getElementById('splSaveBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving…';

    var fd = new FormData();
    fd.append('country_id', splCountry.id);
    fd.append('l1_pct', l1);
    fd.append('l2_pct', l2);
    fd.append('l3_pct', l3);

    fetch('?action=save_split', { method: 'POST', body: fd })
        .then(function(r){ return r.json(); })
        .then(function(res) {
            btn.disabled = false;
            if (res.success) {
                // Update local cache
                SPL_DATA.forEach(function(d){
                    if (parseInt(d.id)===parseInt(splCountry.id)) { d.l1_pct=l1; d.l2_pct=l2; d.l3_pct=l3; }
                });
                // Update option label
                var opt = document.querySelector('#splCountry option[value="'+splCountry.id+'"]');
                if (opt) opt.textContent = splCountry.name+' (L1:'+l1+'% / L2:'+l2+'% / L3:'+l3+'%)';
                btn.innerHTML = '<i class="fas fa-circle-check"></i> Saved!';
                btn.style.background = 'linear-gradient(135deg,#059669,#047857)';
                setTimeout(function(){ btn.innerHTML='<i class="fas fa-floppy-disk"></i> Save Split for this Country'; btn.style.background=''; btn.disabled=false; }, 2200);
                updateComm();
            } else {
                btn.innerHTML = '<i class="fas fa-circle-xmark"></i> Error';
                btn.style.background = 'linear-gradient(135deg,#ef4444,#dc2626)';
                setTimeout(function(){ btn.innerHTML='<i class="fas fa-floppy-disk"></i> Save Split for this Country'; btn.style.background=''; btn.disabled=false; }, 2500);
                alert('Error: '+(res.error||'Unknown'));
            }
        })
        .catch(function(){ btn.disabled=false; btn.innerHTML='<i class="fas fa-floppy-disk"></i> Save Split for this Country'; alert('Network error.'); });
}

/* ─── init ─── */
(function(){
    var checked=document.querySelector('input[name="delivery_type"]:checked');
    if(checked)switchDelivery(checked.value);
    var el=document.getElementById('deliveryLinkInp');
    if(el&&el.value)detectLinkType(el.value);
    syncPrev();updateComm();updateDisc();
})();
</script>