<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth'=>false,'public'=>true]);
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/Logger.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
$action = $_GET['action'] ?? 'list';
$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$guest  = ['id'=>0,'subscription_tier'=>'free','neighborhood_id'=>0,'state'=>'','city'=>''];
$u      = $action === 'list' ? (current_user() ?: $guest) : require_auth();

if ($action === 'list') {
    $state = $_GET['state'] ?? $u['state'] ?? '';
    $st = db()->prepare("SELECT e.*,u.name AS organizer FROM community_events e JOIN users u ON u.id=e.organizer_id WHERE e.status IN ('upcoming','active')" . ($state?" AND e.state=?":'') . " ORDER BY e.event_date ASC LIMIT 50");
    $st->execute($state ? [$state] : []);
    json_response(['success'=>true,'events'=>$st->fetchAll()]);
}

if ($action === 'create') {
    $title    = mb_substr(trim($b['title']??''), 0, 300);
    $desc     = mb_substr(trim($b['description']??''), 0, 2000);
    $category = in_array($b['category']??'', ['health','education','social','sport','culture','volunteer','market','other']) ? $b['category'] : 'social';
    $date     = $b['event_date'] ?? '';
    $location = mb_substr(trim($b['location']??''), 0, 300);
    if (!$title || !$date) json_response(['error'=>'missing_fields'], 400);
    if (!check_rate_limit('event_'.$u['id'], 5, 86400)) json_response(['error'=>'rate_limit'], 429);
    $img = null;
    if (!empty($b['image_base64'])) $img = save_uploaded_image($b['image_base64']);
    db()->prepare('INSERT INTO community_events (organizer_id,neighborhood_id,state,city,title,description,category,event_date,end_date,location,max_participants,image_url,is_free) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)')->execute([$u['id'],$u['neighborhood_id']?:null,$u['state']??'',$u['city']??'',$title,$desc,$category,$date,$b['end_date']??null,$location,$b['max_participants']??null,$img,(int)($b['is_free']??1)]);
    $eid = (int)db()->lastInsertId();
    db()->prepare('UPDATE users SET points_community=points_community+10 WHERE id=?')->execute([$u['id']]);
    json_response(['success'=>true,'event_id'=>$eid,'message'=>'تم نشر الفعالية ✅']);
}

if ($action === 'join') {
    $eid = (int)($b['event_id']??0);
    $ev  = db()->prepare('SELECT * FROM community_events WHERE id=? AND status IN ("upcoming","active") LIMIT 1'); $ev->execute([$eid]); $event=$ev->fetch();
    if (!$event) json_response(['error'=>'not_found'], 404);
    if ($event['max_participants']) {
        $cnt = db()->prepare('SELECT COUNT(*) FROM event_participants WHERE event_id=?'); $cnt->execute([$eid]);
        if ($cnt->fetchColumn() >= $event['max_participants']) json_response(['error'=>'full','message'=>'الفعالية ممتلئة'], 409);
    }
    db()->prepare('INSERT IGNORE INTO event_participants (event_id,user_id) VALUES (?,?)')->execute([$eid,$u['id']]);
    db()->prepare('UPDATE users SET points_community=points_community+5 WHERE id=?')->execute([$u['id']]);
    $cnt2=db()->prepare('SELECT COUNT(*) FROM event_participants WHERE event_id=?'); $cnt2->execute([$eid]);
    json_response(['success'=>true,'count'=>(int)$cnt2->fetchColumn()]);
}

json_response(['error'=>'unknown_action'], 400);
