<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
require __DIR__.'/../src/db.php';
require __DIR__.'/../src/helpers.php';

$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$base = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
if ($base && str_starts_with($uri, $base)) $uri = substr($uri, strlen($base));
$path = '/' . trim($uri, '/');

try {
    if ($method==='GET' && $path==='/health') json_response(['ok'=>true,'time'=>date(DATE_ATOM)]);

    if ($method==='GET' && $path==='/home') {
        $pdo=db();
        $settings=$pdo->query('SELECT * FROM app_settings WHERE id=1')->fetch();
        $banners=$pdo->query('SELECT * FROM banners WHERE is_active=1 ORDER BY sort_order,id DESC')->fetchAll();
        $features=$pdo->query('SELECT * FROM feature_cards WHERE is_active=1 ORDER BY section_key,sort_order,id')->fetchAll();
        $stats=[
          'donors'=>(int)$pdo->query('SELECT COUNT(*) FROM donors')->fetchColumn(),
          'active_requests'=>(int)$pdo->query("SELECT COUNT(*) FROM blood_requests WHERE status IN ('pending','approved')")->fetchColumn(),
          'successful_donations'=>(int)$pdo->query("SELECT COUNT(*) FROM blood_requests WHERE status='completed'")->fetchColumn(),
        ];
        json_response(compact('settings','banners','features','stats'));
    }

    if ($method==='GET' && $path==='/donors') {
        $where=['1=1']; $args=[];
        if (!empty($_GET['blood_group'])) {$where[]='blood_group=?'; $args[]=clean_string($_GET['blood_group'],5);} 
        if (!empty($_GET['district'])) {$where[]='district LIKE ?'; $args[]='%'.clean_string($_GET['district'],100).'%';}
        if (!empty($_GET['q'])) {$where[]='(name LIKE ? OR district LIKE ? OR upazila LIKE ?)'; $q='%'.clean_string($_GET['q'],120).'%'; array_push($args,$q,$q,$q);} 
        $sql='SELECT *, CASE WHEN last_donation_date IS NULL OR DATEDIFF(CURDATE(),last_donation_date)>=120 THEN 1 ELSE 0 END AS can_donate FROM donors WHERE '.implode(' AND ',$where).' ORDER BY available DESC, verified DESC, id DESC LIMIT 200';
        $s=db()->prepare($sql); $s->execute($args); json_response(['data'=>$s->fetchAll()]);
    }

    if ($method==='GET' && $path==='/requests') {
        $s=db()->query("SELECT * FROM blood_requests WHERE status IN ('pending','approved') ORDER BY donation_date ASC, id DESC LIMIT 200");
        json_response(['data'=>$s->fetchAll()]);
    }

    if ($method==='POST' && $path==='/requests') {
        $d=input_json();
        foreach(['patient_problem','blood_group','donation_date','hospital','contact_phone'] as $k) if(empty($d[$k])) json_response(['message'=>"$k is required"],422);
        $s=db()->prepare('INSERT INTO blood_requests(patient_problem,blood_group,bag_count,hemoglobin,donation_date,donation_time,hospital,district,contact_phone,details) VALUES(?,?,?,?,?,?,?,?,?,?)');
        $s->execute([clean_string($d['patient_problem']),clean_string($d['blood_group'],5),max(1,(int)($d['bag_count']??1)),clean_string($d['hemoglobin']??'',30),$d['donation_date'],$d['donation_time']??null,clean_string($d['hospital']),clean_string($d['district']??'',100),clean_string($d['contact_phone'],40),clean_string($d['details']??'',2000)]);
        json_response(['message'=>'Request submitted','id'=>(int)db()->lastInsertId()],201);
    }

    if ($method==='POST' && $path==='/admin/login') {
        $d=input_json(); $email=clean_string($d['email']??'',190); $pass=(string)($d['password']??'');
        $s=db()->prepare('SELECT * FROM admins WHERE email=? LIMIT 1'); $s->execute([$email]); $a=$s->fetch();
        if(!$a || !password_verify($pass,$a['password_hash'])) json_response(['message'=>'Invalid credentials'],401);
        $token=bin2hex(random_bytes(32)); db()->prepare('UPDATE admins SET token=? WHERE id=?')->execute([$token,$a['id']]);
        json_response(['token'=>$token,'admin'=>['id'=>$a['id'],'name'=>$a['name'],'email'=>$a['email']]]);
    }

    if ($method==='GET' && $path==='/admin/dashboard') {
        require_admin(); $pdo=db();
        json_response(['stats'=>[
          'donors'=>(int)$pdo->query('SELECT COUNT(*) FROM donors')->fetchColumn(),
          'requests'=>(int)$pdo->query('SELECT COUNT(*) FROM blood_requests')->fetchColumn(),
          'pending'=>(int)$pdo->query("SELECT COUNT(*) FROM blood_requests WHERE status='pending'")->fetchColumn(),
          'campaigns'=>(int)$pdo->query('SELECT COUNT(*) FROM campaigns WHERE is_active=1')->fetchColumn(),
        ]]);
    }

    if ($method==='GET' && $path==='/admin/donors') { require_admin(); json_response(['data'=>db()->query('SELECT * FROM donors ORDER BY id DESC LIMIT 500')->fetchAll()]); }
    if ($method==='POST' && $path==='/admin/donors') {
        require_admin(); $d=input_json(); foreach(['name','phone','blood_group','district'] as $k) if(empty($d[$k])) json_response(['message'=>"$k is required"],422);
        $s=db()->prepare('INSERT INTO donors(name,phone,blood_group,district,upazila,address,photo_url,last_donation_date,available,verified) VALUES(?,?,?,?,?,?,?,?,?,?)');
        $s->execute([clean_string($d['name'],160),clean_string($d['phone'],40),clean_string($d['blood_group'],5),clean_string($d['district'],100),clean_string($d['upazila']??'',100),clean_string($d['address']??''),clean_string($d['photo_url']??'',1000),$d['last_donation_date']??null,!empty($d['available'])?1:0,!empty($d['verified'])?1:0]);
        json_response(['message'=>'Donor added','id'=>(int)db()->lastInsertId()],201);
    }
    if ($method==='GET' && $path==='/admin/requests') { require_admin(); json_response(['data'=>db()->query('SELECT * FROM blood_requests ORDER BY id DESC LIMIT 500')->fetchAll()]); }
    if ($method==='PUT' && preg_match('#^/admin/requests/(\d+)$#',$path,$m)) {
        require_admin(); $d=input_json(); $allowed=['pending','approved','completed','cancelled']; $status=$d['status']??''; if(!in_array($status,$allowed,true)) json_response(['message'=>'Invalid status'],422);
        db()->prepare('UPDATE blood_requests SET status=? WHERE id=?')->execute([$status,(int)$m[1]]); json_response(['message'=>'Updated']);
    }
    if ($method==='GET' && $path==='/admin/banners') { require_admin(); json_response(['data'=>db()->query('SELECT * FROM banners ORDER BY sort_order,id DESC')->fetchAll()]); }
    if ($method==='POST' && $path==='/admin/banners') {
        require_admin(); $d=input_json(); if(empty($d['title'])) json_response(['message'=>'title is required'],422);
        $s=db()->prepare('INSERT INTO banners(title,subtitle,image_url,is_active,sort_order) VALUES(?,?,?,?,?)'); $s->execute([clean_string($d['title'],190),clean_string($d['subtitle']??''),clean_string($d['image_url']??'',1000),!empty($d['is_active'])?1:0,(int)($d['sort_order']??0)]); json_response(['message'=>'Banner added'],201);
    }
    if ($method==='DELETE' && preg_match('#^/admin/banners/(\d+)$#',$path,$m)) { require_admin(); db()->prepare('DELETE FROM banners WHERE id=?')->execute([(int)$m[1]]); json_response(['message'=>'Deleted']); }

    if ($method==='GET' && $path==='/admin/settings') { require_admin(); json_response(db()->query('SELECT * FROM app_settings WHERE id=1')->fetch()); }
    if ($method==='PUT' && $path==='/admin/settings') {
        require_admin(); $d=input_json();
        $s=db()->prepare('UPDATE app_settings SET organization_name=?,tagline=?,primary_color=?,emergency_phone=? WHERE id=1');
        $s->execute([clean_string($d['organization_name']??'',190),clean_string($d['tagline']??''),clean_string($d['primary_color']??'#C62828',20),clean_string($d['emergency_phone']??'',40)]); json_response(['message'=>'Settings updated']);
    }

    json_response(['message'=>'Not found','path'=>$path],404);
} catch (Throwable $e) {
    json_response(['message'=>'Server error','error'=>$e->getMessage()],500);
}
