<?php
namespace App\Controllers;

use App\Traits\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\AreaGeoModel;

class AreaGeoController extends BaseController {
	use ResponseTrait;
	
	protected $model;

	public function __construct() {	
		$this->model = new AreaGeoModel();
	}

    public function index() {
        try {
            $filters = [
                'AreaGeoID' => $this->request->getVar('AreaGeoID') ?? null,
                'AreaName' => $this->request->getVar('AreaName') ?? null
            ];
            $rows = $this->model->getAreaGeos( $filters );

            if(empty($rows)){return $this->respond(['status'=>'success', 'message'=>"no data found.", 'data'=>$rows], 200);}
            return $this->respond(['status'=>'success', 'message'=>"data fetched successfully", 'data'=>$rows], 200);
        } catch (\Exception $e) {
            return $this->respond([ 'status' => 'error', 'message' => $e->getMessage() ], 200);
        }

    }

    public function getProvinces() {
        $rows = $this->model->getProvinces();
        $transformed = array_map(function($row) {
            return ['value' => $row['AreaGeoID'], 'label' => $row['AreaName']];
        }, $rows);
        if (empty($transformed)) { return $this->respond([ 'status'  => 'success', 'data' => [] ], 200); }
        return $this->respond([ 'status' => 'success', 'data' => $transformed ], 200);
    }

    public function getCities() {
        $filter = [ 'Parent' => $this->request->getVar('ProvinceID') ?? null ];
        $rows = $this->model->getCities($filter);
        $transformed = array_map(function($row) {
            return ['value' => $row['AreaGeoID'], 'label' => $row['AreaName']];
        }, $rows);
        if (empty($transformed)) { return $this->respond([ 'status'  => 'success', 'data' => [] ], 200); }
        return $this->respond([ 'status' => 'success', 'data' => $transformed ], 200);
    }
   
}
