<?php
session_start();
require_once 'db.php';
if (!isset($_SESSION['admin_id'])) { header("Location: admin_login.php"); exit; }
$admin_id = $_SESSION['admin_id'];

$success = ''; $error = '';

// ── Handle actions ──────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Update plan settings
    if ($_POST['action'] === 'update_plan') {
        $id     = (int)$_POST['plan_id'];
        $tasks  = (int)$_POST['daily_tasks'];
        $order  = (float)$_POST['per_order'];
        $earn   = (float)$_POST['daily_earnings'];
        $price  = (float)$_POST['price'];
        $dur    = (int)$_POST['duration_days'];
        $cf     = $conn->real_escape_string($_POST['color_from'] ?? '#3eaabb');
        $ct     = $conn->real_escape_string($_POST['color_to']   ?? '#92c7dd');

        // Commission rates
        $ref_l1  = (float)$_POST['ref_commission_l1'];
        $ref_l2  = (float)$_POST['ref_commission_l2'];
        $ref_l3  = (float)$_POST['ref_commission_l3'];
        $task_l1 = (float)$_POST['task_commission_l1'];
        $task_l2 = (float)$_POST['task_commission_l2'];
        $task_l3 = (float)$_POST['task_commission_l3'];

        // Badge image upload
        $badge_set = '';
        if (!empty($_FILES['badge_img']['name'])) {
            $ext = strtolower(pathinfo($_FILES['badge_img']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                $dir = 'uploads/badges/';
                if (!is_dir($dir)) mkdir($dir, 0755, true);
                $fname = uniqid('badge_').'.'.$ext;
                if (move_uploaded_file($_FILES['badge_img']['tmp_name'], $dir.$fname)) {
                    $badge_path = $conn->real_escape_string($dir.$fname);
                    $badge_set  = ",badge_img='$badge_path'";
                }
            }
        }

        $conn->query("UPDATE plans SET
            daily_tasks=$tasks,
            per_order=$order,
            daily_earnings=$earn,
            price=$price,
            duration_days=$dur,
            color_from='$cf',
            color_to='$ct',
            ref_commission_l1=$ref_l1,
            ref_commission_l2=$ref_l2,
            ref_commission_l3=$ref_l3,
            task_commission_l1=$task_l1,
            task_commission_l2=$task_l2,
            task_commission_l3=$task_l3
            $badge_set
            WHERE id=$id");
        $success = 'Plan updated successfully.';
    }

    // Upload video
    if ($_POST['action'] === 'add_video') {
        $assign_type = $_POST['assign_type'] ?? 'one';
        $pid_single  = (int)($_POST['plan_id'] ?? 0);
        $title       = $conn->real_escape_string(trim($_POST['title']));
        $earn        = (float)$_POST['earn_amount'];
        $cover = $video = '';

        if (!empty($_FILES['cover_img']['name'])) {
            $ext = strtolower(pathinfo($_FILES['cover_img']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                $dir = 'uploads/covers/'; if (!is_dir($dir)) mkdir($dir,0755,true);
                $fname = uniqid('cover_').'.'.$ext;
                if (move_uploaded_file($_FILES['cover_img']['tmp_name'], $dir.$fname)) $cover = $dir.$fname;
            }
        }
        if (!empty($_FILES['video_file']['name'])) {
            $ext = strtolower(pathinfo($_FILES['video_file']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['mp4','webm','mov','avi'])) {
                $dir = 'uploads/videos/'; if (!is_dir($dir)) mkdir($dir,0755,true);
                $fname = uniqid('video_').'.'.$ext;
                if (move_uploaded_file($_FILES['video_file']['tmp_name'], $dir.$fname)) $video = $dir.$fname;
            }
        } elseif (!empty($_POST['video_url'])) {
            $video = $conn->real_escape_string(trim($_POST['video_url']));
        }

        $cover_esc = $conn->real_escape_string($cover);
        $video_esc = $conn->real_escape_string($video);

        if (empty($title)) {
            $error = 'Video title is required.';
        } elseif ($assign_type === 'all') {
            $all_plans = $conn->query("SELECT id FROM plans WHERE active=1")->fetch_all(MYSQLI_ASSOC);
            foreach ($all_plans as $ap) {
                $apid = $ap['id'];
                $conn->query("INSERT INTO plan_videos (plan_id,title,cover_img,video_url,earn_amount) VALUES ($apid,'$title','$cover_esc','$video_esc',$earn)");
            }
            $success = 'Video added to ALL plans.';
        } elseif ($pid_single) {
            $conn->query("INSERT INTO plan_videos (plan_id,title,cover_img,video_url,earn_amount) VALUES ($pid_single,'$title','$cover_esc','$video_esc',$earn)");
            $success = 'Video added successfully.';
        } else {
            $error = 'Please select a plan or choose All Plans.';
        }
    }

    // Delete video
    if ($_POST['action'] === 'delete_video') {
        $vid = (int)$_POST['video_id'];
        $conn->query("UPDATE plan_videos SET active=0 WHERE id=$vid");
        $success = 'Video removed.';
    }
}

// Fetch data
$plans = $conn->query("SELECT * FROM plans WHERE active=1 ORDER BY sort_order ASC")->fetch_all(MYSQLI_ASSOC);
$sel_plan = isset($_GET['plan']) ? (int)$_GET['plan'] : ($plans[0]['id'] ?? 0);

$videos = [];
if ($sel_plan) {
    $videos = $conn->query("SELECT pv.*,p.name as plan_name FROM plan_videos pv JOIN plans p ON p.id=pv.plan_id WHERE pv.plan_id=$sel_plan AND pv.active=1 ORDER BY pv.id DESC")->fetch_all(MYSQLI_ASSOC);
} else {
    $videos = $conn->query("SELECT pv.*,p.name as plan_name FROM plan_videos pv JOIN plans p ON p.id=pv.plan_id WHERE pv.active=1 ORDER BY pv.id DESC LIMIT 50")->fetch_all(MYSQLI_ASSOC);
}
$sel_plan_row = $sel_plan ? $conn->query("SELECT * FROM plans WHERE id=$sel_plan")->fetch_assoc() : null;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Admin - Plans & Videos</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{--teal:#3ecf8e;--blue:#2c7be5;--dark:#0f2027;--body:#f0f4f8;--card:#fff;--border:#e2e8f0;--text:#2d3748;--muted:#718096;--r:12px}
body{font-family:'Segoe UI',sans-serif;background:var(--body);display:flex;min-height:100vh}

/* Sidebar */
.sidebar{width:220px;background:linear-gradient(180deg,#0f2027,#203a43);min-height:100vh;position:fixed;top:0;left:0;z-index:100;display:flex;flex-direction:column}
.sb-logo{padding:24px 18px 18px;border-bottom:1px solid rgba(255,255,255,.08);color:#fff;font-size:16px;font-weight:800;display:flex;align-items:center;gap:8px}
.sb-nav{padding:16px 0;flex:1}
.sb-link{display:flex;align-items:center;gap:10px;padding:11px 18px;color:rgba(255,255,255,.65);font-size:13px;text-decoration:none;border-left:3px solid transparent;transition:all .2s}
.sb-link:hover,.sb-link.active{background:rgba(255,255,255,.08);color:#fff;border-left-color:var(--teal)}
.sb-link svg{width:17px;height:17px;flex-shrink:0}

/* Main */
.main{margin-left:220px;flex:1;display:flex;flex-direction:column}
.topbar{background:#fff;border-bottom:1px solid var(--border);padding:15px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h1{font-size:19px;font-weight:700}
.content{padding:24px 28px;flex:1}

/* Alerts */
.alert{padding:10px 16px;border-radius:10px;margin-bottom:18px;font-size:13px;font-weight:500}
.alert.s{background:#e6f9f0;color:#1a7a4a;border-left:4px solid var(--teal)}
.alert.e{background:#fde8e8;color:#c0392b;border-left:4px solid #e74c3c}

/* Cards */
.card{background:var(--card);border-radius:var(--r);box-shadow:0 2px 10px rgba(0,0,0,.06);margin-bottom:22px}
.card-head{padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px}
.card-head h2{font-size:15px;font-weight:700}
.card-head svg{width:19px;height:19px;color:var(--blue)}
.card-body{padding:20px}

/* Section label inside form */
.section-label{font-size:13px;font-weight:700;color:var(--text);background:var(--body);border-radius:8px;padding:8px 12px;margin-bottom:14px;margin-top:4px;border-left:4px solid var(--blue)}

/* Form */
label{display:block;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--muted);margin-bottom:5px}
input[type=text],input[type=number],input[type=color],input[type=url],select,textarea{width:100%;height:44px;border:1.5px solid var(--border);border-radius:9px;padding:0 12px;font-size:14px;font-family:inherit;color:var(--text);outline:none;transition:border-color .2s;margin-bottom:14px;background:#fff}
textarea{height:auto;padding:10px 12px}
input[type=color]{height:44px;padding:4px 6px;cursor:pointer}
input:focus,select:focus{border-color:var(--blue)}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.form-row-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}
@media(max-width:600px){.form-row,.form-row-3{grid-template-columns:1fr}}

/* Commission box */
.commission-box{background:linear-gradient(135deg,#f0f7ff,#e8f0fe);border:1.5px solid #c3d9f8;border-radius:12px;padding:16px 18px;margin-bottom:18px}
.commission-box .cb-title{font-size:13px;font-weight:700;color:#1a4a8a;margin-bottom:12px;display:flex;align-items:center;gap:7px}
.commission-box .cb-title svg{width:16px;height:16px}
.commission-row{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px}
.commission-row .ci{background:#fff;border-radius:9px;padding:12px;text-align:center;border:1.5px solid #d0e4fa}
.commission-row .ci label{font-size:10px;font-weight:700;color:#5a8fd4;text-transform:uppercase;letter-spacing:.4px;display:block;margin-bottom:6px}
.commission-row .ci input{width:100%;text-align:center;border:1px solid #d0e4fa;border-radius:7px;padding:6px;font-size:15px;font-weight:800;color:#1a4a8a;height:auto;margin-bottom:0;background:#f7fbff}
.commission-row .ci .ci-unit{font-size:10px;color:#888;margin-top:4px}

/* Green commission box */
.commission-box.green{background:linear-gradient(135deg,#f0fff6,#e6f9f0);border-color:#a8e6c8}
.commission-box.green .cb-title{color:#0d6640}
.commission-row.green .ci{border-color:#a8e6c8}
.commission-row.green .ci label{color:#1a7a4a}
.commission-row.green .ci input{color:#0d6640;border-color:#a8e6c8;background:#f5fff9}

/* Buttons */
.btn{display:inline-flex;align-items:center;gap:7px;padding:0 20px;height:42px;border:none;border-radius:9px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;transition:opacity .15s}
.btn:hover{opacity:.9}
.btn-primary{background:linear-gradient(90deg,var(--teal),var(--blue));color:#fff;box-shadow:0 4px 14px rgba(44,123,229,.3)}
.btn-danger{background:#e74c3c;color:#fff}
.btn svg{width:15px;height:15px}

/* Plan tabs */
.plan-tabs{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:20px}
.plan-tab{padding:7px 16px;border-radius:20px;border:1.5px solid var(--border);background:#fff;font-size:13px;font-weight:600;cursor:pointer;color:var(--muted);text-decoration:none;transition:all .2s}
.plan-tab.active{background:var(--blue);border-color:var(--blue);color:#fff}

/* Video table */
table{width:100%;border-collapse:collapse;font-size:13px}
th{text-align:left;padding:9px 12px;background:var(--body);color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.5px;font-weight:700}
td{padding:11px 12px;border-bottom:1px solid var(--border);vertical-align:middle}
tr:last-child td{border-bottom:none}
.thumb{width:56px;height:42px;border-radius:7px;object-fit:cover}
.badge-plan{background:#e8f0fe;color:#1a5cbf;padding:2px 10px;border-radius:20px;font-size:11px;font-weight:600}

/* File input */
.file-label{display:flex;align-items:center;gap:10px;border:1.5px dashed var(--border);border-radius:9px;padding:12px 14px;cursor:pointer;margin-bottom:14px;color:var(--muted);font-size:13px;transition:border-color .2s}
.file-label:hover{border-color:var(--blue)}
input[type=file]{display:none}

/* Badge preview */
.badge-preview{width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid var(--border);margin-top:6px;display:block}

/* Assign toggle */
.assign-toggle{display:flex;gap:10px;margin-bottom:14px}
.assign-toggle label{text-transform:none;letter-spacing:0;font-size:13px;font-weight:600;display:flex;align-items:center;gap:5px;cursor:pointer;color:var(--text)}
.assign-toggle input[type=radio]{width:auto;height:auto;margin:0}

/* Rate info callout */
.rate-callout{background:#fff8e1;border:1px solid #ffe082;border-radius:9px;padding:10px 14px;font-size:12px;color:#7a5800;margin-bottom:16px;line-height:1.6}
</style>
</head>
<body>

<!-- Sidebar -->
<aside class="sidebar">
  <div class="sb-logo">
    <svg width="28" height="28" viewBox="0 0 100 100"><circle cx="50" cy="50" r="46" fill="#2a8cbf"/><text x="50" y="56" text-anchor="middle" font-family="sans-serif" font-weight="900" font-size="20" fill="#fff">WFM</text></svg>
    Admin Panel
  </div>
  <nav class="sb-nav">
    <a class="sb-link" href="admin_dashboard.php">
      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/></svg> Dashboard
    </a>
    <a class="sb-link active" href="admin_plans.php">
      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.38-1 1.73V7h1a7 7 0 0 1 7 7H3a7 7 0 0 1 7-7h1V5.73A2 2 0 0 1 10 4a2 2 0 0 1 2-2z"/></svg> Plans & Videos
    </a>
    <a class="sb-link" href="admin_users.php">
      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg> Users
    </a>
    <a class="sb-link" href="admin_login.php?logout=1">
      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5-5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"/></svg> Logout
    </a>
  </nav>
</aside>

<!-- Main -->
<main class="main">
  <div class="topbar">
    <h1>Plans & Videos Management</h1>
    <span style="color:var(--muted);font-size:13px"><?= date('d M Y') ?></span>
  </div>
  <div class="content">

    <?php if ($success): ?><div class="alert s"><?= htmlspecialchars($success) ?></div><?php endif; ?>
    <?php if ($error):   ?><div class="alert e"><?= htmlspecialchars($error) ?></div><?php endif; ?>

    <!-- Plan selector tabs -->
    <div class="plan-tabs">
      <a href="admin_plans.php" class="plan-tab <?= !$sel_plan ? 'active' : '' ?>">All Plans</a>
      <?php foreach($plans as $pl): ?>
      <a href="?plan=<?= $pl['id'] ?>" class="plan-tab <?= $sel_plan==$pl['id']?'active':'' ?>">
        <?= htmlspecialchars($pl['name']) ?>
      </a>
      <?php endforeach; ?>
    </div>

    <?php if ($sel_plan_row): ?>
    <!-- ── Edit Plan Settings ── -->
    <div class="card">
      <div class="card-head">
        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg>
        <h2>Edit Plan: <?= htmlspecialchars($sel_plan_row['name']) ?></h2>
      </div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="action" value="update_plan">
          <input type="hidden" name="plan_id" value="<?= $sel_plan_row['id'] ?>">

          <!-- Basic Plan Settings -->
          <div class="section-label">📋 Basic Plan Settings</div>
          <div class="form-row">
            <div>
              <label>Required Balance (Price)</label>
              <input type="number" name="price" value="<?= $sel_plan_row['price'] ?>" step="0.01">
            </div>
            <div>
              <label>Daily Tasks</label>
              <input type="number" name="daily_tasks" value="<?= $sel_plan_row['daily_tasks'] ?>">
            </div>
            <div>
              <label>Per Order Earn</label>
              <input type="number" name="per_order" value="<?= $sel_plan_row['per_order'] ?>" step="0.0001">
            </div>
            <div>
              <label>Daily Earnings</label>
              <input type="number" name="daily_earnings" value="<?= $sel_plan_row['daily_earnings'] ?>" step="0.0001">
            </div>
            <div>
              <label>Duration (days, 0=permanent)</label>
              <input type="number" name="duration_days" value="<?= $sel_plan_row['duration_days'] ?>">
            </div>
            <div style="display:flex;gap:10px">
              <div style="flex:1"><label>Color From</label><input type="color" name="color_from" value="<?= $sel_plan_row['color_from'] ?>"></div>
              <div style="flex:1"><label>Color To</label><input type="color" name="color_to" value="<?= $sel_plan_row['color_to'] ?>"></div>
            </div>
          </div>

          <!-- Referral Commission -->
          <div class="section-label">🎯 Referral Commission (when downliner joins a plan)</div>
          <div class="rate-callout">
            💡 Referral commission is paid to the upliner when a downliner <strong>joins/activates a paid plan</strong>. 
            The amount is calculated as <strong>% of the plan's price</strong>.<br>
            Level 1 = direct referral &nbsp;|&nbsp; Level 2 = referral's referral &nbsp;|&nbsp; Level 3 = 3rd tier down
          </div>
          <div class="commission-box">
            <div class="cb-title">
              <svg viewBox="0 0 24 24" fill="currentColor"><path d="M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"/></svg>
              Referral Join Commission (% of plan price)
            </div>
            <div class="commission-row">
              <div class="ci">
                <label>Level 1</label>
                <input type="number" name="ref_commission_l1" value="<?= $sel_plan_row['ref_commission_l1'] ?? 10 ?>" step="0.01" min="0" max="100">
                <div class="ci-unit">% of plan price</div>
              </div>
              <div class="ci">
                <label>Level 2</label>
                <input type="number" name="ref_commission_l2" value="<?= $sel_plan_row['ref_commission_l2'] ?? 5 ?>" step="0.01" min="0" max="100">
                <div class="ci-unit">% of plan price</div>
              </div>
              <div class="ci">
                <label>Level 3</label>
                <input type="number" name="ref_commission_l3" value="<?= $sel_plan_row['ref_commission_l3'] ?? 2 ?>" step="0.01" min="0" max="100">
                <div class="ci-unit">% of plan price</div>
              </div>
            </div>

            <!-- Live preview -->
            <?php $price_val = (float)$sel_plan_row['price']; if ($price_val > 0): ?>
            <div style="margin-top:12px;background:#fff;border-radius:8px;padding:10px 12px;font-size:12px;color:#555">
              <strong>Preview for <?= htmlspecialchars($sel_plan_row['name']) ?> (Price: <?= number_format($price_val,2) ?>):</strong><br>
              L1 earns ≈ <strong id="prev_r1"><?= number_format($price_val * (($sel_plan_row['ref_commission_l1'] ?? 10)/100), 2) ?></strong> &nbsp;|&nbsp;
              L2 earns ≈ <strong id="prev_r2"><?= number_format($price_val * (($sel_plan_row['ref_commission_l2'] ?? 5)/100), 2) ?></strong> &nbsp;|&nbsp;
              L3 earns ≈ <strong id="prev_r3"><?= number_format($price_val * (($sel_plan_row['ref_commission_l3'] ?? 2)/100), 2) ?></strong>
            </div>
            <?php endif; ?>
          </div>

          <!-- Task Commission -->
          <div class="section-label">🎬 Task Commission (when downliner earns from watching videos)</div>
          <div class="rate-callout">
            💡 Task commission is paid to the upliner <strong>every time a downliner completes a video task</strong>.
            Calculated as <strong>% of the downliner's earned amount</strong> per task.<br>
            Example: Downliner earns 0.30 on a task, you get 5% = 0.015
          </div>
          <div class="commission-box green">
            <div class="cb-title">
              <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/></svg>
              Task Completion Commission (% of downliner's task earning)
            </div>
            <div class="commission-row green">
              <div class="ci">
                <label>Level 1</label>
                <input type="number" name="task_commission_l1" value="<?= $sel_plan_row['task_commission_l1'] ?? 5 ?>" step="0.01" min="0" max="100">
                <div class="ci-unit">% of task earned</div>
              </div>
              <div class="ci">
                <label>Level 2</label>
                <input type="number" name="task_commission_l2" value="<?= $sel_plan_row['task_commission_l2'] ?? 3 ?>" step="0.01" min="0" max="100">
                <div class="ci-unit">% of task earned</div>
              </div>
              <div class="ci">
                <label>Level 3</label>
                <input type="number" name="task_commission_l3" value="<?= $sel_plan_row['task_commission_l3'] ?? 1 ?>" step="0.01" min="0" max="100">
                <div class="ci-unit">% of task earned</div>
              </div>
            </div>

            <!-- Live preview -->
            <?php $per_order = (float)$sel_plan_row['per_order']; if ($per_order > 0): ?>
            <div style="margin-top:12px;background:#fff;border-radius:8px;padding:10px 12px;font-size:12px;color:#555">
              <strong>Preview per task (Per Order: <?= number_format($per_order,4) ?>):</strong><br>
              L1 gets ≈ <strong><?= number_format($per_order * (($sel_plan_row['task_commission_l1'] ?? 5)/100), 4) ?></strong> &nbsp;|&nbsp;
              L2 gets ≈ <strong><?= number_format($per_order * (($sel_plan_row['task_commission_l2'] ?? 3)/100), 4) ?></strong> &nbsp;|&nbsp;
              L3 gets ≈ <strong><?= number_format($per_order * (($sel_plan_row['task_commission_l3'] ?? 1)/100), 4) ?></strong>
            </div>
            <?php endif; ?>
          </div>

          <!-- Badge Image -->
          <div class="section-label">🏅 Plan Badge Image (shown on plan card)</div>
          <?php if (!empty($sel_plan_row['badge_img'])): ?>
            <div style="margin-bottom:10px">
              <img src="<?= htmlspecialchars($sel_plan_row['badge_img']) ?>" class="badge-preview" alt="Current Badge">
              <small style="color:var(--muted);display:block;margin-top:4px">Current badge image</small>
            </div>
          <?php endif; ?>
          <label class="file-label" for="badge_inp">
            <svg viewBox="0 0 24 24" fill="currentColor" style="color:#aaa"><path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/></svg>
            <span id="badge_lbl">Click to upload badge image (JPG, PNG, WebP)</span>
          </label>
          <input type="file" id="badge_inp" name="badge_img" accept="image/*"
                 onchange="document.getElementById('badge_lbl').textContent=this.files[0].name">

          <button type="submit" class="btn btn-primary">
            <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>
            Save All Plan Settings
          </button>
        </form>
      </div>
    </div>
    <?php endif; ?>

    <!-- ── Upload Video ── -->
    <div class="card">
      <div class="card-head">
        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/></svg>
        <h2>Upload Video</h2>
      </div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="action" value="add_video">

          <label>Assign Video To</label>
          <div class="assign-toggle">
            <label><input type="radio" name="assign_type" value="one" checked onchange="togglePlanSelect(this)"> Specific Plan</label>
            <label><input type="radio" name="assign_type" value="all" onchange="togglePlanSelect(this)"> All Plans</label>
          </div>

          <div id="plan_select_wrap">
            <label>Select Plan</label>
            <select name="plan_id">
              <option value="">-- Choose Plan --</option>
              <?php foreach($plans as $pl): ?>
              <option value="<?= $pl['id'] ?>" <?= $sel_plan==$pl['id'] ? 'selected' : '' ?>><?= htmlspecialchars($pl['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="form-row">
            <div>
              <label>Video Title *</label>
              <input type="text" name="title" placeholder="e.g. Festive Frolic - Instrumental">
            </div>
            <div>
              <label>Earn Per View (0 = use plan rate)</label>
              <input type="number" name="earn_amount" value="0" step="0.0001">
            </div>
          </div>

          <label>Cover Image</label>
          <label class="file-label" for="cover_inp">
            <svg viewBox="0 0 24 24" fill="currentColor" style="color:#aaa"><path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/></svg>
            <span id="cover_lbl">Click to select cover image</span>
          </label>
          <input type="file" id="cover_inp" name="cover_img" accept="image/*"
                 onchange="document.getElementById('cover_lbl').textContent=this.files[0].name">

          <label>Video File (MP4/WebM)</label>
          <label class="file-label" for="video_inp">
            <svg viewBox="0 0 24 24" fill="currentColor" style="color:#aaa"><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/></svg>
            <span id="video_lbl">Click to select video file (MP4, WebM)</span>
          </label>
          <input type="file" id="video_inp" name="video_file" accept="video/*"
                 onchange="document.getElementById('video_lbl').textContent=this.files[0].name">

          <label>— OR — Video URL</label>
          <input type="url" name="video_url" placeholder="https://...">

          <button type="submit" class="btn btn-primary">
            <svg viewBox="0 0 24 24" fill="currentColor"><path d="M9 16h6v-6h4l-7-7-7 7h4v6zm-4 2h14v2H5v-2z"/></svg>
            Upload Video
          </button>
        </form>
      </div>
    </div>

    <!-- ── Videos List ── -->
    <div class="card">
      <div class="card-head">
        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8 12.5v-9l6 4.5-6 4.5z"/></svg>
        <h2>Videos <?= $sel_plan_row ? 'in '.htmlspecialchars($sel_plan_row['name']) : '(All Plans)' ?> (<?= count($videos) ?>)</h2>
      </div>
      <div style="overflow-x:auto">
        <table>
          <thead><tr><th>Cover</th><th>Title</th><th>Plan</th><th>Earn/View</th><th>Actions</th></tr></thead>
          <tbody>
          <?php if (empty($videos)): ?>
            <tr><td colspan="5" style="text-align:center;color:#aaa;padding:24px">No videos yet. Upload above.</td></tr>
          <?php else: ?>
          <?php foreach($videos as $v): ?>
          <tr>
            <td><img src="<?= htmlspecialchars($v['cover_img'] ?: 'https://via.placeholder.com/56x42') ?>" class="thumb" onerror="this.src='https://via.placeholder.com/56x42'"></td>
            <td style="max-width:220px">
              <div style="font-weight:600;overflow:hidden;white-space:nowrap;text-overflow:ellipsis"><?= htmlspecialchars($v['title']) ?></div>
              <?php if ($v['video_url']): ?><div style="font-size:11px;color:#aaa;margin-top:2px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis"><?= htmlspecialchars($v['video_url']) ?></div><?php endif; ?>
            </td>
            <td><span class="badge-plan"><?= htmlspecialchars($v['plan_name']) ?></span></td>
            <td style="font-weight:700;color:#3ecf8e"><?= $v['earn_amount'] > 0 ? number_format($v['earn_amount'],4) : '<span style="color:#aaa">Plan rate</span>' ?></td>
            <td>
              <form method="POST" style="display:inline" onsubmit="return confirm('Remove this video?')">
                <input type="hidden" name="action" value="delete_video">
                <input type="hidden" name="video_id" value="<?= $v['id'] ?>">
                <input type="hidden" name="plan_id" value="<?= $sel_plan ?>">
                <button type="submit" class="btn btn-danger" style="height:34px;font-size:12px;padding:0 14px">
                  <svg viewBox="0 0 24 24" fill="currentColor" width="14"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/></svg>
                  Remove
                </button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

  </div>
</main>

<script>
function togglePlanSelect(radio) {
  document.getElementById('plan_select_wrap').style.display = radio.value === 'all' ? 'none' : 'block';
}
</script>
</body>
</html>