<?php
// ============================================================================
// HANDLE AJAX REQUESTS FIRST
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    require_once '../config/database.php';
    require_once '../includes/functions.php';
    header('Content-Type: application/json');
    $conn = getConnection();

    if ($_POST['ajax_action'] === 'approve_completion') {
        $completionId = intval($_POST['completion_id'] ?? 0);
        $newStatus    = $_POST['status'] ?? 'completed';
        $adminNotes   = mysqli_real_escape_string($conn, $_POST['admin_notes'] ?? '');
        if ($completionId <= 0) { echo json_encode(['success'=>false,'message'=>'Invalid ID']); exit; }
        $completion = mysqli_query($conn,"SELECT * FROM task_completions WHERE id=$completionId")->fetch_assoc();
        if (!$completion) { echo json_encode(['success'=>false,'message'=>'Not found']); exit; }
        $stmt = mysqli_prepare($conn,"UPDATE task_completions SET status=?,admin_notes=?,reviewed_at=NOW() WHERE id=?");
        mysqli_stmt_bind_param($stmt,"ssi",$newStatus,$adminNotes,$completionId);
        mysqli_stmt_execute($stmt);
        if ($newStatus==='completed'&&$completion['status']!=='completed') {
            $uid=$completion['user_id']; $rwd=$completion['reward_earned']; $tt=$completion['task_type'];
            $wmap=['video'=>'video_wallet','survey'=>'survey_wallet','chat'=>'chat_wallet','transcription'=>'transcription_wallet','trivia'=>'trivia_wallet','quiz'=>'trivia_wallet','ads'=>'ads_wallet','blog'=>'blog_wallet','meme'=>'meme_wallet','spin'=>'spin_wallet'];
            $wc=$wmap[$tt]??'trivia_wallet';
            mysqli_query($conn,"INSERT INTO wallets(user_id,$wc,created_at,updated_at)VALUES($uid,$rwd,NOW(),NOW()) ON DUPLICATE KEY UPDATE $wc=$wc+$rwd,updated_at=NOW()");
        }
        echo json_encode(['success'=>true,'message'=>'Updated']);
        exit;
    }

    if ($_POST['ajax_action'] === 'get_task_data') {
        $taskId = intval($_POST['task_id'] ?? 0);
        if ($taskId<=0) { echo json_encode(['success'=>false,'message'=>'Invalid ID']); exit; }
        $stmt=mysqli_prepare($conn,"SELECT * FROM tasks WHERE id=?");
        mysqli_stmt_bind_param($stmt,"i",$taskId); mysqli_stmt_execute($stmt);
        $task=mysqli_stmt_get_result($stmt)->fetch_assoc();
        if (!$task) { echo json_encode(['success'=>false,'message'=>'Not found']); exit; }
        $td=['success'=>true,'task'=>$task,'quiz_questions'=>[],'blog_data'=>null,'survey_questions'=>[],'meme_data'=>null,'transcription_data'=>null];
        if ($task['content_type']==='internal') {
            if (in_array($task['task_type'],['quiz','trivia'])) { $q=mysqli_query($conn,"SELECT * FROM task_quizzes WHERE task_id=$taskId ORDER BY order_number"); while($r=mysqli_fetch_assoc($q))$td['quiz_questions'][]=$r; }
            elseif ($task['task_type']==='blog') { $q=mysqli_query($conn,"SELECT * FROM task_blog_requirements WHERE task_id=$taskId LIMIT 1"); $td['blog_data']=mysqli_fetch_assoc($q); }
            elseif ($task['task_type']==='survey') { $q=mysqli_query($conn,"SELECT * FROM task_survey_questions WHERE task_id=$taskId ORDER BY order_number"); while($r=mysqli_fetch_assoc($q))$td['survey_questions'][]=$r; }
            elseif ($task['task_type']==='meme') { $q=mysqli_query($conn,"SELECT * FROM task_meme_requirements WHERE task_id=$taskId LIMIT 1"); $td['meme_data']=mysqli_fetch_assoc($q); }
            elseif ($task['task_type']==='transcription') { $q=mysqli_query($conn,"SELECT * FROM task_transcription_content WHERE task_id=$taskId LIMIT 1"); $td['transcription_data']=mysqli_fetch_assoc($q); }
        }
        echo json_encode($td); exit;
    }

    if ($_POST['ajax_action'] === 'bulk_action') {
        $action  = $_POST['bulk_type'] ?? '';
        $taskIds = $_POST['task_ids'] ?? [];
        if (is_string($taskIds)) $taskIds = json_decode($taskIds, true);
        if (!is_array($taskIds)||empty($taskIds)) { echo json_encode(['success'=>false,'message'=>'None selected']); exit; }
        $ids    = array_map('intval', $taskIds);
        $idsStr = implode(',', $ids);
        if ($action==='activate')   { mysqli_query($conn,"UPDATE tasks SET status='active' WHERE id IN($idsStr)"); echo json_encode(['success'=>true,'message'=>count($ids).' tasks activated']); }
        elseif ($action==='deactivate') { mysqli_query($conn,"UPDATE tasks SET status='inactive' WHERE id IN($idsStr)"); echo json_encode(['success'=>true,'message'=>count($ids).' tasks deactivated']); }
        elseif ($action==='delete') {
            foreach(['task_quizzes','task_blog_requirements','task_survey_questions','task_chat_requirements','task_meme_requirements','task_transcription_content','task_completions'] as $tbl)
                mysqli_query($conn,"DELETE FROM $tbl WHERE task_id IN($idsStr)");
            mysqli_query($conn,"DELETE FROM tasks WHERE id IN($idsStr)");
            echo json_encode(['success'=>true,'message'=>count($ids).' tasks deleted']);
        } else { echo json_encode(['success'=>false,'message'=>'Invalid action']); }
        exit;
    }
}

// ============================================================================
// PAGE SETUP
// ============================================================================
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Manage Tasks';
include 'side.php';
require_once 'admin_protect.php';
$conn = getConnection();
$view = $_GET['view'] ?? 'tasks';

$internalTaskTypes = ['trivia','quiz','blog','survey','meme','transcription'];
$externalTaskTypes = ['video','ads','spin','chat'];

// ============================================================================
// FORM SUBMISSIONS
// ============================================================================
if ($_SERVER['REQUEST_METHOD']==='POST' && !isset($_POST['ajax_action'])) {
    $action = $_POST['form_action'] ?? '';

    if ($action==='add'||$action==='edit') {
        if (empty($_POST['title']))                            { setFlash('error','Title required!'); header('Location: '.$_SERVER['PHP_SELF']); exit; }
        if (empty($_POST['reward'])||floatval($_POST['reward'])<=0) { setFlash('error','Valid reward required!'); header('Location: '.$_SERVER['PHP_SELF']); exit; }

        $title=$_POST['title']; $description=$_POST['description']??''; $instructions=$_POST['instructions']??'';
        $taskType=$_POST['task_type']??'trivia';
        $contentType=in_array($taskType,$internalTaskTypes)?'internal':'external';
        $taskUrl=$_POST['task_url']??''; $reward=floatval($_POST['reward']);
        $dailyLimit=intval($_POST['daily_limit_per_user']??1);
        $totalLimit=!empty($_POST['total_limit'])?intval($_POST['total_limit']):null;
        $minDur=intval($_POST['min_duration_seconds']??0);
        $enableTimer=isset($_POST['enable_timer'])?1:0;
        $status=isset($_POST['is_active'])?'active':'inactive';
        $sidebar=isset($_POST['show_in_sidebar'])?1:0;
        $autoAppr=isset($_POST['auto_approve'])?1:0;
        $reqProof=isset($_POST['requires_proof'])?1:0;
        $difficulty=$_POST['difficulty']??'easy';
        $category=$_POST['category']??'general';
        $passPct=intval($_POST['pass_percentage']??70);

        // Image
        $taskImage=null; $uploadErr=false;
        if (isset($_FILES['task_image'])&&$_FILES['task_image']['error']===UPLOAD_ERR_OK) {
            $ext=strtolower(pathinfo($_FILES['task_image']['name'],PATHINFO_EXTENSION));
            if (!in_array($ext,['jpg','jpeg','png','gif','webp'])) { setFlash('error','Invalid image type!'); $uploadErr=true; }
            elseif ($_FILES['task_image']['size']>10*1024*1024) { setFlash('error','Image too large!'); $uploadErr=true; }
            else {
                $ud='../uploads/task_images/'; if(!file_exists($ud))mkdir($ud,0755,true);
                $nf='task_'.time().'_'.uniqid().'.'.$ext;
                if(move_uploaded_file($_FILES['task_image']['tmp_name'],$ud.$nf)) $taskImage='uploads/task_images/'.$nf;
                else { setFlash('error','Upload failed!'); $uploadErr=true; }
            }
        }
        if ($action==='edit') {
            $existingImage=$_POST['existing_image']??null;
            $removeImage=isset($_POST['remove_image'])&&$_POST['remove_image']=='1';
            if ($removeImage&&$existingImage) { $op='../'.$existingImage; if(file_exists($op))@unlink($op); $taskImage=null; }
            elseif (!$taskImage&&$existingImage&&!$removeImage) $taskImage=$existingImage;
        }
        if ($uploadErr) { header('Location: '.$_SERVER['PHP_SELF']); exit; }
        if ($contentType==='external'&&empty($taskUrl)) { setFlash('error','URL required for '.$taskType.'!'); header('Location: '.$_SERVER['PHP_SELF']); exit; }

        mysqli_begin_transaction($conn);
        try {
            if ($action==='add') {
                $sql="INSERT INTO tasks(title,description,instructions,task_type,content_type,task_url,task_image,reward,daily_limit_per_user,total_limit,min_duration_seconds,enable_timer,status,show_in_sidebar,auto_approve,requires_proof,difficulty,category,pass_percentage)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                $stmt=mysqli_prepare($conn,$sql);
                mysqli_stmt_bind_param($stmt,"sssssssdiiiisiiissi",$title,$description,$instructions,$taskType,$contentType,$taskUrl,$taskImage,$reward,$dailyLimit,$totalLimit,$minDur,$enableTimer,$status,$sidebar,$autoAppr,$reqProof,$difficulty,$category,$passPct);
                mysqli_stmt_execute($stmt); $taskId=mysqli_insert_id($conn); mysqli_stmt_close($stmt);
            } else {
                $taskId=intval($_POST['task_id']);
                $sql="UPDATE tasks SET title=?,description=?,instructions=?,task_type=?,content_type=?,task_url=?,task_image=?,reward=?,daily_limit_per_user=?,total_limit=?,min_duration_seconds=?,enable_timer=?,status=?,show_in_sidebar=?,auto_approve=?,requires_proof=?,difficulty=?,category=?,pass_percentage=? WHERE id=?";
                $stmt=mysqli_prepare($conn,$sql);
                mysqli_stmt_bind_param($stmt,"sssssssdiiiisiiissii",$title,$description,$instructions,$taskType,$contentType,$taskUrl,$taskImage,$reward,$dailyLimit,$totalLimit,$minDur,$enableTimer,$status,$sidebar,$autoAppr,$reqProof,$difficulty,$category,$passPct,$taskId);
                mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt);
                foreach(['task_quizzes','task_blog_requirements','task_survey_questions','task_meme_requirements','task_transcription_content'] as $t)
                    mysqli_query($conn,"DELETE FROM $t WHERE task_id=$taskId");
            }

            // Save internal content
            if ($contentType==='internal') {
                if (in_array($taskType,['trivia','quiz'])) {
                    foreach ($_POST['quiz_questions']??[] as $i=>$q) {
                        if (!empty($q['question'])&&!empty($q['option_a'])&&!empty($q['option_b'])&&!empty($q['correct_answer'])) {
                            $s=mysqli_prepare($conn,"INSERT INTO task_quizzes(task_id,question,option_a,option_b,option_c,option_d,correct_answer,explanation,order_number,points)VALUES(?,?,?,?,?,?,?,?,?,?)");
                            $oc=$q['option_c']??null; $od=$q['option_d']??null; $ex=$q['explanation']??null; $ca=strtoupper(trim($q['correct_answer'])); $pts=intval($q['points']??1);
                            mysqli_stmt_bind_param($s,"isssssssii",$taskId,$q['question'],$q['option_a'],$q['option_b'],$oc,$od,$ca,$ex,$i,$pts);
                            mysqli_stmt_execute($s); mysqli_stmt_close($s);
                        }
                    }
                } elseif ($taskType==='blog') {
                    $topic=$_POST['blog_topic']??$title; $minW=intval($_POST['blog_min_words']??300); $maxW=!empty($_POST['blog_max_words'])?intval($_POST['blog_max_words']):null;
                    $kw=$_POST['blog_keywords']??''; $bg=$_POST['blog_guidelines']??''; $ewc=isset($_POST['enable_word_count'])?1:0; $bo=$_POST['blog_sample_outline']??'';
                    $s=mysqli_prepare($conn,"INSERT INTO task_blog_requirements(task_id,topic,min_words,max_words,keywords,guidelines,enable_word_count,sample_outline)VALUES(?,?,?,?,?,?,?,?)");
                    mysqli_stmt_bind_param($s,"isiissis",$taskId,$topic,$minW,$maxW,$kw,$bg,$ewc,$bo); mysqli_stmt_execute($s); mysqli_stmt_close($s);
                } elseif ($taskType==='survey') {
                    foreach ($_POST['survey_questions']??[] as $i=>$sq) {
                        if (!empty($sq['question'])&&!empty($sq['type'])) {
                            $opts=null; if ($sq['type']==='multiple_choice'&&!empty($sq['options'])) $opts=implode('|',array_map('trim',explode(',',$sq['options'])));
                            $req=isset($sq['required'])?1:0;
                            $s=mysqli_prepare($conn,"INSERT INTO task_survey_questions(task_id,question,question_type,options,required,order_number)VALUES(?,?,?,?,?,?)");
                            mysqli_stmt_bind_param($s,"isssii",$taskId,$sq['question'],$sq['type'],$opts,$req,$i); mysqli_stmt_execute($s); mysqli_stmt_close($s);
                        }
                    }
                } elseif ($taskType==='meme') {
                    $theme=$_POST['meme_theme']??$title; $af=$_POST['meme_allowed_formats']??'jpg,png,gif'; $ms=intval($_POST['meme_max_file_size']??5); $md=$_POST['meme_min_dimensions']??''; $mg=$_POST['meme_guidelines']??'';
                    $s=mysqli_prepare($conn,"INSERT INTO task_meme_requirements(task_id,theme,allowed_formats,max_file_size_mb,min_dimensions,guidelines)VALUES(?,?,?,?,?,?)");
                    mysqli_stmt_bind_param($s,"ississ",$taskId,$theme,$af,$ms,$md,$mg); mysqli_stmt_execute($s); mysqli_stmt_close($s);
                } elseif ($taskType==='transcription') {
                    $au=$_POST['trans_audio_url']??''; $vu=$_POST['trans_video_url']??''; $ds=!empty($_POST['trans_duration_seconds'])?intval($_POST['trans_duration_seconds']):null;
                    $lang=$_POST['trans_language']??'English'; $ewc2=!empty($_POST['trans_expected_word_count'])?intval($_POST['trans_expected_word_count']):null; $dl=$_POST['trans_difficulty_level']??'medium';
                    $s=mysqli_prepare($conn,"INSERT INTO task_transcription_content(task_id,audio_url,video_url,duration_seconds,language,expected_word_count,difficulty_level)VALUES(?,?,?,?,?,?,?)");
                    mysqli_stmt_bind_param($s,"issisis",$taskId,$au,$vu,$ds,$lang,$ewc2,$dl); mysqli_stmt_execute($s); mysqli_stmt_close($s);
                }
            }

            mysqli_commit($conn);
            setFlash('success','Task '.($action==='add'?'created':'updated').' successfully!');
        } catch (Exception $e) {
            mysqli_rollback($conn);
            setFlash('error','Error: '.$e->getMessage());
        }
        header('Location: '.$_SERVER['PHP_SELF']); exit;
    }

    elseif ($action==='delete') {
        $taskId=intval($_POST['task_id']);
        $td=mysqli_query($conn,"SELECT task_image FROM tasks WHERE id=$taskId")->fetch_assoc();
        foreach(['task_quizzes','task_blog_requirements','task_survey_questions','task_chat_requirements','task_meme_requirements','task_transcription_content','task_completions'] as $t)
            mysqli_query($conn,"DELETE FROM $t WHERE task_id=$taskId");
        $s=mysqli_prepare($conn,"DELETE FROM tasks WHERE id=?"); mysqli_stmt_bind_param($s,"i",$taskId); mysqli_stmt_execute($s);
        if ($td&&$td['task_image']&&file_exists('../'.$td['task_image']))@unlink('../'.$td['task_image']);
        setFlash('success','Task deleted!'); header('Location: '.$_SERVER['PHP_SELF']); exit;
    }
    elseif ($action==='toggle') {
        $taskId=intval($_POST['task_id']);
        $s=mysqli_prepare($conn,"UPDATE tasks SET status=CASE WHEN status='active' THEN 'inactive' ELSE 'active' END WHERE id=?");
        mysqli_stmt_bind_param($s,"i",$taskId); mysqli_stmt_execute($s);
        setFlash('success','Status toggled!'); header('Location: '.$_SERVER['PHP_SELF']); exit;
    }
    elseif ($action==='duplicate') {
        $taskId=intval($_POST['task_id']);
        $task=mysqli_query($conn,"SELECT * FROM tasks WHERE id=$taskId")->fetch_assoc();
        if ($task) {
            $nt=$task['title'].' (Copy)';
            $s=mysqli_prepare($conn,"INSERT INTO tasks(title,description,instructions,task_type,content_type,task_url,reward,daily_limit_per_user,total_limit,min_duration_seconds,enable_timer,status,show_in_sidebar,auto_approve,requires_proof,difficulty,category,pass_percentage)SELECT ?,description,instructions,task_type,content_type,task_url,reward,daily_limit_per_user,total_limit,min_duration_seconds,enable_timer,'inactive',0,auto_approve,requires_proof,difficulty,category,pass_percentage FROM tasks WHERE id=?");
            mysqli_stmt_bind_param($s,"si",$nt,$taskId); mysqli_stmt_execute($s); $newId=mysqli_insert_id($conn);
            if (in_array($task['task_type'],['trivia','quiz'])) mysqli_query($conn,"INSERT INTO task_quizzes(task_id,question,option_a,option_b,option_c,option_d,correct_answer,explanation,order_number,points)SELECT $newId,question,option_a,option_b,option_c,option_d,correct_answer,explanation,order_number,points FROM task_quizzes WHERE task_id=$taskId");
            elseif ($task['task_type']==='blog') mysqli_query($conn,"INSERT INTO task_blog_requirements(task_id,topic,min_words,max_words,keywords,guidelines,enable_word_count,sample_outline)SELECT $newId,topic,min_words,max_words,keywords,guidelines,enable_word_count,sample_outline FROM task_blog_requirements WHERE task_id=$taskId");
            elseif ($task['task_type']==='survey') mysqli_query($conn,"INSERT INTO task_survey_questions(task_id,question,question_type,options,required,order_number)SELECT $newId,question,question_type,options,required,order_number FROM task_survey_questions WHERE task_id=$taskId");
        }
        setFlash('success','Task duplicated!'); header('Location: '.$_SERVER['PHP_SELF']); exit;
    }
}

// ============================================================================
// FETCH DATA
// ============================================================================
$filterType=$_GET['type']??''; $filterStatus=$_GET['status']??''; $search=$_GET['search']??'';
$where=[]; $types=''; $vals=[];
if ($filterType)   { $where[]="t.task_type=?";  $types.='s'; $vals[]=$filterType; }
if ($filterStatus) { $where[]="t.status=?";     $types.='s'; $vals[]=$filterStatus; }
if ($search)       { $where[]="(t.title LIKE ? OR t.description LIKE ?)"; $types.='ss'; $term='%'.$search.'%'; $vals[]=$term; $vals[]=$term; }
$wc=!empty($where)?'WHERE '.implode(' AND ',$where):'';
$q="SELECT t.*,COUNT(DISTINCT tc.user_id) as unique_users,COALESCE(SUM(CASE WHEN tc.status='completed' THEN tc.reward_earned ELSE 0 END),0) as total_paid FROM tasks t LEFT JOIN task_completions tc ON t.id=tc.task_id $wc GROUP BY t.id ORDER BY t.created_at DESC";
if (!empty($where)) { $stmt=mysqli_prepare($conn,$q); mysqli_stmt_bind_param($stmt,$types,...$vals); mysqli_stmt_execute($stmt); $tasks=mysqli_stmt_get_result($stmt); }
else $tasks=mysqli_query($conn,$q);

$stats=mysqli_query($conn,"SELECT COUNT(*) as total,SUM(status='active') as active,SUM(content_type='internal') as internal,SUM(content_type='external') as external FROM tasks")->fetch_assoc();
$stats['paid']=mysqli_query($conn,"SELECT COALESCE(SUM(reward_earned),0) as t FROM task_completions WHERE status='completed'")->fetch_assoc()['t'];
$stats['pending']=mysqli_query($conn,"SELECT COUNT(*) as t FROM task_completions WHERE status='pending'")->fetch_assoc()['t'];

$typeStats=[]; $tsr=mysqli_query($conn,"SELECT task_type,COUNT(*) as cnt,SUM(status='active') as active FROM tasks GROUP BY task_type"); while($r=mysqli_fetch_assoc($tsr))$typeStats[$r['task_type']]=$r;

if ($view==='approvals') {
    $pending=mysqli_query($conn,"SELECT tc.*,t.title as ttl,t.task_type,u.username,u.email FROM task_completions tc JOIN tasks t ON tc.task_id=t.id JOIN users u ON tc.user_id=u.id WHERE tc.status='pending' ORDER BY tc.created_at DESC LIMIT 100");
}
if ($view==='completions') {
    $cs=$_GET['cs']??'all'; $ctid=isset($_GET['tid'])?intval($_GET['tid']):null;
    $cw=[]; if($cs!=='all')$cw[]="tc.status='".mysqli_real_escape_string($conn,$cs)."'"; if($ctid)$cw[]="tc.task_id=$ctid";
    $cwc=!empty($cw)?'WHERE '.implode(' AND ',$cw):'';
    $allComps=mysqli_query($conn,"SELECT tc.*,t.title as ttl,t.task_type,u.username FROM task_completions tc JOIN tasks t ON tc.task_id=t.id JOIN users u ON tc.user_id=u.id $cwc ORDER BY tc.created_at DESC LIMIT 200");
}

$themeColor=getSetting('theme_color','#6366f1');
$flash=getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
    --tc:<?= $themeColor ?>;
    --bg:#0d0f14;--bg2:#13161d;--bg3:#1a1e28;
    --bdr:rgba(255,255,255,.07);--bdr2:rgba(255,255,255,.12);
    --txt:#f1f5f9;--txt2:#94a3b8;--txt3:#475569;
    --grn:#22c55e;--red:#ef4444;--ylw:#f59e0b;--blu:#3b82f6;
    --rad:12px;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--txt);font-size:13px;line-height:1.5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif}
::-webkit-scrollbar{width:4px;height:4px}
::-webkit-scrollbar-thumb{background:var(--bg3);border-radius:4px}

.adm{padding:14px;max-width:1280px}
@media(min-width:768px){.adm{padding:20px}}

/* ── FLASH ── */
.fl{display:flex;align-items:center;gap:9px;padding:10px 14px;border-radius:var(--rad);font-size:12.5px;font-weight:600;margin-bottom:14px;border-left:3px solid}
.fl.success{background:rgba(34,197,94,.08);border-color:var(--grn);color:var(--grn)}
.fl.error{background:rgba(239,68,68,.08);border-color:var(--red);color:var(--red)}
.fl.warning{background:rgba(245,158,11,.08);border-color:var(--ylw);color:var(--ylw)}
.fl.info{background:rgba(59,130,246,.08);border-color:var(--blu);color:var(--blu)}

/* ── STATS ── */
.stats{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:14px}
@media(min-width:640px){.stats{grid-template-columns:repeat(3,1fr)}}
@media(min-width:900px){.stats{grid-template-columns:repeat(6,1fr)}}
.sc{background:var(--bg2);border:1px solid var(--bdr);border-radius:var(--rad);padding:13px;position:relative;overflow:hidden;transition:border-color .2s}
.sc:hover{border-color:var(--bdr2)}
.sc::after{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:var(--sc-color,var(--tc))}
.sc-ico{width:32px;height:32px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:14px;margin-bottom:9px;background:rgba(var(--sc-rgb,99,102,241),.12);color:var(--sc-color,var(--tc))}
.sc-num{font-size:20px;font-weight:800;color:var(--txt);letter-spacing:-1px;line-height:1;margin-bottom:2px}
.sc-lbl{font-size:9.5px;color:var(--txt3);text-transform:uppercase;letter-spacing:.6px;font-weight:600}

/* ── NAV TABS ── */
.nav-tabs{display:flex;gap:4px;margin-bottom:14px;background:var(--bg2);border:1px solid var(--bdr);border-radius:var(--rad);padding:4px;overflow-x:auto;scrollbar-width:none}
.nav-tabs::-webkit-scrollbar{display:none}
.ntab{display:flex;align-items:center;gap:6px;padding:7px 14px;border-radius:9px;text-decoration:none;color:var(--txt2);font-size:12px;font-weight:600;white-space:nowrap;transition:.15s;flex-shrink:0;border:none;background:none;cursor:pointer}
.ntab:hover{color:var(--txt);background:var(--bg3)}
.ntab.on{background:var(--tc);color:#fff;box-shadow:0 3px 12px rgba(99,102,241,.35)}
.ntab .cnt{padding:1px 6px;border-radius:5px;font-size:9px;font-weight:700;background:rgba(255,255,255,.18)}
.ntab:not(.on) .cnt{background:var(--bg3);color:var(--txt3)}

/* ── TOOLBAR ── */
.toolbar{display:flex;gap:8px;margin-bottom:10px;flex-wrap:wrap;align-items:center}
.tb-search{position:relative;flex:1;min-width:160px}
.tb-search i{position:absolute;left:11px;top:50%;transform:translateY(-50%);color:var(--txt3);font-size:12px;pointer-events:none}
.tb-search input{width:100%;height:36px;padding:0 11px 0 33px;background:var(--bg2);border:1px solid var(--bdr);border-radius:9px;color:var(--txt);font-size:12.5px;outline:none;transition:.15s}
.tb-search input:focus{border-color:var(--tc);box-shadow:0 0 0 3px rgba(99,102,241,.12)}
.tb-sel{height:36px;padding:0 10px;background:var(--bg2);border:1px solid var(--bdr);border-radius:9px;color:var(--txt2);font-size:12px;outline:none;transition:.15s;cursor:pointer}
.tb-sel option{background:var(--bg2)}
.btn{height:36px;padding:0 14px;border-radius:9px;font-size:12px;font-weight:700;border:none;cursor:pointer;display:inline-flex;align-items:center;gap:6px;transition:.15s;white-space:nowrap}
.btn:hover{opacity:.88;transform:translateY(-1px)}
.btn-primary{background:var(--tc);color:#fff;box-shadow:0 3px 12px rgba(99,102,241,.3)}
.btn-ghost{background:var(--bg2);border:1px solid var(--bdr);color:var(--txt2)}
.btn-ghost:hover{color:var(--txt);border-color:var(--bdr2)}
.btn-green{background:var(--grn);color:#fff}
.btn-red{background:var(--red);color:#fff}

/* ── BULK BAR ── */
.bulk-bar{display:none;align-items:center;justify-content:space-between;gap:10px;padding:10px 14px;background:linear-gradient(135deg,var(--tc),#8b5cf6);border-radius:var(--rad);margin-bottom:10px;flex-wrap:wrap}
.bulk-bar.on{display:flex}
.bulk-info{color:#fff;font-size:12.5px;font-weight:700}
.bulk-btns{display:flex;gap:6px;flex-wrap:wrap}
.bulk-btn{padding:5px 12px;background:rgba(255,255,255,.18);border:1px solid rgba(255,255,255,.25);border-radius:7px;color:#fff;font-size:11px;font-weight:700;cursor:pointer;transition:.15s}
.bulk-btn:hover{background:rgba(255,255,255,.3)}

/* ── TASK CARDS ── */
.tasks-grid{display:flex;flex-direction:column}
.tc{background:var(--bg2);border:1px solid var(--bdr);border-radius:var(--rad);overflow:hidden;transition:border-color .15s;margin-bottom:8px}
.tc:hover{border-color:var(--bdr2)}
.tc.sel{border-color:var(--tc);background:rgba(99,102,241,.04)}
.tc-img-strip{width:100%;height:110px;object-fit:cover;background:var(--bg3);display:block}
.tc-body{padding:13px}
.tc-top{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:8px}
.tc-chk{width:18px;height:18px;flex-shrink:0;margin-top:2px;accent-color:var(--tc);cursor:pointer;display:none}
.tc.bulk-mode .tc-chk{display:block}
.tc-title{font-size:13.5px;font-weight:700;color:var(--txt);flex:1;min-width:0;word-break:break-word}
.tc-id{font-size:10px;color:var(--txt3);font-weight:600;flex-shrink:0}
.tc-badges{display:flex;flex-wrap:wrap;gap:5px;margin-bottom:9px}
.badge{padding:2px 8px;border-radius:5px;font-size:9.5px;font-weight:700;text-transform:uppercase;display:inline-flex;align-items:center;gap:3px}
.b-type{background:rgba(99,102,241,.15);color:#818cf8}
.b-int{background:rgba(34,197,94,.12);color:#4ade80}
.b-ext{background:rgba(59,130,246,.12);color:#60a5fa}
.b-active{background:rgba(34,197,94,.12);color:#4ade80}
.b-inactive{background:rgba(239,68,68,.1);color:#f87171}
.b-sidebar{background:rgba(245,158,11,.1);color:#fbbf24}
.b-timer{background:rgba(168,85,247,.12);color:#c084fc}
.tc-url{display:flex;align-items:center;gap:7px;padding:6px 9px;background:var(--bg3);border-radius:7px;margin-bottom:9px}
.tc-url i{color:var(--tc);font-size:10px;flex-shrink:0}
.tc-url a{font-size:10.5px;color:var(--txt2);text-decoration:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1}
.tc-meta{display:grid;grid-template-columns:repeat(2,1fr);gap:6px;margin-bottom:10px}
.tm{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--txt2)}
.tm i{color:var(--txt3);font-size:10px;width:13px;text-align:center}
.tm strong{color:var(--txt);font-weight:700}
.tc-actions{display:grid;grid-template-columns:repeat(2,1fr);gap:6px}
@media(min-width:480px){.tc-actions{grid-template-columns:repeat(4,1fr)}}
.ta{height:33px;border-radius:8px;border:none;cursor:pointer;font-size:11px;font-weight:700;display:flex;align-items:center;justify-content:center;gap:5px;color:#fff;transition:.15s}
.ta:hover{transform:translateY(-1px);opacity:.88}
.ta-edit{background:var(--tc)}.ta-toggle{background:var(--ylw);color:#000}.ta-copy{background:var(--blu)}.ta-del{background:var(--red)}

/* ── APPROVALS/COMPLETIONS ── */
.comp-item{background:var(--bg2);border:1px solid var(--bdr);border-radius:var(--rad);padding:13px;margin-bottom:8px}
.comp-item:hover{border-color:var(--bdr2)}
.comp-title{font-size:13px;font-weight:700;color:var(--txt);margin-bottom:6px}
.comp-meta{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:9px}
.cm{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--txt2)}
.cm i{color:var(--txt3);font-size:10px}
.comp-proof{max-width:200px;border-radius:8px;border:1px solid var(--bdr);margin:8px 0;display:block}
.comp-actions{display:flex;gap:7px}
.empty{text-align:center;padding:48px 20px;background:var(--bg2);border:1px solid var(--bdr);border-radius:var(--rad)}
.empty i{font-size:40px;color:var(--txt3);margin-bottom:12px;display:block}
.empty-t{font-size:14px;font-weight:700;color:var(--txt2);margin-bottom:4px}
.empty-s{font-size:12px;color:var(--txt3)}

/* ═══════════════════════════════
   DRAWER
═══════════════════════════════ */
.drawer-overlay{
    display:none;position:fixed;inset:0;
    background:rgba(0,0,0,.65);
    backdrop-filter:blur(8px);
    -webkit-backdrop-filter:blur(8px);
    z-index:3000;
    opacity:0;transition:opacity .3s ease;
}
.drawer-overlay.on{display:block;opacity:1}
.drawer{position:fixed;top:0;right:-110%;width:100%;max-width:580px;height:100vh;background:var(--bg2);border-left:1px solid var(--bdr);z-index:3001;display:flex;flex-direction:column;transition:right .35s cubic-bezier(.22,1,.36,1)}
.drawer.on{right:0}
.drawer-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px;border-bottom:1px solid var(--bdr);flex-shrink:0;background:var(--bg3)}
.drawer-title{font-size:15px;font-weight:800;color:var(--txt)}
.drawer-cls{width:32px;height:32px;border-radius:8px;background:var(--bg);border:1px solid var(--bdr);color:var(--txt2);display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:15px;transition:.15s}
.drawer-cls:hover{background:var(--red);color:#fff;border-color:var(--red)}
.drawer-body{flex:1;overflow-y:auto;padding:18px}
.drawer-body::-webkit-scrollbar{width:3px}
.drawer-body::-webkit-scrollbar-thumb{background:var(--bg3)}
.drawer-foot{padding:14px 18px;border-top:1px solid var(--bdr);flex-shrink:0;background:var(--bg3)}

/* ── FORM ── */
.fg{margin-bottom:13px}
.fl2{display:block;font-size:11px;font-weight:700;color:var(--txt2);margin-bottom:5px;text-transform:uppercase;letter-spacing:.4px}
.fi,.fta,.fsel2{width:100%;padding:9px 11px;background:var(--bg);border:1.5px solid var(--bdr);border-radius:9px;color:var(--txt);font-size:12.5px;outline:none;transition:.15s}
.fi:focus,.fta:focus,.fsel2:focus{border-color:var(--tc);box-shadow:0 0 0 3px rgba(99,102,241,.12);background:var(--bg2)}
.fi::placeholder,.fta::placeholder{color:var(--txt3)}
.fta{min-height:80px;resize:vertical;line-height:1.6}
.fsel2{cursor:pointer;-webkit-appearance:none;appearance:none}
.fsel2 option{background:var(--bg2)}
.frow{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.fchk-row{display:flex;align-items:center;gap:8px;padding:9px 11px;background:var(--bg);border:1px solid var(--bdr);border-radius:9px;margin-bottom:8px;cursor:pointer;transition:.15s}
.fchk-row:hover{border-color:var(--bdr2)}
.fchk-row input[type=checkbox]{width:16px;height:16px;accent-color:var(--tc);cursor:pointer;flex-shrink:0}
.fchk-row span{font-size:12px;color:var(--txt2);font-weight:500}

/* ── TYPE GRID ── */
.type-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:6px;margin-bottom:14px}
.type-opt{padding:10px 6px;background:var(--bg);border:1.5px solid var(--bdr);border-radius:10px;cursor:pointer;text-align:center;transition:.15s;position:relative}
.type-opt:hover{border-color:var(--bdr2)}
.type-opt.on{border-color:var(--tc);background:rgba(99,102,241,.08)}
.type-opt input{display:none}
.type-ico{font-size:18px;margin-bottom:3px;display:block}
.type-lbl{font-size:9.5px;font-weight:700;color:var(--txt2)}
.type-opt.on .type-lbl{color:var(--tc)}
.type-mode{font-size:8px;position:absolute;top:4px;right:4px;padding:1px 4px;border-radius:3px;font-weight:700}
.type-mode.int{background:rgba(34,197,94,.15);color:#4ade80}
.type-mode.ext{background:rgba(59,130,246,.12);color:#60a5fa}

/* ── SECTION DIV ── */
.sec-div{display:flex;align-items:center;gap:9px;margin:16px 0 12px;font-size:10.5px;font-weight:700;color:var(--txt2);text-transform:uppercase;letter-spacing:.8px}
.sec-div::after{content:'';flex:1;height:1px;background:var(--bdr)}

/* ── QUIZ/SURVEY BLOCKS ── */
.qblock{background:var(--bg);border:1px solid var(--bdr);border-radius:10px;padding:13px;margin-bottom:9px}
.qblock-hdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
.qblock-n{font-size:10px;font-weight:800;color:var(--tc);background:rgba(99,102,241,.12);padding:2px 8px;border-radius:5px;text-transform:uppercase}
.qblock-del{width:26px;height:26px;border-radius:6px;background:rgba(239,68,68,.1);border:none;color:var(--red);font-size:11px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:.15s}
.qblock-del:hover{background:var(--red);color:#fff}
.sqblock{background:var(--bg);border:1px solid var(--bdr);border-radius:10px;padding:13px;margin-bottom:9px}
.sqblock-hdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}

/* ── FILE UPLOAD ── */
.fu-label{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:18px;background:var(--bg);border:2px dashed var(--bdr);border-radius:10px;cursor:pointer;transition:.15s;text-align:center;gap:5px}
.fu-label:hover{border-color:rgba(99,102,241,.4)}
.fu-label input{display:none}
.fu-label i{font-size:22px;color:var(--tc)}
.fu-label span{font-size:11.5px;color:var(--txt2)}

/* ── INFO BOX ── */
.ibox{background:rgba(59,130,246,.06);border-left:3px solid var(--blu);border-radius:0 9px 9px 0;padding:9px 12px;font-size:11.5px;color:var(--txt2);margin-bottom:12px;line-height:1.6}
.ibox strong{color:var(--txt)}
.dyn{display:none}.dyn.on{display:block}
.add-q-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:rgba(99,102,241,.1);border:1px dashed rgba(99,102,241,.3);border-radius:9px;color:var(--tc);font-size:12px;font-weight:700;cursor:pointer;transition:.15px;margin-top:4px}
.add-q-btn:hover{background:rgba(99,102,241,.18)}

/* ═══════════════════════════════════
   BOLD NOTIFICATION SYSTEM
═══════════════════════════════════ */
@keyframes ntSlideDown{0%{opacity:0;transform:translateX(-50%) translateY(-20px) scale(.93)}60%{transform:translateX(-50%) translateY(3px) scale(1.01)}100%{opacity:1;transform:translateX(-50%) translateY(0) scale(1)}}
@keyframes ntSlideUp{0%{opacity:1;transform:translateX(-50%) translateY(0)}100%{opacity:0;transform:translateX(-50%) translateY(-14px) scale(.95)}}
@keyframes ntProgress{from{width:100%}to{width:0%}}
@keyframes ntPop{0%,100%{transform:scale(1)}50%{transform:scale(1.2)}}
@keyframes ntShake{0%,100%{transform:translateX(-50%)}20%{transform:translateX(calc(-50% - 4px))}40%{transform:translateX(calc(-50% + 4px))}60%{transform:translateX(calc(-50% - 3px))}80%{transform:translateX(calc(-50% + 3px))}}

.nt{position:fixed;top:14px;left:50%;transform:translateX(-50%) translateY(-20px) scale(.93);opacity:0;min-width:min(360px,92vw);max-width:92vw;z-index:99999;pointer-events:none;border-radius:16px;overflow:hidden;box-shadow:0 16px 48px rgba(0,0,0,.45),0 4px 16px rgba(0,0,0,.25);font-family:inherit}
.nt.nt-show{pointer-events:all;animation:ntSlideDown .42s cubic-bezier(.22,1,.36,1) forwards}
.nt.nt-hide{animation:ntSlideUp .28s ease forwards}
.nt.nt-err-anim{animation:ntSlideDown .42s cubic-bezier(.22,1,.36,1) forwards,ntShake .4s .42s ease}
.nt-inner{display:flex;align-items:flex-start;gap:12px;padding:14px 14px 10px;position:relative}
.nt-success .nt-inner{background:linear-gradient(135deg,#052e16,#064e3b);border:1px solid rgba(52,211,153,.2);border-bottom:none}
.nt-error   .nt-inner{background:linear-gradient(135deg,#450a0a,#7f1d1d);border:1px solid rgba(248,113,113,.2);border-bottom:none}
.nt-warning .nt-inner{background:linear-gradient(135deg,#1c1000,#451a03);border:1px solid rgba(251,191,36,.2);border-bottom:none}
.nt-info    .nt-inner{background:linear-gradient(135deg,#0c1445,#1e3a8a);border:1px solid rgba(96,165,250,.2);border-bottom:none}
.nt-ico{width:38px;height:38px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:16px;color:#fff;animation:ntPop .38s .28s cubic-bezier(.34,1.56,.64,1) both}
.nt-success .nt-ico{background:linear-gradient(135deg,#10b981,#059669);box-shadow:0 0 16px rgba(16,185,129,.45)}
.nt-error   .nt-ico{background:linear-gradient(135deg,#ef4444,#dc2626);box-shadow:0 0 16px rgba(239,68,68,.45)}
.nt-warning .nt-ico{background:linear-gradient(135deg,#f59e0b,#d97706);box-shadow:0 0 16px rgba(245,158,11,.45)}
.nt-info    .nt-ico{background:linear-gradient(135deg,#3b82f6,#2563eb);box-shadow:0 0 16px rgba(59,130,246,.45)}
.nt-txt{flex:1;min-width:0;padding-top:2px}
.nt-label{font-size:10px;font-weight:800;letter-spacing:1.2px;text-transform:uppercase;margin-bottom:3px;opacity:.75}
.nt-success .nt-label{color:#6ee7b7}.nt-error .nt-label{color:#fca5a5}.nt-warning .nt-label{color:#fde68a}.nt-info .nt-label{color:#bfdbfe}
.nt-msg{font-size:13.5px;font-weight:700;color:#fff;line-height:1.4;word-break:break-word}
.nt-cls{width:26px;height:26px;border-radius:7px;flex-shrink:0;background:rgba(255,255,255,.1);border:none;color:rgba(255,255,255,.6);font-size:13px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:.15s;margin-top:1px}
.nt-cls:hover{background:rgba(255,255,255,.22);color:#fff}
.nt-bar{height:3px;border:1px solid transparent;border-top:none}
.nt-bar-fill{height:100%;animation:ntProgress linear forwards}
.nt-success .nt-bar{border-color:rgba(52,211,153,.2);background:rgba(16,185,129,.12)}.nt-success .nt-bar-fill{background:linear-gradient(90deg,#10b981,#34d399)}
.nt-error   .nt-bar{border-color:rgba(248,113,113,.2);background:rgba(239,68,68,.12)}.nt-error   .nt-bar-fill{background:linear-gradient(90deg,#ef4444,#f87171)}
.nt-warning .nt-bar{border-color:rgba(251,191,36,.2);background:rgba(245,158,11,.12)}.nt-warning .nt-bar-fill{background:linear-gradient(90deg,#f59e0b,#fbbf24)}
.nt-info    .nt-bar{border-color:rgba(96,165,250,.2);background:rgba(59,130,246,.12)}.nt-info    .nt-bar-fill{background:linear-gradient(90deg,#3b82f6,#60a5fa)}
</style>
</head>
<body>
<div class="adm">

<?php if($flash):?>
<div class="fl <?= $flash['type'] ?>">
    <i class="fa-solid fa-<?= $flash['type']==='success'?'circle-check':($flash['type']==='error'?'circle-xmark':'triangle-exclamation') ?>"></i>
    <?= htmlspecialchars($flash['message']) ?>
</div>
<?php endif;?>

<!-- STATS -->
<div class="stats">
<?php
$scs=[
    ['Total Tasks',$stats['total']??0,'fa-layer-group','#6366f1','99,102,241'],
    ['Active',$stats['active']??0,'fa-check-circle','#22c55e','34,197,94'],
    ['Pending',$stats['pending']??0,'fa-clock','#f59e0b','245,158,11'],
    ['Paid Out','Ksh '.number_format($stats['paid']??0),'fa-coins','#a855f7','168,85,247'],
    ['Internal',$stats['internal']??0,'fa-server','#3b82f6','59,130,246'],
    ['External',$stats['external']??0,'fa-link','#06b6d4','6,182,212'],
];
foreach($scs as $sc):?>
<div class="sc" style="--sc-color:<?=$sc[3]?>;--sc-rgb:<?=$sc[4]?>">
    <div class="sc-ico"><i class="fa-solid <?=$sc[2]?>"></i></div>
    <div class="sc-num"><?=$sc[1]?></div>
    <div class="sc-lbl"><?=$sc[0]?></div>
</div>
<?php endforeach;?>
</div>

<!-- NAV TABS -->
<div class="nav-tabs">
    <a href="?view=tasks"       class="ntab <?=$view==='tasks'?'on':''?>"><i class="fa-solid fa-list-check"></i> All Tasks <span class="cnt"><?=$stats['total']??0?></span></a>
    <a href="?view=approvals"   class="ntab <?=$view==='approvals'?'on':''?>"><i class="fa-solid fa-clipboard-check"></i> Approvals <span class="cnt"><?=$stats['pending']??0?></span></a>
    <a href="?view=completions" class="ntab <?=$view==='completions'?'on':''?>"><i class="fa-solid fa-history"></i> History</a>
</div>

<?php if($view==='tasks'): ?>
<div class="toolbar">
    <form method="GET" style="display:contents">
        <input type="hidden" name="view" value="tasks">
        <div class="tb-search"><i class="fa-solid fa-magnifying-glass"></i><input type="text" name="search" placeholder="Search tasks…" value="<?=htmlspecialchars($search)?>" onchange="this.form.submit()"></div>
        <select name="type" class="tb-sel" onchange="this.form.submit()">
            <option value="">All Types</option>
            <?php foreach(['trivia','quiz','blog','survey','meme','transcription','video','ads','chat','spin'] as $t):?>
            <option value="<?=$t?>" <?=$filterType===$t?'selected':''?>><?=ucfirst($t)?></option>
            <?php endforeach;?>
        </select>
        <select name="status" class="tb-sel" onchange="this.form.submit()">
            <option value="">All Status</option>
            <option value="active" <?=$filterStatus==='active'?'selected':''?>>Active</option>
            <option value="inactive" <?=$filterStatus==='inactive'?'selected':''?>>Inactive</option>
        </select>
    </form>
    <button class="btn btn-ghost" onclick="toggleBulk()"><i class="fa-solid fa-check-square"></i> Bulk</button>
    <button class="btn btn-primary" onclick="openDrawer()"><i class="fa-solid fa-plus"></i> New Task</button>
</div>

<div class="bulk-bar" id="bulkBar">
    <div class="bulk-info"><span id="selCount">0</span> selected</div>
    <div class="bulk-btns">
        <button class="bulk-btn" onclick="doBulk('activate')"><i class="fa-solid fa-check"></i> Activate</button>
        <button class="bulk-btn" onclick="doBulk('deactivate')"><i class="fa-solid fa-ban"></i> Deactivate</button>
        <button class="bulk-btn" onclick="doBulk('delete')"><i class="fa-solid fa-trash"></i> Delete</button>
        <button class="bulk-btn" onclick="clearSel()"><i class="fa-solid fa-xmark"></i> Clear</button>
    </div>
</div>

<div class="tasks-grid" id="tasksGrid">
<?php if($tasks&&mysqli_num_rows($tasks)>0): while($t=mysqli_fetch_assoc($tasks)):
    $typeColors=['trivia'=>'#8b5cf6','quiz'=>'#6366f1','blog'=>'#10b981','survey'=>'#06b6d4','video'=>'#ef4444','ads'=>'#f97316','chat'=>'#3b82f6','meme'=>'#ec4899','transcription'=>'#f59e0b','spin'=>'#14b8a6'];
    $tc2=$typeColors[$t['task_type']]??'#6366f1';
?>
<div class="tc" id="tc<?=$t['id']?>" data-id="<?=$t['id']?>">
    <?php if(!empty($t['task_image'])):?><img src="../<?=htmlspecialchars($t['task_image'])?>" class="tc-img-strip" alt="" onerror="this.style.display='none'"><?php endif;?>
    <div class="tc-body">
        <div class="tc-top">
            <input type="checkbox" class="tc-chk" data-id="<?=$t['id']?>" onchange="onChk(this)">
            <div class="tc-title"><?=htmlspecialchars($t['title'])?></div>
            <div class="tc-id">#<?=$t['id']?></div>
        </div>
        <div class="tc-badges">
            <span class="badge b-type" style="background:<?=$tc2?>22;color:<?=$tc2?>"><?=strtoupper($t['task_type'])?></span>
            <span class="badge <?=$t['content_type']==='internal'?'b-int':'b-ext'?>"><i class="fa-solid fa-<?=$t['content_type']==='internal'?'server':'link'?>"></i><?=ucfirst($t['content_type'])?></span>
            <span class="badge <?=$t['status']==='active'?'b-active':'b-inactive'?>"><i class="fa-solid fa-<?=$t['status']==='active'?'circle-check':'circle-xmark'?>"></i><?=ucfirst($t['status'])?></span>
            <?php if($t['show_in_sidebar']):?><span class="badge b-sidebar"><i class="fa-solid fa-thumbtack"></i>Sidebar</span><?php endif;?>
            <?php if($t['enable_timer']):?><span class="badge b-timer"><i class="fa-solid fa-stopwatch"></i><?=$t['min_duration_seconds']?>s</span><?php endif;?>
        </div>
        <?php if(!empty($t['task_url'])):?><div class="tc-url"><i class="fa-solid fa-link"></i><a href="<?=htmlspecialchars($t['task_url'])?>" target="_blank"><?=htmlspecialchars($t['task_url'])?></a></div><?php endif;?>
        <div class="tc-meta">
            <div class="tm"><i class="fa-solid fa-coins"></i>Ksh <strong><?=number_format($t['reward'],2)?></strong></div>
            <div class="tm"><i class="fa-solid fa-check"></i><strong><?=number_format($t['total_completions']??0)?></strong> done</div>
            <div class="tm"><i class="fa-solid fa-users"></i><strong><?=number_format($t['unique_users']??0)?></strong> users</div>
            <div class="tm"><i class="fa-solid fa-money-bill"></i>Ksh <strong><?=number_format($t['total_paid']??0,0)?></strong></div>
        </div>
        <div class="tc-actions">
            <button class="ta ta-edit" onclick="editTask(<?=$t['id']?>)"><i class="fa-solid fa-pen"></i>Edit</button>
            <form method="POST" style="display:contents"><input type="hidden" name="form_action" value="toggle"><input type="hidden" name="task_id" value="<?=$t['id']?>"><button type="submit" class="ta ta-toggle"><i class="fa-solid fa-power-off"></i><?=$t['status']==='active'?'Deactivate':'Activate'?></button></form>
            <form method="POST" style="display:contents"><input type="hidden" name="form_action" value="duplicate"><input type="hidden" name="task_id" value="<?=$t['id']?>"><button type="submit" class="ta ta-copy"><i class="fa-solid fa-copy"></i>Clone</button></form>
            <form method="POST" style="display:contents" onsubmit="return confirm('Delete this task and all its data?')"><input type="hidden" name="form_action" value="delete"><input type="hidden" name="task_id" value="<?=$t['id']?>"><button type="submit" class="ta ta-del"><i class="fa-solid fa-trash"></i>Delete</button></form>
        </div>
    </div>
</div>
<?php endwhile; else:?>
<div class="empty"><i class="fa-solid fa-clipboard-list"></i><div class="empty-t">No tasks found</div><div class="empty-s">Create your first task</div></div>
<?php endif;?>
</div>

<?php elseif($view==='approvals'): ?>
<div class="tasks-grid">
<?php if($pending&&mysqli_num_rows($pending)>0): while($c=mysqli_fetch_assoc($pending)):?>
<div class="comp-item">
    <div class="comp-title"><?=htmlspecialchars($c['ttl'])?></div>
    <div class="tc-badges" style="margin-bottom:8px"><span class="badge b-type"><?=strtoupper($c['task_type'])?></span><span class="badge" style="background:rgba(245,158,11,.1);color:#fbbf24"><i class="fa-solid fa-clock"></i>Pending</span></div>
    <div class="comp-meta"><div class="cm"><i class="fa-solid fa-user"></i><?=htmlspecialchars($c['username'])?> — <?=htmlspecialchars($c['email'])?></div><div class="cm"><i class="fa-solid fa-calendar"></i><?=date('M j, Y g:i A',strtotime($c['created_at']))?></div><div class="cm"><i class="fa-solid fa-coins"></i>Ksh <?=number_format($c['reward_earned'],2)?></div></div>
    <?php if($c['screenshot']):?><img src="../<?=$c['screenshot']?>" class="comp-proof" alt=""><?php endif;?>
    <div class="comp-actions"><button class="btn btn-green" onclick="approve(<?=$c['id']?>,'completed')"><i class="fa-solid fa-check"></i>Approve</button><button class="btn btn-red" onclick="approve(<?=$c['id']?>,'rejected')"><i class="fa-solid fa-xmark"></i>Reject</button></div>
</div>
<?php endwhile; else:?><div class="empty"><i class="fa-solid fa-clipboard-check"></i><div class="empty-t">All caught up!</div><div class="empty-s">No pending approvals</div></div><?php endif;?>
</div>

<?php elseif($view==='completions'): ?>
<div class="toolbar">
    <form method="GET" style="display:contents">
        <input type="hidden" name="view" value="completions">
        <select name="cs" class="tb-sel" onchange="this.form.submit()"><option value="all" <?=($cs??'all')==='all'?'selected':''?>>All Status</option><option value="pending" <?=($cs??'')==='pending'?'selected':''?>>Pending</option><option value="completed" <?=($cs??'')==='completed'?'selected':''?>>Completed</option><option value="rejected" <?=($cs??'')==='rejected'?'selected':''?>>Rejected</option></select>
        <select name="tid" class="tb-sel" onchange="this.form.submit()"><option value="">All Tasks</option><?php $allT=mysqli_query($conn,"SELECT id,title FROM tasks ORDER BY title"); while($tt=mysqli_fetch_assoc($allT)):?><option value="<?=$tt['id']?>" <?=($ctid??0)==$tt['id']?'selected':''?>><?=htmlspecialchars($tt['title'])?></option><?php endwhile;?></select>
    </form>
</div>
<div class="tasks-grid">
<?php if($allComps&&mysqli_num_rows($allComps)>0): while($co=mysqli_fetch_assoc($allComps)):
    $sc2=['completed'=>['b-active','check'],'pending'=>['','clock'],'rejected'=>['b-inactive','xmark']];
    $scl=$sc2[$co['status']]??['','circle'];
?>
<div class="comp-item">
    <div class="comp-title"><?=htmlspecialchars($co['ttl'])?></div>
    <div class="tc-badges" style="margin-bottom:8px"><span class="badge b-type"><?=strtoupper($co['task_type'])?></span><span class="badge <?=$scl[0]?>"><i class="fa-solid fa-<?=$scl[1]?>"></i><?=ucfirst($co['status'])?></span></div>
    <div class="comp-meta"><div class="cm"><i class="fa-solid fa-user"></i><?=htmlspecialchars($co['username'])?></div><div class="cm"><i class="fa-solid fa-calendar"></i><?=date('M j, Y',strtotime($co['created_at']))?></div><div class="cm"><i class="fa-solid fa-coins"></i>Ksh <?=number_format($co['reward_earned'],2)?></div><div class="cm"><i class="fa-solid fa-hashtag"></i>ID <?=$co['id']?></div></div>
    <?php if($co['screenshot']):?><img src="../<?=$co['screenshot']?>" class="comp-proof" alt=""><?php endif;?>
</div>
<?php endwhile; else:?><div class="empty"><i class="fa-solid fa-history"></i><div class="empty-t">No completions found</div></div><?php endif;?>
</div>
<?php endif;?>
</div>

<!-- DRAWER OVERLAY + DRAWER -->
<div class="drawer-overlay" id="dOverlay" onclick="closeDrawer()"></div>
<div class="drawer" id="drawer">
    <div class="drawer-head">
        <div class="drawer-title" id="drawerTitle">New Task</div>
        <button class="drawer-cls" onclick="closeDrawer()"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <div class="drawer-body">
        <!-- ★ KEY FIX: NO onsubmit here — validation handled manually in JS ★ -->
        <form method="POST" id="taskForm" enctype="multipart/form-data">
            <input type="hidden" name="form_action" id="fAction" value="add">
            <input type="hidden" name="task_id" id="fTaskId">
            <input type="hidden" name="existing_image" id="fExistImg">
            <input type="hidden" name="remove_image" id="fRemoveImg" value="0">

            <div class="sec-div"><i class="fa-solid fa-shapes"></i>Task Type</div>
            <div class="type-grid">
<?php
$types2=[['trivia','fa-brain','Trivia','int'],['quiz','fa-circle-question','Quiz','int'],['blog','fa-pen-nib','Blog','int'],['survey','fa-chart-bar','Survey','int'],['meme','fa-image','Meme','int'],['transcription','fa-microphone','Trans','int'],['video','fa-clapperboard','Video','ext'],['ads','fa-rectangle-ad','Ads','ext'],['chat','fa-message','Chat','ext'],['spin','fa-rotate','Spin','ext']];
foreach($types2 as $tp):?>
                <label class="type-opt <?=$tp[0]==='trivia'?'on':''?>" id="topt_<?=$tp[0]?>">
                    <input type="radio" name="task_type" value="<?=$tp[0]?>" <?=$tp[0]==='trivia'?'checked':''?> onchange="onTypeChange()">
                    <span class="type-mode <?=$tp[3]?>"><?=strtoupper($tp[3])?></span>
                    <span class="type-ico"><i class="fa-solid <?=$tp[1]?>"></i></span>
                    <span class="type-lbl"><?=$tp[2]?></span>
                </label>
<?php endforeach;?>
            </div>

            <div class="ibox" id="typeInfoBox"><strong>Internal task</strong> — content is created here (questions, prompts, etc.)</div>

            <div class="sec-div"><i class="fa-solid fa-circle-info"></i>Basic Info</div>
            <div class="fg"><label class="fl2">Title *</label><input type="text" name="title" id="fTitle" class="fi" placeholder="e.g., Python Quiz — Level 1"></div>
            <div class="frow">
                <div class="fg"><label class="fl2">Reward (Ksh) *</label><input type="number" name="reward" id="fReward" class="fi" step="0.01" min="0.01" placeholder="50.00"></div>
                <div class="fg"><label class="fl2">Difficulty</label><select name="difficulty" id="fDifficulty" class="fsel2"><option value="easy">Easy</option><option value="medium">Medium</option><option value="hard">Hard</option></select></div>
            </div>
            <div class="fg"><label class="fl2">Description</label><textarea name="description" id="fDesc" class="fta" rows="2" placeholder="Short description…"></textarea></div>
            <div class="fg"><label class="fl2">Instructions</label><textarea name="instructions" id="fInstr" class="fta" rows="3" placeholder="Step-by-step instructions…"></textarea></div>

            <div class="dyn" id="extFields">
                <div class="fg"><label class="fl2">Task URL *</label><input type="url" name="task_url" id="fUrl" class="fi" placeholder="https://…"></div>
            </div>

            <div class="sec-div"><i class="fa-solid fa-image"></i>Task Image</div>
            <div class="fg">
                <label class="fu-label"><input type="file" name="task_image" id="fImage" accept="image/*" onchange="prevImg(event)"><i class="fa-solid fa-cloud-arrow-up"></i><span>Click to upload image (optional)</span></label>
                <div id="imgPrev" style="position:relative;display:none;margin-top:8px">
                    <img id="imgPrevEl" src="" style="max-width:100%;border-radius:9px;border:1px solid var(--bdr);display:block">
                    <button type="button" onclick="removeImg()" style="position:absolute;top:6px;right:6px;width:26px;height:26px;background:var(--red);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:12px;display:flex;align-items:center;justify-content:center"><i class="fa-solid fa-xmark"></i></button>
                </div>
            </div>

            <div class="sec-div"><i class="fa-solid fa-sliders"></i>Limits & Settings</div>
            <div class="frow">
                <div class="fg"><label class="fl2">Daily Limit/User</label><input type="number" name="daily_limit_per_user" id="fDailyLim" class="fi" min="1" value="1"></div>
                <div class="fg"><label class="fl2">Total Completions</label><input type="number" name="total_limit" id="fTotalLim" class="fi" min="1" placeholder="Unlimited"></div>
            </div>
            <div class="frow">
                <div class="fg"><label class="fl2">Category</label><input type="text" name="category" id="fCat" class="fi" placeholder="general"></div>
                <div class="fg"><label class="fl2">Pass % (Quiz)</label><input type="number" name="pass_percentage" id="fPassPct" class="fi" min="0" max="100" value="70"></div>
            </div>
            <div class="frow">
                <div class="fg"><label class="fl2">Timer Duration (sec)</label><input type="number" name="min_duration_seconds" id="fTimer" class="fi" min="0" value="0"></div>
                <div class="fg" style="display:flex;align-items:flex-end;padding-bottom:13px"><label class="fchk-row" style="margin:0;flex:1"><input type="checkbox" name="enable_timer" id="fEnTimer"><span>Enable Timer</span></label></div>
            </div>
            <label class="fchk-row"><input type="checkbox" name="is_active" id="fActive" checked><span>Active (visible to users)</span></label>
            <label class="fchk-row"><input type="checkbox" name="show_in_sidebar" id="fSidebar"><span>Show in Sidebar (Featured)</span></label>
            <label class="fchk-row"><input type="checkbox" name="auto_approve" id="fAutoApp"><span>Auto-approve completions</span></label>
            <label class="fchk-row"><input type="checkbox" name="requires_proof" id="fProof"><span>Requires proof screenshot</span></label>

            <!-- QUIZ/TRIVIA -->
            <div class="dyn" id="quizSection">
                <div class="sec-div"><i class="fa-solid fa-brain"></i>Quiz Questions</div>
                <div id="quizCont"></div>
                <button type="button" class="add-q-btn" onclick="addQ()"><i class="fa-solid fa-plus"></i>Add Question</button>
            </div>

            <!-- BLOG -->
            <div class="dyn" id="blogSection">
                <div class="sec-div"><i class="fa-solid fa-pen-nib"></i>Blog Requirements</div>
                <div class="fg"><label class="fl2">Topic</label><input type="text" name="blog_topic" id="fBTopic" class="fi" placeholder="e.g., AI Trends in 2025"></div>
                <div class="frow"><div class="fg"><label class="fl2">Min Words</label><input type="number" name="blog_min_words" id="fBMin" class="fi" value="300" min="50"></div><div class="fg"><label class="fl2">Max Words</label><input type="number" name="blog_max_words" id="fBMax" class="fi" placeholder="Optional"></div></div>
                <div class="fg"><label class="fl2">Keywords</label><input type="text" name="blog_keywords" id="fBKw" class="fi" placeholder="AI, tech, trends"></div>
                <div class="fg"><label class="fl2">Guidelines</label><textarea name="blog_guidelines" id="fBGuide" class="fta" rows="3" placeholder="Writing guidelines…"></textarea></div>
                <div class="fg"><label class="fl2">Sample Outline</label><textarea name="blog_sample_outline" id="fBOutline" class="fta" rows="3" placeholder="1. Intro&#10;2. Body&#10;3. Conclusion"></textarea></div>
                <label class="fchk-row"><input type="checkbox" name="enable_word_count" id="fBWordCnt" checked><span>Validate word count</span></label>
            </div>

            <!-- SURVEY -->
            <div class="dyn" id="surveySection">
                <div class="sec-div"><i class="fa-solid fa-chart-bar"></i>Survey Questions</div>
                <div id="surveyCont"></div>
                <button type="button" class="add-q-btn" onclick="addSQ()"><i class="fa-solid fa-plus"></i>Add Question</button>
            </div>

            <!-- MEME -->
            <div class="dyn" id="memeSection">
                <div class="sec-div"><i class="fa-solid fa-image"></i>Meme Requirements</div>
                <div class="fg"><label class="fl2">Theme</label><input type="text" name="meme_theme" id="fMTheme" class="fi" placeholder="e.g., Funny Tech Memes"></div>
                <div class="frow"><div class="fg"><label class="fl2">Formats</label><input type="text" name="meme_allowed_formats" id="fMFormats" class="fi" value="jpg,png,gif"></div><div class="fg"><label class="fl2">Max Size (MB)</label><input type="number" name="meme_max_file_size" id="fMSize" class="fi" value="5" min="1"></div></div>
                <div class="fg"><label class="fl2">Min Dimensions</label><input type="text" name="meme_min_dimensions" id="fMDim" class="fi" placeholder="800x600"></div>
                <div class="fg"><label class="fl2">Guidelines</label><textarea name="meme_guidelines" id="fMGuide" class="fta" rows="3" placeholder="Meme guidelines…"></textarea></div>
            </div>

            <!-- TRANSCRIPTION -->
            <div class="dyn" id="transSection">
                <div class="sec-div"><i class="fa-solid fa-microphone"></i>Transcription Content</div>
                <div class="fg"><label class="fl2">Audio URL</label><input type="url" name="trans_audio_url" id="fTAudio" class="fi" placeholder="https://…/audio.mp3"></div>
                <div class="fg"><label class="fl2">Video URL</label><input type="url" name="trans_video_url" id="fTVideo" class="fi" placeholder="https://youtube.com/…"></div>
                <div class="frow"><div class="fg"><label class="fl2">Duration (sec)</label><input type="number" name="trans_duration_seconds" id="fTDur" class="fi" placeholder="Optional"></div><div class="fg"><label class="fl2">Language</label><input type="text" name="trans_language" id="fTLang" class="fi" value="English"></div></div>
                <div class="frow"><div class="fg"><label class="fl2">Expected Words</label><input type="number" name="trans_expected_word_count" id="fTWords" class="fi" placeholder="Optional"></div><div class="fg"><label class="fl2">Difficulty</label><select name="trans_difficulty_level" id="fTDiff" class="fsel2"><option value="easy">Easy</option><option value="medium" selected>Medium</option><option value="hard">Hard</option></select></div></div>
            </div>

        </form>
    </div>
    <div class="drawer-foot">
        <!-- ★ KEY FIX: Button calls saveTask() not requestSubmit() ★ -->
        <button type="button" class="btn btn-primary" style="width:100%;height:42px;font-size:14px" onclick="saveTask()">
            <i class="fa-solid fa-floppy-disk"></i> Save Task
        </button>
    </div>
</div>

<!-- NOTIFICATION -->
<div class="nt" id="nt" role="alert" aria-live="assertive">
    <div class="nt-inner">
        <div class="nt-ico" id="nt-ico"></div>
        <div class="nt-txt"><div class="nt-label" id="nt-label"></div><div class="nt-msg" id="nt-msg"></div></div>
        <button class="nt-cls" id="nt-cls"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <div class="nt-bar"><div class="nt-bar-fill" id="nt-bar-fill"></div></div>
</div>

<script>
const INTERNAL=['trivia','quiz','blog','survey','meme','transcription'];
let qCount=0,sqCount=0,bulkMode=false,sel=new Set();

/* ══════════════════════════════════════════
   NOTIFICATION SYSTEM
══════════════════════════════════════════ */
var _ntTimer=null,_ntHide=null;
function toast(msg,type){
    // Normalise type aliases
    if(type==='err')type='error';
    if(type==='warn')type='warning';
    type=type||'success';
    var nt=document.getElementById('nt');
    var ico=document.getElementById('nt-ico');
    var lbl=document.getElementById('nt-label');
    var m=document.getElementById('nt-msg');
    var bar=document.getElementById('nt-bar-fill');
    var cls=document.getElementById('nt-cls');
    clearTimeout(_ntTimer);clearTimeout(_ntHide);
    nt.className='nt'; void nt.offsetWidth;
    var cfg={
        success:{cls:'nt-success',lbl:'Success',ico:'fa-circle-check',dur:4500},
        error:  {cls:'nt-error',  lbl:'Error',  ico:'fa-circle-xmark',dur:5500},
        warning:{cls:'nt-warning',lbl:'Warning', ico:'fa-triangle-exclamation',dur:5000},
        info:   {cls:'nt-info',   lbl:'Info',    ico:'fa-circle-info',dur:4500},
    }[type]||{cls:'nt-success',lbl:'Notice',ico:'fa-circle-check',dur:4500};
    nt.classList.add(cfg.cls);
    ico.innerHTML='<i class="fa-solid '+cfg.ico+'"></i>';
    lbl.textContent=cfg.lbl;
    m.textContent=msg;
    bar.style.animation='none'; void bar.offsetWidth;
    bar.style.animation='ntProgress '+cfg.dur+'ms linear forwards';
    if(type==='error'){nt.classList.add('nt-err-anim');}
    else{nt.classList.add('nt-show');}
    _ntTimer=setTimeout(ntHide,cfg.dur);
    cls.onclick=function(){clearTimeout(_ntTimer);ntHide();};
}
function ntHide(){
    var nt=document.getElementById('nt');
    nt.classList.add('nt-hide');
    _ntHide=setTimeout(function(){nt.className='nt';},300);
}

/* ══════════════════════════════════════════
   DRAWER
══════════════════════════════════════════ */
function openDrawer(){
    document.getElementById('drawerTitle').textContent='New Task';
    document.getElementById('fAction').value='add';
    document.getElementById('fTaskId').value='';
    document.getElementById('fExistImg').value='';
    document.getElementById('fRemoveImg').value='0';
    document.getElementById('taskForm').reset();
    qCount=0;sqCount=0;
    document.getElementById('quizCont').innerHTML='';
    document.getElementById('surveyCont').innerHTML='';
    document.getElementById('imgPrev').style.display='none';
    document.querySelector('input[name="task_type"][value="trivia"]').checked=true;
    onTypeChange();
    document.getElementById('fActive').checked=true;
    showDrawer();
}
function showDrawer(){
    document.getElementById('drawer').classList.add('on');
    document.getElementById('dOverlay').classList.add('on');
    document.body.style.overflow='hidden';
}
function closeDrawer(){
    document.getElementById('drawer').classList.remove('on');
    var ov=document.getElementById('dOverlay');
    ov.style.opacity='0';
    setTimeout(function(){ov.classList.remove('on');ov.style.opacity='';},300);
    document.body.style.overflow='';
}

/* ══════════════════════════════════════════
   ★ THE CORE FIX: saveTask()
   1. Strip required from ALL hidden .dyn sections
   2. Validate manually (title + reward)
   3. Submit via form.submit() — bypasses browser
      HTML5 validation entirely (no more blocked saves)
══════════════════════════════════════════ */
function saveTask(){
    var form=document.getElementById('taskForm');

    // Step 1: Remove required from every hidden dynamic section
    form.querySelectorAll('.dyn:not(.on) input, .dyn:not(.on) select, .dyn:not(.on) textarea').forEach(function(el){
        el.removeAttribute('required');
        el.dataset.reqStripped='1';
    });

    // Step 2: Simple manual validation for the always-visible fields
    var title=document.getElementById('fTitle').value.trim();
    var reward=parseFloat(document.getElementById('fReward').value);
    if(!title){toast('Please enter a task title.','error');document.getElementById('fTitle').focus();return;}
    if(!reward||reward<=0){toast('Please enter a valid reward amount.','error');document.getElementById('fReward').focus();return;}

    // Step 3: External tasks need a URL
    var taskType=form.querySelector('input[name="task_type"]:checked').value;
    if(!INTERNAL.includes(taskType)){
        var url=document.getElementById('fUrl').value.trim();
        if(!url){toast('External tasks require a URL.','error');document.getElementById('fUrl').focus();return;}
    }

    // Step 4: Submit — bypasses HTML5 validation, PHP does server-side validation
    form.submit();
}

/* ══════════════════════════════════════════
   TYPE CHANGE
══════════════════════════════════════════ */
function onTypeChange(){
    var t=document.querySelector('input[name="task_type"]:checked').value;
    var isInt=INTERNAL.includes(t);
    document.querySelectorAll('.type-opt').forEach(function(o){o.classList.remove('on');});
    document.getElementById('topt_'+t).classList.add('on');
    document.getElementById('typeInfoBox').innerHTML=isInt
        ?'<strong>Internal task</strong> — fill in the content below (questions, blog details, etc.)'
        :'<strong>External task</strong> — users will be sent to your URL to complete the task';
    var ef=document.getElementById('extFields');
    var fu=document.getElementById('fUrl');
    if(isInt){ef.classList.remove('on');fu.removeAttribute('required');}
    else{ef.classList.add('on');}
    ['quizSection','blogSection','surveySection','memeSection','transSection'].forEach(function(s){document.getElementById(s).classList.remove('on');});
    if(t==='trivia'||t==='quiz'){document.getElementById('quizSection').classList.add('on');if(qCount===0)addQ();}
    else if(t==='blog')document.getElementById('blogSection').classList.add('on');
    else if(t==='survey'){document.getElementById('surveySection').classList.add('on');if(sqCount===0)addSQ();}
    else if(t==='meme')document.getElementById('memeSection').classList.add('on');
    else if(t==='transcription')document.getElementById('transSection').classList.add('on');
}

/* ══════════════════════════════════════════
   QUIZ + SURVEY BUILDERS
══════════════════════════════════════════ */
function addQ(){
    var c=document.getElementById('quizCont'),i=qCount++;
    c.insertAdjacentHTML('beforeend','<div class="qblock" id="qb'+i+'"><div class="qblock-hdr"><span class="qblock-n">Question '+(i+1)+'</span><button type="button" class="qblock-del" onclick="rmQ('+i+')"><i class="fa-solid fa-trash"></i></button></div><div class="fg"><label class="fl2">Question *</label><input type="text" name="quiz_questions['+i+'][question]" class="fi" placeholder="Your question…"></div><div class="frow"><div class="fg"><label class="fl2">Option A *</label><input type="text" name="quiz_questions['+i+'][option_a]" class="fi" placeholder="Option A"></div><div class="fg"><label class="fl2">Option B *</label><input type="text" name="quiz_questions['+i+'][option_b]" class="fi" placeholder="Option B"></div></div><div class="frow"><div class="fg"><label class="fl2">Option C</label><input type="text" name="quiz_questions['+i+'][option_c]" class="fi" placeholder="Optional"></div><div class="fg"><label class="fl2">Option D</label><input type="text" name="quiz_questions['+i+'][option_d]" class="fi" placeholder="Optional"></div></div><div class="frow"><div class="fg"><label class="fl2">Correct Answer *</label><select name="quiz_questions['+i+'][correct_answer]" class="fsel2"><option value="">Select…</option><option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option></select></div><div class="fg"><label class="fl2">Points</label><input type="number" name="quiz_questions['+i+'][points]" class="fi" value="1" min="1"></div></div><div class="fg"><label class="fl2">Explanation</label><textarea name="quiz_questions['+i+'][explanation]" class="fta" style="min-height:55px" placeholder="Why is this correct? (optional)"></textarea></div></div>');
}
function rmQ(i){var e=document.getElementById('qb'+i);if(e)e.remove();}

function addSQ(){
    var c=document.getElementById('surveyCont'),i=sqCount++;
    c.insertAdjacentHTML('beforeend','<div class="sqblock" id="sqb'+i+'"><div class="sqblock-hdr"><span class="qblock-n">Question '+(i+1)+'</span><button type="button" class="qblock-del" onclick="rmSQ('+i+')"><i class="fa-solid fa-trash"></i></button></div><div class="fg"><label class="fl2">Question *</label><input type="text" name="survey_questions['+i+'][question]" class="fi" placeholder="Your question…"></div><div class="fg"><label class="fl2">Type *</label><select name="survey_questions['+i+'][type]" class="fsel2" onchange="toggleSurvOpts('+i+')"><option value="text">Text Input</option><option value="textarea">Long Text</option><option value="multiple_choice">Multiple Choice</option><option value="rating">Rating 1-5</option><option value="yes_no">Yes/No</option></select></div><div class="fg sq-opts-'+i+'" style="display:none"><label class="fl2">Options (comma-separated) *</label><input type="text" name="survey_questions['+i+'][options]" class="fi" placeholder="Option 1, Option 2, Option 3"></div><label class="fchk-row" style="margin-bottom:0"><input type="checkbox" name="survey_questions['+i+'][required]" checked><span>Required</span></label></div>');
}
function rmSQ(i){var e=document.getElementById('sqb'+i);if(e)e.remove();}
function toggleSurvOpts(i){
    var s=document.querySelector('select[name="survey_questions['+i+'][type]"]');
    var o=document.querySelector('.sq-opts-'+i);
    if(o)o.style.display=s.value==='multiple_choice'?'block':'none';
}

/* ══════════════════════════════════════════
   IMAGE PREVIEW
══════════════════════════════════════════ */
function prevImg(e){
    var f=e.target.files[0];if(!f)return;
    if(f.size>10*1024*1024){toast('Image too large (max 10MB)','error');e.target.value='';return;}
    var r=new FileReader();r.onload=function(ev){
        document.getElementById('imgPrevEl').src=ev.target.result;
        document.getElementById('imgPrev').style.display='block';
        document.getElementById('fRemoveImg').value='0';
    };r.readAsDataURL(f);
}
function removeImg(){
    document.getElementById('fImage').value='';
    document.getElementById('imgPrev').style.display='none';
    if(document.getElementById('fExistImg').value)document.getElementById('fRemoveImg').value='1';
}

/* ══════════════════════════════════════════
   EDIT TASK
══════════════════════════════════════════ */
async function editTask(id){
    var fd=new FormData();fd.append('ajax_action','get_task_data');fd.append('task_id',id);
    var r=await fetch(location.href,{method:'POST',body:fd});
    var d=await r.json();
    if(!d.success){toast(d.message,'error');return;}
    var t=d.task;
    document.getElementById('drawerTitle').textContent='Edit Task #'+t.id;
    document.getElementById('fAction').value='edit';
    document.getElementById('fTaskId').value=t.id;
    document.getElementById('fTitle').value=t.title||'';
    document.getElementById('fDesc').value=t.description||'';
    document.getElementById('fInstr').value=t.instructions||'';
    document.getElementById('fUrl').value=t.task_url||'';
    document.getElementById('fReward').value=t.reward||0;
    document.getElementById('fDailyLim').value=t.daily_limit_per_user||1;
    document.getElementById('fTotalLim').value=t.total_limit||'';
    document.getElementById('fTimer').value=t.min_duration_seconds||0;
    document.getElementById('fDifficulty').value=t.difficulty||'easy';
    document.getElementById('fCat').value=t.category||'general';
    document.getElementById('fPassPct').value=t.pass_percentage||70;
    document.getElementById('fActive').checked=t.status==='active';
    document.getElementById('fSidebar').checked=t.show_in_sidebar==1;
    document.getElementById('fAutoApp').checked=t.auto_approve==1;
    document.getElementById('fProof').checked=t.requires_proof==1;
    document.getElementById('fEnTimer').checked=t.enable_timer==1;
    document.getElementById('fExistImg').value=t.task_image||'';
    document.getElementById('fRemoveImg').value='0';
    if(t.task_image){document.getElementById('imgPrevEl').src='../'+t.task_image;document.getElementById('imgPrev').style.display='block';}
    else document.getElementById('imgPrev').style.display='none';
    var tr=document.querySelector('input[name="task_type"][value="'+t.task_type+'"]');
    if(tr){tr.checked=true;}
    qCount=0;sqCount=0;
    document.getElementById('quizCont').innerHTML='';
    document.getElementById('surveyCont').innerHTML='';
    onTypeChange();
    if(t.task_type==='trivia'||t.task_type==='quiz'){
        if(d.quiz_questions&&d.quiz_questions.length){
            d.quiz_questions.forEach(function(q,idx){
                addQ();
                document.querySelector('input[name="quiz_questions['+idx+'][question]"]').value=q.question||'';
                document.querySelector('input[name="quiz_questions['+idx+'][option_a]"]').value=q.option_a||'';
                document.querySelector('input[name="quiz_questions['+idx+'][option_b]"]').value=q.option_b||'';
                var oc=document.querySelector('input[name="quiz_questions['+idx+'][option_c]"]');if(oc)oc.value=q.option_c||'';
                var od=document.querySelector('input[name="quiz_questions['+idx+'][option_d]"]');if(od)od.value=q.option_d||'';
                document.querySelector('select[name="quiz_questions['+idx+'][correct_answer]"]').value=q.correct_answer||'';
                document.querySelector('input[name="quiz_questions['+idx+'][points]"]').value=q.points||1;
                var ex=document.querySelector('textarea[name="quiz_questions['+idx+'][explanation]"]');if(ex)ex.value=q.explanation||'';
            });
        }
    } else if(t.task_type==='blog'&&d.blog_data){
        var b=d.blog_data;
        document.getElementById('fBTopic').value=b.topic||'';
        document.getElementById('fBMin').value=b.min_words||300;
        document.getElementById('fBMax').value=b.max_words||'';
        document.getElementById('fBKw').value=b.keywords||'';
        document.getElementById('fBGuide').value=b.guidelines||'';
        document.getElementById('fBOutline').value=b.sample_outline||'';
        document.getElementById('fBWordCnt').checked=b.enable_word_count==1;
    } else if(t.task_type==='survey'&&d.survey_questions&&d.survey_questions.length){
        d.survey_questions.forEach(function(sq,idx){
            addSQ();
            document.querySelector('input[name="survey_questions['+idx+'][question]"]').value=sq.question||'';
            document.querySelector('select[name="survey_questions['+idx+'][type]"]').value=sq.question_type||'text';
            var op=document.querySelector('input[name="survey_questions['+idx+'][options]"]');
            if(op)op.value=sq.options?sq.options.replace(/\|/g,', '):'';
            document.querySelector('input[name="survey_questions['+idx+'][required]"]').checked=sq.required==1;
            toggleSurvOpts(idx);
        });
    } else if(t.task_type==='meme'&&d.meme_data){
        var m=d.meme_data;
        document.getElementById('fMTheme').value=m.theme||'';
        document.getElementById('fMFormats').value=m.allowed_formats||'jpg,png,gif';
        document.getElementById('fMSize').value=m.max_file_size_mb||5;
        document.getElementById('fMDim').value=m.min_dimensions||'';
        document.getElementById('fMGuide').value=m.guidelines||'';
    } else if(t.task_type==='transcription'&&d.transcription_data){
        var tr2=d.transcription_data;
        document.getElementById('fTAudio').value=tr2.audio_url||'';
        document.getElementById('fTVideo').value=tr2.video_url||'';
        document.getElementById('fTDur').value=tr2.duration_seconds||'';
        document.getElementById('fTLang').value=tr2.language||'English';
        document.getElementById('fTWords').value=tr2.expected_word_count||'';
        document.getElementById('fTDiff').value=tr2.difficulty_level||'medium';
    }
    showDrawer();
}

/* ══════════════════════════════════════════
   APPROVE / BULK
══════════════════════════════════════════ */
async function approve(id,status){
    if(!confirm((status==='completed'?'Approve':'Reject')+' this completion?'))return;
    var fd=new FormData();fd.append('ajax_action','approve_completion');fd.append('completion_id',id);fd.append('status',status);
    var r=await fetch(location.href,{method:'POST',body:fd});
    var d=await r.json();
    if(d.success){toast(d.message,'success');setTimeout(function(){location.reload();},900);}
    else toast(d.message,'error');
}
function toggleBulk(){
    bulkMode=!bulkMode;
    document.querySelectorAll('.tc').forEach(function(c){bulkMode?c.classList.add('bulk-mode'):c.classList.remove('bulk-mode','sel');});
    if(!bulkMode){sel.clear();updateBulkBar();}
}
function onChk(cb){
    var id=cb.dataset.id,card=document.getElementById('tc'+id);
    if(cb.checked){sel.add(id);card.classList.add('sel');}
    else{sel.delete(id);card.classList.remove('sel');}
    updateBulkBar();
}
function updateBulkBar(){
    document.getElementById('bulkBar').classList.toggle('on',sel.size>0);
    document.getElementById('selCount').textContent=sel.size;
}
function clearSel(){
    document.querySelectorAll('.tc-chk').forEach(function(c){c.checked=false;});
    document.querySelectorAll('.tc').forEach(function(c){c.classList.remove('sel');});
    sel.clear();updateBulkBar();
}
async function doBulk(action){
    if(!sel.size){toast('No tasks selected','warning');return;}
    if(!confirm(action.toUpperCase()+' '+sel.size+' task(s)?'+(action==='delete'?' This cannot be undone!':'')))return;
    var fd=new FormData();fd.append('ajax_action','bulk_action');fd.append('bulk_type',action);fd.append('task_ids',JSON.stringify([...sel]));
    var r=await fetch(location.href,{method:'POST',body:fd});
    var d=await r.json();
    if(d.success){toast(d.message,'success');setTimeout(function(){location.reload();},900);}
    else toast(d.message,'error');
}

/* ── INIT ── */
document.addEventListener('DOMContentLoaded',function(){
    onTypeChange();
    <?php if($flash&&$flash['type']==='success'):?>toast(<?=json_encode($flash['message'])?>,'success');<?php endif;?>
    <?php if($flash&&$flash['type']==='error'):?>toast(<?=json_encode($flash['message'])?>,'error');<?php endif;?>
    <?php if($flash&&$flash['type']==='warning'):?>toast(<?=json_encode($flash['message'])?>,'warning');<?php endif;?>
});
</script>
</body>
</html>