<?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' || $action === 'rate' ? (current_user() ?: $guest) : require_auth();

if ($action === 'list') {
    $cat   = $_GET['cat']   ?? '';
    $state = $_GET['state'] ?? $u['state'] ?? '';
    $city  = $_GET['city']  ?? $u['city']  ?? '';
    $allowed_cats = ['health','education','food','services','social','religion','security','transport'];
    $where = "s.status='active'";
    $params = [];
    if ($state) { $where .= ' AND s.state=?'; $params[] = $state; }
    if ($city)  { $where .= ' AND s.city=?';  $params[] = $city; }
    if ($cat && in_array($cat, $allowed_cats)) { $where .= ' AND s.category=?'; $params[] = $cat; }
    $st = db()->prepare("SELECT s.* FROM neighborhood_services s WHERE $where ORDER BY s.rating_avg DESC, s.is_verified DESC LIMIT 100");
    $st->execute($params);
    json_response(['success'=>true,'services'=>$st->fetchAll()]);
}

if ($action === 'add') {
    $name  = mb_substr(trim($b['name']??''), 0, 200);
    $cat   = in_array($b['category']??'', ['health','education','food','services','social','religion','security','transport']) ? $b['category'] : 'services';
    if (!$name) json_response(['error'=>'name_required'], 400);
    $img = null;
    if (!empty($b['image_base64'])) $img = save_uploaded_image($b['image_base64']);
    db()->prepare('INSERT INTO neighborhood_services (provider_user_id,neighborhood_id,state,city,category,sub_category,name,description,address,phone,whatsapp,hours,image_url) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)')->execute([$u['id'],$u['neighborhood_id']?:null,$u['state']??'',$u['city']??'',$cat,$b['sub_category']??'',$name,$b['description']??'',$b['address']??'',$b['phone']??'',$b['whatsapp']??'',$b['hours']??'',$img]);
    json_response(['success'=>true,'message'=>'تم إرسال الخدمة للمراجعة']);
}

if ($action === 'rate') {
    $sid    = (int)($b['service_id']??0);
    $rating = max(1, min(5, (int)($b['rating']??5)));
    $comment= mb_substr(trim($b['comment']??''), 0, 300);
    if (!$u['id']) json_response(['error'=>'login_required'], 401);
    db()->prepare('INSERT INTO service_ratings (service_id,user_id,rating,comment) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE rating=?,comment=?')->execute([$sid,$u['id'],$rating,$comment,$rating,$comment]);
    $avg = db()->prepare('SELECT AVG(rating),COUNT(*) FROM service_ratings WHERE service_id=?'); $avg->execute([$sid]); $row=$avg->fetch(PDO::FETCH_NUM);
    db()->prepare('UPDATE neighborhood_services SET rating_avg=?,rating_count=? WHERE id=?')->execute([round($row[0],2),$row[1],$sid]);
    json_response(['success'=>true,'new_avg'=>round($row[0],2)]);
}

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