<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$action = $_GET['action'] ?? 'check';

if ($action === 'check') {
    $track = $u['learning_track'] ?: 'foundation';
    $stmt_total = db()->prepare('SELECT COUNT(*) FROM lessons WHERE track=?');
    $stmt_total->execute([$track]);
    $total_lessons = (int)$stmt_total->fetchColumn();
    $stmt_done = db()->prepare('SELECT COUNT(*) FROM user_progress up JOIN lessons l ON l.id=up.lesson_id WHERE up.user_id=? AND l.track=?');
    $stmt_done->execute([$u['id'], $track]);
    $done = (int)$stmt_done->fetchColumn();
    $pct = $total_lessons > 0 ? round($done / $total_lessons * 100) : 0;
    // Check existing cert
    $cert = db()->prepare('SELECT * FROM certificates WHERE user_id=? AND track=? LIMIT 1'); $cert->execute([$u['id'],$track]); $existing=$cert->fetch();
    json_response(['success'=>true,'track'=>$track,'done'=>$done,'total'=>$total_lessons,'percent'=>$pct,'eligible'=>$pct>=80,'certificate'=>$existing]);
}

if ($action === 'issue') {
    $track = $u['learning_track'] ?: 'foundation';
    // Verify 80%+ completion
    $stmt_t2 = db()->prepare('SELECT COUNT(*) FROM lessons WHERE track=?');
    $stmt_t2->execute([$track]);
    $total = (int)$stmt_t2->fetchColumn();
    $stmt_d2 = db()->prepare('SELECT COUNT(*) FROM user_progress up JOIN lessons l ON l.id=up.lesson_id WHERE up.user_id=? AND l.track=?');
    $stmt_d2->execute([$u['id'], $track]);
    $done  = (int)$stmt_d2->fetchColumn();
    if ($total === 0 || $done/$total < 0.8) json_response(['error'=>'not_eligible','message'=>'يجب إكمال 80% من الدروس للحصول على الشهادة','percent'=>round($done/$total*100)], 403);
    // Check not already issued
    $ex = db()->prepare('SELECT id,cert_code FROM certificates WHERE user_id=? AND track=? LIMIT 1'); $ex->execute([$u['id'],$track]); $existing=$ex->fetch();
    if ($existing) json_response(['success'=>true,'cert_code'=>$existing['cert_code'],'already_issued'=>true]);
    $code = strtoupper(substr(md5($u['id'].$track.time()), 0, 16));
    db()->prepare('INSERT INTO certificates (user_id,track,lessons_done,cert_code) VALUES (?,?,?,?)')->execute([$u['id'],$track,$done,$code]);
    db()->prepare('UPDATE users SET points_learn=points_learn+50 WHERE id=?')->execute([$u['id']]);
    save_notification($u['id'],'certificate_issued','🎓 حصلت على شهادتك!',"شهادة إتمام مسار «$track» — رمز التحقق: $code");
    json_response(['success'=>true,'cert_code'=>$code,'user_name'=>$u['name'],'track'=>$track,'issued_at'=>date('Y-m-d')]);
}

// التحقق من شهادة (عام)
if ($action === 'verify') {
    $code = trim($_GET['code'] ?? '');
    if (!$code) Kernel::fail('code_required', '', 400);
    $st = db()->prepare('SELECT c.*,u.name AS holder_name FROM certificates c JOIN users u ON u.id=c.user_id WHERE c.cert_code=? LIMIT 1');
    $st->execute([strtoupper($code)]);
    $cert = $st->fetch();
    json_response(['success'=>true,'valid'=>(bool)$cert,'certificate'=>$cert]);
}

Kernel::fail('unknown_action', '', 400);
