<?php
$pageTitle = 'Available Tasks';
require_once 'side.php';

$filterType       = $_GET['type']       ?? 'all';
$filterDifficulty = $_GET['difficulty'] ?? 'all';
$searchQuery      = $_GET['search']     ?? '';

/* ── FORM SUBMISSION ── */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='complete_task') {
    $taskId    = intval($_POST['task_id']);
    $startTime = intval($_POST['start_time'] ?? 0);
    $task = $conn->query("SELECT * FROM tasks WHERE id=$taskId AND status='active'")->fetch_assoc();
    if (!$task) { setFlash('error','Task not found.'); redirect('tasks.php'); }
    $doneToday = $conn->query("SELECT COUNT(*) as c FROM task_completions WHERE user_id=$userId AND task_id=$taskId AND DATE(created_at)=CURDATE()")->fetch_assoc()['c'];
    if ($doneToday >= $task['daily_limit_per_user']) { setFlash('error','Daily limit reached.'); redirect('tasks.php'); }
    if (($task['total_limit']??0)>0 && ($task['total_completions']??0)>=$task['total_limit']) { setFlash('error','Task limit reached.'); redirect('tasks.php'); }

    $screenshotPath = null;
    if (isset($_FILES['proof_screenshot']) && $_FILES['proof_screenshot']['error']===UPLOAD_ERR_OK) {
        $dir=__DIR__.'/../uploads/task_proofs/';
        if (!file_exists($dir)) mkdir($dir,0755,true);
        $ext=strtolower(pathinfo($_FILES['proof_screenshot']['name'],PATHINFO_EXTENSION));
        if (in_array($ext,['jpg','jpeg','png','gif','webp']) && $_FILES['proof_screenshot']['size']<=5*1024*1024) {
            $fn='proof_'.$userId.'_'.$taskId.'_'.time().'.'.$ext;
            if (move_uploaded_file($_FILES['proof_screenshot']['tmp_name'],$dir.$fn)) $screenshotPath='uploads/task_proofs/'.$fn;
        }
    }

    $status='pending'; $content=''; $taskType=$task['task_type'];
    if ($task['content_type']==='internal') {
        switch ($taskType) {
            case 'trivia': case 'quiz':
                $answers=$_POST['quiz_answers']??[]; $correct=0; $total=0;
                $qd=$conn->query("SELECT * FROM task_quizzes WHERE task_id=$taskId");
                while ($q=$qd->fetch_assoc()) { $total++; if (strtoupper($answers[$q['id']]??'')===strtoupper($q['correct_answer'])) $correct++; }
                $score=$total>0?($correct/$total)*100:0;
                $pass=intval($task['pass_percentage']??70);
                if ($score<$pass) { setFlash('error',"Score: ".round($score)."%. Need $pass%+ to pass!"); redirect('tasks.php?task_id='.$taskId); }
                $status='completed'; $content=json_encode(['score'=>$score,'correct'=>$correct,'total'=>$total]); break;
            case 'survey':
                $content=json_encode($_POST['survey_answers']??[]); $status='completed'; break;
            case 'blog':
                $bc=$_POST['blog_content']??''; $wc=str_word_count($bc);
                $br=$conn->query("SELECT * FROM task_blog_requirements WHERE task_id=$taskId LIMIT 1")->fetch_assoc();
                if ($br && $br['enable_word_count']) {
                    $mn=intval($br['min_words']??300); $mx=intval($br['max_words']??0);
                    if ($wc<$mn) { setFlash('error',"Too short! Min: $mn words. You wrote: $wc."); redirect('tasks.php?task_id='.$taskId); }
                    if ($mx>0&&$wc>$mx) { setFlash('error',"Too long! Max: $mx words. You wrote: $wc."); redirect('tasks.php?task_id='.$taskId); }
                }
                $content=json_encode(['title'=>$_POST['blog_title']??'','content'=>$bc,'words'=>$wc]); break;
            default: $content=json_encode(['data'=>$_POST]);
        }
    } else { $content=$_POST['proof_text']??''; }
    if ($task['auto_approve']) $status='completed';
    $reward=floatval($task['reward']); $timeTaken=time()-$startTime;
    $st=$conn->prepare("INSERT INTO task_completions(user_id,task_id,task_type,reward_earned,status,screenshot,submission_data,time_spent_seconds)VALUES(?,?,?,?,?,?,?,?)");
    $st->bind_param("iisdsssi",$userId,$taskId,$taskType,$reward,$status,$screenshotPath,$content,$timeTaken);
    if ($st->execute()) {
        $conn->query("UPDATE tasks SET total_completions=total_completions+1 WHERE id=$taskId");
        if ($status==='completed') {
            $wm=['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'];
            $col=$wm[$taskType]??'trivia_wallet';
            $conn->query("INSERT INTO wallets(user_id,$col,created_at,updated_at)VALUES($userId,$reward,NOW(),NOW()) ON DUPLICATE KEY UPDATE $col=$col+$reward,updated_at=NOW()");
            setFlash('success','🎉 Earned '.($cd['currency_symbol']??'Ksh').' '.number_format($reward,2).'!');
        } else { setFlash('success','✓ Submitted for review'); }
    }
    redirect('tasks.php');
}

/* ── QUERY ── */
$where=["status='active'"];
if ($filterType!=='all') $where[]="task_type='".$conn->real_escape_string($filterType)."'";
if ($filterDifficulty!=='all') $where[]="difficulty='".$conn->real_escape_string($filterDifficulty)."'";
if ($searchQuery) $where[]="(title LIKE '%".$conn->real_escape_string($searchQuery)."%' OR description LIKE '%".$conn->real_escape_string($searchQuery)."%')";

$tasks=$conn->query("SELECT t.*,(SELECT COUNT(*) FROM task_completions tc WHERE tc.task_id=t.id AND tc.user_id=$userId AND DATE(tc.created_at)=CURDATE()) as user_completed_today FROM tasks t WHERE ".implode(' AND ',$where)." ORDER BY show_in_sidebar DESC,created_at DESC");

$taskContents=[]; $tasksArray=[];
if ($tasks) {
    while ($task=$tasks->fetch_assoc()) {
        $tasksArray[]=$task;
        if ($task['content_type']==='internal') {
            $tid=$task['id']; $tt=$task['task_type'];
            switch ($tt) {
                case 'trivia': case 'quiz':
                    $qs=[];$r=$conn->query("SELECT id,question,option_a,option_b,option_c,option_d,correct_answer,points FROM task_quizzes WHERE task_id=$tid ORDER BY order_number");
                    if ($r) while ($q=$r->fetch_assoc()) $qs[]=$q;
                    if (!empty($qs)) $taskContents[$tid]=['type'=>'quiz','questions'=>$qs,'pass_percentage'=>intval($task['pass_percentage']??70)]; break;
                case 'survey':
                    $qs=[];$r=$conn->query("SELECT id,question,question_type,options,required,order_number FROM task_survey_questions WHERE task_id=$tid ORDER BY order_number");
                    if ($r) while ($q=$r->fetch_assoc()) $qs[]=$q;
                    if (!empty($qs)) $taskContents[$tid]=['type'=>'survey','questions'=>$qs]; break;
                case 'blog':
                    $r=$conn->query("SELECT * FROM task_blog_requirements WHERE task_id=$tid");
                    if ($r){ $req=$r->fetch_assoc(); if ($req) $taskContents[$tid]=['type'=>'blog','requirements'=>$req]; } break;
            }
        }
    }
}

$stats=$conn->query("SELECT COUNT(*) as total,SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as approved,SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END) as pending,SUM(CASE WHEN status='completed' THEN reward_earned ELSE 0 END) as earned FROM task_completions WHERE user_id=$userId")->fetch_assoc();

$typeCounts=['quiz'=>0,'survey'=>0,'blog'=>0,'video'=>0];
foreach ($tasksArray as $t) {
    $ty=$t['task_type']==='trivia'?'quiz':$t['task_type'];
    if (isset($typeCounts[$ty])) $typeCounts[$ty]++;
}

$typeIcons=['quiz'=>'fa-brain','survey'=>'fa-chart-simple','blog'=>'fa-pen-nib','video'=>'fa-clapperboard','chat'=>'fa-message','transcription'=>'fa-microphone','ads'=>'fa-rectangle-ad','meme'=>'fa-image','spin'=>'fa-rotate','external'=>'fa-arrow-up-right-from-square'];
$currSymbol=$cd['currency_symbol']??'Ksh';
?>
<style>
.pg{padding:12px 14px}
@media(max-width:480px){.pg{padding:10px}}

/* ── STAT CARDS ── */
.stats{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:10px}
@media(min-width:600px){.stats{grid-template-columns:repeat(4,1fr)}}
.sc{border-radius:12px;padding:12px;position:relative;overflow:hidden;color:#fff}
.sc::before{content:'';position:absolute;top:-20px;right:-20px;width:70px;height:70px;border-radius:50%;background:rgba(255,255,255,.08)}
.sc-1{background:linear-gradient(135deg,#6366f1,#8b5cf6);box-shadow:0 4px 14px rgba(99,102,241,.4)}
.sc-2{background:linear-gradient(135deg,#10b981,#059669);box-shadow:0 4px 14px rgba(16,185,129,.4)}
.sc-3{background:linear-gradient(135deg,#f59e0b,#f97316);box-shadow:0 4px 14px rgba(245,158,11,.4)}
.sc-4{background:linear-gradient(135deg,#ec4899,#f43f5e);box-shadow:0 4px 14px rgba(236,72,153,.4)}
.sc-ico{position:absolute;top:10px;right:10px;width:30px;height:30px;border-radius:8px;background:rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;font-size:13px}
.sc-lbl{font-size:10px;opacity:.8;text-transform:uppercase;letter-spacing:.5px;font-weight:600;margin-bottom:3px}
.sc-num{font-size:22px;font-weight:800;letter-spacing:-1px;line-height:1}
.sc-sub{font-size:10px;opacity:.75;margin-top:3px}

/* ── TYPE TABS ── */
.ttabs{display:flex;gap:5px;margin-bottom:10px;overflow-x:auto;padding-bottom:2px;scrollbar-width:none}
.ttabs::-webkit-scrollbar{display:none}
.ttab{display:flex;align-items:center;gap:5px;padding:6px 12px;border-radius:8px;background:var(--surf);border:1px solid var(--bdr);color:var(--txt2);font-size:12px;font-weight:600;text-decoration:none;white-space:nowrap;transition:.12s;flex-shrink:0}
.ttab:hover{border-color:rgba(var(--ar),.4);color:var(--txt)}
.ttab.on{background:linear-gradient(135deg,var(--a),#8b5cf6);color:#fff;border-color:transparent;box-shadow:0 3px 10px rgba(var(--ar),.35)}
.tcnt{display:inline-block;padding:1px 6px;border-radius:20px;font-size:9px;font-weight:700;background:rgba(255,255,255,.2)}
.ttab:not(.on) .tcnt{background:var(--surf2);color:var(--txt3)}

/* ── FILTER ROW ── */
.frow{display:flex;gap:6px;margin-bottom:10px;flex-wrap:wrap}
.frow form{display:flex;gap:6px;flex:1;flex-wrap:wrap}
.fsel,.finp{height:34px;padding:0 10px;background:var(--surf);border:1px solid var(--bdr);border-radius:8px;color:var(--txt);font-size:12px;font-family:'Inter',sans-serif;flex:1;min-width:90px}
.fsel:focus,.finp:focus{outline:none;border-color:rgba(var(--ar),.5)}
.fsub{height:34px;padding:0 14px;background:var(--a);color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;font-family:'Inter',sans-serif;flex-shrink:0}
.frst{height:34px;padding:0 12px;background:var(--surf2);border:1px solid var(--bdr);border-radius:8px;color:var(--txt2);font-size:12px;font-weight:600;text-decoration:none;display:flex;align-items:center;gap:5px;white-space:nowrap;flex-shrink:0;transition:.12s}
.frst:hover{color:var(--txt);border-color:rgba(var(--ar),.4)}

/* ── TASK GRID ── */
.tgrid{display:grid;grid-template-columns:1fr;gap:8px;margin-bottom:10px}
@media(min-width:580px){.tgrid{grid-template-columns:repeat(2,1fr)}}
@media(min-width:900px){.tgrid{grid-template-columns:repeat(3,1fr)}}

/* ── TASK CARD ── */
.tcard{background:var(--surf);border:1px solid var(--bdr);border-radius:14px;overflow:hidden;cursor:pointer;transition:.15s;position:relative;display:flex;flex-direction:column}
.tcard:hover{transform:translateY(-3px);box-shadow:0 8px 24px rgba(0,0,0,.1);border-color:rgba(var(--ar),.3)}
.tcard.done{opacity:.65}

/* image */
.tc-img{width:100%;height:130px;overflow:hidden;position:relative;background:linear-gradient(135deg,#6366f1,#8b5cf6)}
.tc-img img{width:100%;height:100%;object-fit:cover;transition:transform .2s}
.tcard:hover .tc-img img{transform:scale(1.05)}
.tc-img-ico{display:flex;align-items:center;justify-content:center;height:100%;font-size:40px;color:rgba(255,255,255,.25)}
.tc-featured{position:absolute;top:8px;left:8px;background:linear-gradient(135deg,#f59e0b,#f97316);color:#fff;padding:2px 8px;border-radius:5px;font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.5px}

/* body */
.tc-body{padding:12px;flex:1;display:flex;flex-direction:column;gap:8px}
.tc-tags{display:flex;align-items:center;gap:5px;flex-wrap:wrap}
.type-tag{padding:2px 8px;border-radius:20px;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.3px;color:#fff}
.diff-tag{padding:2px 7px;border-radius:20px;font-size:9.5px;font-weight:600;text-transform:uppercase}
.diff-easy{background:rgba(16,185,129,.12);color:#059669}
.diff-medium{background:rgba(245,158,11,.12);color:#d97706}
.diff-hard{background:rgba(239,68,68,.1);color:#ef4444}
[data-theme=dark] .diff-easy{background:rgba(16,185,129,.2);color:#34d399}
[data-theme=dark] .diff-medium{background:rgba(245,158,11,.2);color:#fbbf24}
[data-theme=dark] .diff-hard{background:rgba(239,68,68,.18);color:#f87171}

.tc-title{font-size:13px;font-weight:700;color:var(--txt);line-height:1.4}
.tc-desc{font-size:11.5px;color:var(--txt2);line-height:1.5;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}

/* reward strip */
.tc-reward{background:linear-gradient(135deg,var(--a),#8b5cf6);border-radius:9px;padding:8px 12px;display:flex;align-items:center;justify-content:space-between}
.tc-reward-num{font-size:16px;font-weight:800;color:#fff;letter-spacing:-.5px}
.tc-reward-lbl{font-size:9px;font-weight:700;color:rgba(255,255,255,.75);text-transform:uppercase;letter-spacing:.5px}

.tc-meta{display:grid;grid-template-columns:1fr 1fr;gap:4px}
.tcm{display:flex;align-items:center;gap:4px;font-size:10.5px;color:var(--txt2)}
.tcm i{width:12px;text-align:center;font-size:10px;color:var(--txt3)}

.tc-btn{width:100%;height:36px;background:var(--a);color:#fff;border:none;border-radius:9px;font-size:12.5px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;font-family:'Inter',sans-serif;transition:.15s;box-shadow:0 3px 10px rgba(var(--ar),.3);margin-top:auto}
.tc-btn:hover:not(:disabled){opacity:.9;transform:translateY(-1px)}
.tc-btn:disabled{background:var(--surf2);color:var(--txt3);box-shadow:none;cursor:not-allowed;border:1px solid var(--bdr)}

/* ── MODAL ── */
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);backdrop-filter:blur(10px);z-index:2000;overflow-y:auto;padding:0}
@media(min-width:600px){.modal{padding:16px;display:none}}
.modal.on{display:flex;align-items:flex-start;justify-content:center}
@media(min-width:600px){.modal.on{align-items:center}}

.modal-box{background:var(--surf);width:100%;min-height:100%;position:relative;overflow-y:auto}
@media(min-width:600px){.modal-box{border-radius:16px;max-width:580px;min-height:auto;max-height:90vh;box-shadow:0 20px 60px rgba(0,0,0,.5)}}

.modal-hdr{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;border-bottom:1px solid var(--bdr);position:sticky;top:0;background:var(--surf);z-index:10}
.modal-title{font-size:14px;font-weight:800;color:var(--txt);flex:1;padding-right:10px;line-height:1.4}
.modal-cls{width:34px;height:34px;border-radius:8px;background:var(--surf2);border:1px solid var(--bdr);color:var(--txt2);display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:14px;transition:.15s;flex-shrink:0}
.modal-cls:hover{background:var(--a);color:#fff;border-color:transparent}

.modal-body{padding:14px}

/* modal sections */
.mimg{width:100%;height:180px;object-fit:cover;border-radius:10px;margin-bottom:12px}
.mdetails{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:12px}
.mdet{background:var(--surf2);border-radius:9px;padding:8px;text-align:center}
.mdet-lbl{font-size:9px;text-transform:uppercase;letter-spacing:.5px;color:var(--txt3);font-weight:600;margin-bottom:3px}
.mdet-val{font-size:13px;font-weight:800;color:var(--txt)}

.mbox{background:var(--surf2);border:1px solid var(--bdr);border-radius:10px;padding:12px;margin-bottom:10px}
.mbox-title{font-size:12px;font-weight:700;color:var(--txt);display:flex;align-items:center;gap:6px;margin-bottom:6px}
.mbox-body{font-size:12px;color:var(--txt2);line-height:1.6}

/* timer */
.timer-box{text-align:center;padding:14px;background:var(--surf2);border-radius:10px;margin-bottom:10px}
.timer-lbl{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--txt2);margin-bottom:4px}
.timer-num{font-size:42px;font-weight:800;letter-spacing:-2px;line-height:1;color:var(--a);font-family:'Courier New',monospace}
.timer-box.warn .timer-num{color:#f59e0b}
.timer-box.danger .timer-num{color:#ef4444}
.timer-box.expired .timer-num{color:var(--txt3);text-decoration:line-through}
.timer-sub{font-size:11px;color:var(--txt2);margin-top:4px}

/* quiz/survey */
.qblock{background:var(--surf2);border:1px solid var(--bdr);border-radius:10px;padding:12px;margin-bottom:8px}
.qnum{display:inline-block;background:var(--a);color:#fff;padding:2px 8px;border-radius:5px;font-size:9px;font-weight:700;margin-bottom:6px}
.qtxt{font-size:13px;font-weight:600;color:var(--txt);margin-bottom:8px;line-height:1.5}
.qopts{display:grid;gap:5px}
.qopt input[type=radio]{display:none}
.qopt label{display:flex;align-items:center;padding:8px 11px;background:var(--surf);border:1.5px solid var(--bdr);border-radius:8px;cursor:pointer;font-size:12px;font-weight:500;color:var(--txt);transition:.12s;min-height:36px}
.qopt label:hover{border-color:rgba(var(--ar),.5)}
.qopt input[type=radio]:checked+label{background:rgba(var(--ar),.1);border-color:var(--a);color:var(--a);font-weight:600}

/* blog */
.blog-in,.blog-ta{width:100%;padding:9px 11px;border:1.5px solid var(--bdr);border-radius:9px;background:var(--surf);color:var(--txt);font-family:'Inter',sans-serif;font-size:12.5px;transition:.15s;margin-bottom:8px}
.blog-in:focus,.blog-ta:focus{outline:none;border-color:var(--a)}
.blog-ta{min-height:160px;resize:vertical;line-height:1.6}
.wc{text-align:right;font-size:11px;color:var(--txt2);font-weight:600;margin-top:-4px;margin-bottom:8px}

/* file */
.file-in{width:100%;padding:9px;border:1.5px dashed var(--bdr);border-radius:9px;background:var(--surf2);color:var(--txt2);font-size:12px;margin-bottom:8px;cursor:pointer;transition:.15s}
.file-in:hover{border-color:rgba(var(--ar),.5)}

/* submit btn */
.m-submit{width:100%;height:44px;background:linear-gradient(135deg,var(--a),#8b5cf6);color:#fff;border:none;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:7px;font-family:'Inter',sans-serif;box-shadow:0 4px 14px rgba(var(--ar),.4);margin-top:12px;transition:.2s;text-transform:uppercase;letter-spacing:.3px}
.m-submit:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 6px 20px rgba(var(--ar),.5)}
.m-submit:disabled{background:var(--surf2);color:var(--txt3);box-shadow:none;cursor:not-allowed;border:1px solid var(--bdr)}

/* empty */
.empty{text-align:center;padding:36px 16px;background:var(--surf);border:1px solid var(--bdr);border-radius:14px}
.empty-ico{font-size:36px;color:var(--txt3);margin-bottom:10px}
.empty-t{font-size:14px;font-weight:700;color:var(--txt);margin-bottom:4px}
.empty-s{font-size:12px;color:var(--txt2)}

/* toast */
.toast{position:fixed;top:-70px;left:50%;transform:translateX(-50%);min-width:260px;max-width:90%;background:var(--surf);border:1px solid var(--bdr);border-left:3px solid #10b981;border-radius:12px;padding:10px 14px;display:flex;align-items:center;gap:9px;font-size:12.5px;font-weight:600;color:var(--txt);z-index:9999;box-shadow:0 6px 24px rgba(0,0,0,.15);transition:top .33s cubic-bezier(.34,1.56,.64,1)}
.toast.show{top:calc(var(--hh)+10px)}
.toast.error{border-left-color:#ef4444}
.tdot{width:20px;height:20px;border-radius:50%;background:#10b981;display:flex;align-items:center;justify-content:center;font-size:10px;color:#fff;flex-shrink:0}
.toast.error .tdot{background:#ef4444}
</style>

<div class="pg">

<!-- STATS -->
<div class="stats">
  <div class="sc sc-1">
    <div class="sc-ico"><i class="fa-solid fa-list-check"></i></div>
    <div class="sc-lbl">Completed</div>
    <div class="sc-num"><?php echo number_format($stats['total']??0);?></div>
    <div class="sc-sub">All time</div>
  </div>
  <div class="sc sc-2">
    <div class="sc-ico"><i class="fa-solid fa-circle-check"></i></div>
    <div class="sc-lbl">Approved</div>
    <div class="sc-num"><?php echo number_format($stats['approved']??0);?></div>
    <div class="sc-sub">Paid out</div>
  </div>
  <div class="sc sc-3">
    <div class="sc-ico"><i class="fa-solid fa-clock"></i></div>
    <div class="sc-lbl">Pending</div>
    <div class="sc-num"><?php echo number_format($stats['pending']??0);?></div>
    <div class="sc-sub">In review</div>
  </div>
  <div class="sc sc-4">
    <div class="sc-ico"><i class="fa-solid fa-coins"></i></div>
    <div class="sc-lbl">Earned</div>
    <div class="sc-num" style="font-size:16px"><?php echo $currSymbol.' '.number_format($stats['earned']??0);?></div>
    <div class="sc-sub">Total</div>
  </div>
</div>

<!-- TYPE TABS -->
<div class="ttabs">
  <a href="?type=all&difficulty=<?php echo $filterDifficulty;?>&search=<?php echo urlencode($searchQuery);?>" class="ttab <?php echo $filterType==='all'?'on':'';?>">
    <i class="fa-solid fa-grid-2"></i>All<span class="tcnt"><?php echo count($tasksArray);?></span>
  </a>
  <?php foreach(['quiz'=>'Brain','survey'=>'Survey','blog'=>'Blog','video'=>'Video'] as $tk=>$tl):?>
  <a href="?type=<?php echo $tk;?>&difficulty=<?php echo $filterDifficulty;?>&search=<?php echo urlencode($searchQuery);?>" class="ttab <?php echo $filterType===$tk?'on':'';?>">
    <i class="fa-solid <?php echo $typeIcons[$tk];?>"></i><?php echo $tl;?><span class="tcnt"><?php echo $typeCounts[$tk]??0;?></span>
  </a>
  <?php endforeach;?>
</div>

<!-- FILTER ROW -->
<div class="frow">
  <form method="GET" style="display:flex;gap:6px;flex:1;flex-wrap:wrap">
    <input type="hidden" name="type" value="<?php echo $filterType;?>">
    <select name="difficulty" class="fsel">
      <option value="all" <?php echo $filterDifficulty==='all'?'selected':'';?>>All Levels</option>
      <option value="easy" <?php echo $filterDifficulty==='easy'?'selected':'';?>>Easy</option>
      <option value="medium" <?php echo $filterDifficulty==='medium'?'selected':'';?>>Medium</option>
      <option value="hard" <?php echo $filterDifficulty==='hard'?'selected':'';?>>Hard</option>
    </select>
    <input type="text" name="search" class="finp" placeholder="Search tasks…" value="<?php echo htmlspecialchars($searchQuery);?>">
    <button type="submit" class="fsub"><i class="fa-solid fa-magnifying-glass"></i></button>
  </form>
  <?php if($searchQuery||$filterDifficulty!=='all'||$filterType!=='all'):?>
  <a href="tasks.php" class="frst"><i class="fa-solid fa-xmark"></i>Clear</a>
  <?php endif;?>
</div>

<!-- TASK GRID -->
<?php if(empty($tasksArray)):?>
<div class="empty">
  <div class="empty-ico"><i class="fa-solid fa-clipboard-list"></i></div>
  <div class="empty-t">No Tasks Found</div>
  <div class="empty-s"><?php echo $searchQuery?'No tasks match your search.':'Check back soon for new tasks!';?></div>
</div>
<?php else:?>
<div class="tgrid">
<?php
$typeGrads=['quiz'=>'linear-gradient(135deg,#6366f1,#8b5cf6)','trivia'=>'linear-gradient(135deg,#6366f1,#8b5cf6)','survey'=>'linear-gradient(135deg,#06b6d4,#3b82f6)','blog'=>'linear-gradient(135deg,#10b981,#059669)','video'=>'linear-gradient(135deg,#ef4444,#f97316)','chat'=>'linear-gradient(135deg,#3b82f6,#6366f1)','transcription'=>'linear-gradient(135deg,#f97316,#f59e0b)','ads'=>'linear-gradient(135deg,#8b5cf6,#a855f7)','meme'=>'linear-gradient(135deg,#ec4899,#f43f5e)','spin'=>'linear-gradient(135deg,#14b8a6,#06b6d4)','external'=>'linear-gradient(135deg,#64748b,#475569)'];
foreach($tasksArray as $task):
    $canDo=$task['user_completed_today']<$task['daily_limit_per_user'];
    $isInt=$task['content_type']==='internal';
    $hasImg=!empty($task['task_image']);
    $grad=$typeGrads[$task['task_type']]??'linear-gradient(135deg,var(--a),#8b5cf6)';
    $ico=$typeIcons[$task['task_type']]??'fa-circle-dot';
?>
<div class="tcard <?php echo !$canDo?'done':'';?>" onclick="openModal(<?php echo htmlspecialchars(json_encode($task));?>)">
  <?php if($task['show_in_sidebar']):?><div class="tc-featured"><i class="fa-solid fa-star"></i> Featured</div><?php endif;?>

  <div class="tc-img" style="<?php echo !$hasImg?"background:$grad":'';?>">
    <?php if($hasImg):?>
    <img src="../<?php echo htmlspecialchars($task['task_image']);?>" alt="" loading="lazy" onerror="this.parentElement.innerHTML='<div class=\'tc-img-ico\'><i class=\'fa-solid <?php echo $ico;?>\'></i></div>'">
    <?php else:?><div class="tc-img-ico"><i class="fa-solid <?php echo $ico;?>"></i></div><?php endif;?>
  </div>

  <div class="tc-body">
    <div class="tc-tags">
      <span class="type-tag" style="background:<?php echo $grad;?>"><?php echo strtoupper($task['task_type']);?></span>
      <span class="diff-tag diff-<?php echo $task['difficulty'];?>"><?php echo ucfirst($task['difficulty']);?></span>
    </div>
    <div class="tc-title"><?php echo htmlspecialchars($task['title']);?></div>
    <div class="tc-desc"><?php echo htmlspecialchars(substr($task['description'],0,110));?>…</div>
    <div class="tc-reward">
      <div><div class="tc-reward-lbl">Reward</div><div class="tc-reward-num"><?php echo $currSymbol.' '.number_format($task['reward'],2);?></div></div>
      <i class="fa-solid fa-coins" style="color:rgba(255,255,255,.5);font-size:20px"></i>
    </div>
    <div class="tc-meta">
      <div class="tcm"><i class="fa-solid fa-rotate-right"></i><?php echo $task['daily_limit_per_user'];?>x daily</div>
      <div class="tcm"><i class="fa-solid fa-users"></i><?php echo $task['total_completions']??0;?> done</div>
      <?php if(intval($task['enable_timer'])===1&&intval($task['min_duration_seconds'])>0):?>
      <div class="tcm"><i class="fa-solid fa-stopwatch"></i><?php echo gmdate('i:s',$task['min_duration_seconds']);?></div>
      <?php elseif($isInt):?>
      <div class="tcm"><i class="fa-solid fa-laptop-code"></i>Interactive</div>
      <?php endif;?>
      <div class="tcm"><i class="fa-solid fa-fingerprint"></i>ID: <?php echo $task['id'];?></div>
    </div>
    <button class="tc-btn" <?php echo !$canDo?'disabled':'';?> onclick="event.stopPropagation();openModal(<?php echo htmlspecialchars(json_encode($task));?>)">
      <i class="fa-solid <?php echo $canDo?'fa-play':'fa-ban';?>"></i>
      <?php echo $canDo?'Start Task':'Limit Reached';?>
    </button>
  </div>
</div>
<?php endforeach;?>
</div>
<?php endif;?>
</div><!-- .pg -->

<!-- MODAL -->
<div class="modal" id="tm">
  <div class="modal-box">
    <div class="modal-hdr">
      <div class="modal-title" id="mt-title"></div>
      <button class="modal-cls" onclick="closeModal()"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <div class="modal-body" id="mt-body"></div>
  </div>
</div>

<!-- TOAST -->
<div class="toast" id="toast"><div class="tdot" id="tdot"><i class="fa-solid fa-check" style="font-size:9px"></i></div><span id="tmsg"></span></div>

<script>
const TASK_CONTENTS=<?php echo json_encode($taskContents);?>;
const TASKS=<?php echo json_encode($tasksArray);?>;
const CUR='<?php echo addslashes($currSymbol);?>';

let curTask=null,startTime=0,timerIv=null,timeLeft=0;

function showToast(msg,type){
  type=type||'success';
  var t=document.getElementById('toast'),d=document.getElementById('tdot'),s=document.getElementById('tmsg');
  clearTimeout(t._timer);
  t.className='toast'+(type==='error'?' error':'');
  d.innerHTML=type==='error'?'<i class="fa-solid fa-xmark" style="font-size:9px"></i>':'<i class="fa-solid fa-check" style="font-size:9px"></i>';
  s.textContent=msg;t.classList.add('show');
  t._timer=setTimeout(function(){t.classList.remove('show');},4000);
}

function fmt(s){return String(Math.floor(s/60)).padStart(2,'0')+':'+String(s%60).padStart(2,'0');}

function startTimer(sec){
  if(timerIv) clearInterval(timerIv);
  timeLeft=sec;
  var total=sec;
  timerIv=setInterval(function(){
    timeLeft--;
    var d=document.getElementById('timerNum'),b=document.getElementById('timerBox'),st=document.getElementById('timerSub'),sb=document.getElementById('msubmit');
    if(d) d.textContent=fmt(timeLeft);
    if(b){
      var pct=timeLeft/total;
      b.className='timer-box'+(pct<=.1?' danger':pct<=.3?' warn':'');
    }
    if(timeLeft<=0){
      clearInterval(timerIv);
      if(b) b.className='timer-box expired';
      if(st) st.textContent='⛔ Time expired — cannot submit';
      if(sb){sb.disabled=true;sb.innerHTML='<i class="fa-solid fa-ban"></i> Time Expired';}
      showToast('⏰ Time expired!','error');
    }
  },1000);
}

function openModal(task){
  curTask=task; startTime=Math.floor(Date.now()/1000);
  if(timerIv){clearInterval(timerIv);timerIv=null;}
  document.getElementById('mt-title').textContent=task.title;

  var body='';
  if(task.task_image) body+=`<img src="../${task.task_image}" class="mimg" onerror="this.style.display='none'">`;

  body+=`<div class="mdetails">
    <div class="mdet"><div class="mdet-lbl">Type</div><div class="mdet-val">${task.task_type.toUpperCase()}</div></div>
    <div class="mdet"><div class="mdet-lbl">Level</div><div class="mdet-val">${task.difficulty.toUpperCase()}</div></div>
    <div class="mdet"><div class="mdet-lbl">Reward</div><div class="mdet-val">${CUR} ${parseFloat(task.reward).toFixed(2)}</div></div>
    <div class="mdet"><div class="mdet-lbl">Daily</div><div class="mdet-val">${task.daily_limit_per_user}×</div></div>
  </div>`;

  var hasTimer=parseInt(task.enable_timer)===1&&parseInt(task.min_duration_seconds)>0;
  if(hasTimer){
    timeLeft=parseInt(task.min_duration_seconds);
    body+=`<div class="timer-box" id="timerBox">
      <div class="timer-lbl"><i class="fa-solid fa-stopwatch"></i> Time Remaining</div>
      <div class="timer-num" id="timerNum">${fmt(timeLeft)}</div>
      <div class="timer-sub" id="timerSub">Submit before the timer runs out</div>
    </div>`;
  }

  if(task.description) body+=`<div class="mbox"><div class="mbox-title"><i class="fa-solid fa-circle-info"></i> About</div><div class="mbox-body">${task.description}</div></div>`;
  if(task.instructions) body+=`<div class="mbox" style="border-left:2px solid var(--a)"><div class="mbox-title"><i class="fa-solid fa-list-check"></i> Instructions</div><div class="mbox-body">${task.instructions}</div></div>`;

  var tc=TASK_CONTENTS[task.id];
  if(task.content_type==='internal'&&tc){
    body+=renderContent(tc,task);
  } else {
    body+=renderExternal(task);
  }

  document.getElementById('mt-body').innerHTML=body;
  document.getElementById('tm').classList.add('on');
  document.body.style.overflow='hidden';
  if(hasTimer) setTimeout(function(){startTimer(parseInt(task.min_duration_seconds));},100);
}

function renderContent(tc,task){
  switch(tc.type){
    case 'quiz': return renderQuiz(tc.questions,task,tc.pass_percentage||70);
    case 'survey': return renderSurvey(tc.questions,task);
    case 'blog': return renderBlog(tc.requirements,task);
    default: return renderExternal(task);
  }
}

function renderQuiz(qs,task,pass){
  if(!qs||!qs.length) return '<p style="text-align:center;padding:20px;color:var(--txt2)">No questions available.</p>';
  var h=`<form method="POST" enctype="multipart/form-data" onsubmit="return validateSub()">
    <input type="hidden" name="action" value="complete_task">
    <input type="hidden" name="task_id" value="${task.id}">
    <input type="hidden" name="start_time" value="${startTime}">
    <div class="mbox-title" style="margin-bottom:8px"><i class="fa-solid fa-brain"></i> Answer All (${pass}%+ to pass)</div>`;
  qs.forEach(function(q,i){
    h+=`<div class="qblock"><span class="qnum">Q${i+1}/${qs.length}</span><div class="qtxt">${q.question}</div><div class="qopts">`;
    ['A','B','C','D'].forEach(function(opt){
      var k='option_'+opt.toLowerCase(),txt=q[k];
      if(txt) h+=`<div class="qopt"><input type="radio" name="quiz_answers[${q.id}]" value="${opt}" id="q${q.id}_${opt}" required><label for="q${q.id}_${opt}"><strong>${opt}.</strong> ${txt}</label></div>`;
    });
    h+='</div></div>';
  });
  h+=`<button type="submit" class="m-submit" id="msubmit"><i class="fa-solid fa-paper-plane"></i> Submit Quiz</button></form>`;
  return h;
}

function renderSurvey(qs,task){
  if(!qs||!qs.length) return '<p style="text-align:center;padding:20px;color:var(--txt2)">No questions.</p>';
  var h=`<form method="POST" enctype="multipart/form-data" onsubmit="return validateSub()">
    <input type="hidden" name="action" value="complete_task">
    <input type="hidden" name="task_id" value="${task.id}">
    <input type="hidden" name="start_time" value="${startTime}">
    <div class="mbox-title" style="margin-bottom:8px"><i class="fa-solid fa-chart-simple"></i> Complete Survey</div>`;
  qs.forEach(function(q,i){
    h+=`<div class="qblock"><div class="qtxt">${i+1}. ${q.question}${q.required==1?' <span style="color:#ef4444">*</span>':''}</div>`;
    switch(q.question_type){
      case 'text': h+=`<input type="text" name="survey_answers[${q.id}]" class="blog-in" placeholder="Your answer…" ${q.required==1?'required':''}>`; break;
      case 'textarea': h+=`<textarea name="survey_answers[${q.id}]" class="blog-ta" style="min-height:90px" placeholder="Your answer…" ${q.required==1?'required':''}></textarea>`; break;
      case 'multiple_choice':
        if(q.options){
          h+='<div class="qopts">';
          q.options.split('|').forEach(function(op,j){h+=`<div class="qopt"><input type="radio" name="survey_answers[${q.id}]" value="${op}" id="s${q.id}_${j}" ${q.required==1?'required':''}><label for="s${q.id}_${j}">${op}</label></div>`;});
          h+='</div>';
        } break;
    }
    h+='</div>';
  });
  h+=`<button type="submit" class="m-submit" id="msubmit"><i class="fa-solid fa-paper-plane"></i> Submit Survey</button></form>`;
  return h;
}

function renderBlog(req,task){
  var mn=req&&req.min_words?req.min_words:300,mx=req&&req.max_words?req.max_words:0;
  return `<form method="POST" enctype="multipart/form-data" onsubmit="return validateSub()">
    <input type="hidden" name="action" value="complete_task">
    <input type="hidden" name="task_id" value="${task.id}">
    <input type="hidden" name="start_time" value="${startTime}">
    <div class="mbox" style="margin-bottom:8px">
      <div class="mbox-title"><i class="fa-solid fa-list-check"></i> Requirements</div>
      <div class="mbox-body">Words: ${mn}–${mx>0?mx:'unlimited'}${req&&req.keywords?'<br>Keywords: '+req.keywords:''}</div>
    </div>
    <input type="text" name="blog_title" class="blog-in" placeholder="Blog title…" required>
    <textarea name="blog_content" id="blogTA" class="blog-ta" placeholder="Write your blog here…" required oninput="wc()"></textarea>
    <div class="wc">Words: <span id="wcNum">0</span> / ${mn}${mx>0?'–'+mx:'+' }</div>
    <button type="submit" class="m-submit" id="msubmit"><i class="fa-solid fa-paper-plane"></i> Submit Blog</button>
  </form>`;
}

function renderExternal(task){
  return `<form method="POST" enctype="multipart/form-data" onsubmit="return validateSub()">
    <input type="hidden" name="action" value="complete_task">
    <input type="hidden" name="task_id" value="${task.id}">
    <input type="hidden" name="start_time" value="${startTime}">
    ${task.task_url?`<div class="mbox"><div class="mbox-title"><i class="fa-solid fa-arrow-up-right-from-square"></i> Task Link</div><a href="${task.task_url}" target="_blank" style="color:var(--a);font-size:12px;font-weight:600;word-break:break-all">${task.task_url}</a></div>`:''}
    <label style="display:block;font-size:11px;font-weight:700;color:var(--txt2);text-transform:uppercase;letter-spacing:.5px;margin-bottom:5px">${task.requires_proof?'* ':''}Proof Screenshot</label>
    <input type="file" name="proof_screenshot" accept="image/*" class="file-in" ${task.requires_proof?'required':''}>
    <textarea name="proof_text" class="blog-ta" style="min-height:80px" placeholder="Additional notes (optional)…"></textarea>
    <button type="submit" class="m-submit" id="msubmit"><i class="fa-solid fa-circle-check"></i> Submit Task</button>
  </form>`;
}

function wc(){
  var ta=document.getElementById('blogTA'),n=document.getElementById('wcNum');
  if(ta&&n) n.textContent=ta.value.trim()?ta.value.trim().split(/\s+/).length:0;
}

function closeModal(){
  if(timerIv){clearInterval(timerIv);timerIv=null;}
  timeLeft=0;
  document.getElementById('tm').classList.remove('on');
  document.body.style.overflow='';
}

function validateSub(){
  if(!curTask) return false;
  var hasTimer=parseInt(curTask.enable_timer)===1&&parseInt(curTask.min_duration_seconds)>0;
  if(hasTimer&&timeLeft<=0){showToast('⏰ Time expired!','error');return false;}
  if(curTask.content_type==='internal'&&(curTask.task_type==='quiz'||curTask.task_type==='trivia')){
    var groups=document.querySelectorAll('.qblock');
    for(var g of groups){var r=g.querySelectorAll('input[type=radio]');if(!Array.from(r).some(function(x){return x.checked;})){showToast('Answer all questions!','error');return false;}}
  }
  return confirm('Submit this task?');
}

document.getElementById('tm').addEventListener('click',function(e){if(e.target===this)closeModal();});
document.addEventListener('keydown',function(e){if(e.key==='Escape')closeModal();});

// auto-open from sidebar/URL
(function(){
  var p=new URLSearchParams(location.search),tid=p.get('task_id');
  if(tid){
    var t=TASKS.find(function(x){return x.id==tid;});
    if(t) setTimeout(function(){openModal(t);},400);
    var nu=location.pathname+(location.search.replace(/[?&]task_id=\d+/,'').replace(/^&/,'?')||'');
    history.replaceState({},'',nu);
  }
})();

// flash
<?php $fl=getFlash(); if($fl): ?>
document.addEventListener('DOMContentLoaded',function(){showToast(<?php echo json_encode($fl['message']);?>,<?php echo json_encode($fl['type']==='success'?'success':'error');?>);});
<?php endif;?>
</script>
<?php include 'footer.php';?>