<?php

namespace App\Controllers;

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

class FindCare extends BaseController
{
    public function index()
    {
        $service=(int)($this->request->getGet('service') ?: 0);
        $lat=$this->request->getGet('lat'); $lng=$this->request->getGet('lng');
        try {
            $services=(new ServiceModel())->where('is_active',1)->orderBy('sort_order')->findAll();
            $practitioners=(new DispatchService())->nearbyPractitioners($service ?: null,$lat!==null?(float)$lat:null,$lng!==null?(float)$lng:null,20);
        } catch(\Throwable $e) { $services=[]; $practitioners=[]; }
        return $this->render('find/index',['title'=>'Find Care | TibaLeta','services'=>$services,'practitioners'=>$practitioners,'selectedService'=>$service]);
    }

    public function profile(int $id)
    {
        $db=db_connect();
        $p=$db->table('practitioner_profiles pp')->select('pp.*,u.full_name,u.email,u.avatar')->join('users u','u.id=pp.user_id')->where('pp.id',$id)->get()->getRowArray();
        if(!$p) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        $p['services']=$db->table('practitioner_services ps')->select('s.*,ps.price')->join('services s','s.id=ps.service_id')->where(['ps.practitioner_id'=>$id,'ps.is_active'=>1])->get()->getResultArray();
        $p['reviews']=$db->table('reviews r')->select('r.*,u.full_name')->join('users u','u.id=r.patient_id','left')->where(['r.practitioner_id'=>$id,'r.status'=>'published'])->orderBy('r.id','DESC')->limit(6)->get()->getResultArray();
        return $this->render('find/profile',['title'=>$p['full_name'].' | TibaLeta','practitioner'=>$p]);
    }
}
