<?php

namespace App\Controllers\Api;

use App\Controllers\BaseController;
use App\Models\ServiceModel;
use App\Services\DispatchService;

class CareApi extends BaseController
{
    public function nearby()
    {
        $service=(int)($this->request->getGet('service') ?: 0); $lat=$this->request->getGet('lat'); $lng=$this->request->getGet('lng');
        $rows=(new DispatchService())->nearbyPractitioners($service ?: null,$lat!==null?(float)$lat:null,$lng!==null?(float)$lng:null,20);
        foreach($rows as &$row){unset($row['latitude'],$row['longitude'],$row['user_id'],$row['email']);} unset($row);
        return $this->response->setJSON(['data'=>$rows,'meta'=>['count'=>count($rows)]]);
    }
    public function services(){ return $this->response->setJSON(['data'=>(new ServiceModel())->where('is_active',1)->orderBy('sort_order')->findAll()]); }
    public function requestStatus(int $id)
    {
        $db=db_connect();
        $row=$db->table('care_requests')->select('id,patient_id,status,assigned_practitioner_id,accepted_at,updated_at')->where('id',$id)->get()->getRowArray();
        if(!$row) return $this->response->setStatusCode(404)->setJSON(['error'=>'Not found']);
        $user=auth_user(); $allowed=in_array($user['role'] ?? '',['admin','operations'],true);
        if(($user['role'] ?? '')==='patient'){$patient=$db->table('patient_profiles')->select('id')->where('user_id',$user['id'])->get()->getRowArray();$allowed=$patient && (int)$patient['id']===(int)$row['patient_id'];}
        if(($user['role'] ?? '')==='practitioner'){$p=$db->table('practitioner_profiles')->select('id')->where('user_id',$user['id'])->get()->getRowArray();$allowed=$p && (int)$p['id']===(int)$row['assigned_practitioner_id'];}
        if(!$allowed) return $this->response->setStatusCode(403)->setJSON(['error'=>'Forbidden']);
        unset($row['patient_id']);
        return $this->response->setJSON(['data'=>$row]);
    }
}
