2025-11-04 09:42:03 +07:00

88 lines
3.0 KiB
PHP

<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\SyncCRM\ZonesModel;
class Zones extends BaseController {
use ResponseTrait;
protected $model;
public function __construct() {
$this->model = new ZonesModel();
}
public function index() {
try {
$rows = $this->model->getZones();
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() {
$filters = [
'zoneid' => $this->request->getVar('zoneid') ?? null,
'zonename' => $this->request->getVar('zonename') ?? null
];
$rows = $this->model->getProvinces();
if (empty($rows)) { return $this->respond([ 'status' => 'success', 'message' => "data not found", 'data' => [] ], 200); }
return $this->respond([ 'status' => 'success', 'message'=> "Data fetched successfully", 'data' => $rows ], 200);
}
public function getCities() {
$filter = [
'zoneid' => $this->request->getVar('zoneid') ?? null
];
$rows = $this->model->getCities($filter);
if (empty($rows)) { return $this->respond([ 'status' => 'success', 'message' => "data not found", 'data' => [] ], 200); }
return $this->respond([ 'status' => 'success', 'message'=> "Data fetched successfully", 'data' => $rows ], 200);
}
public function synchronize() {
$client = \Config\Services::curlrequest();
try {
// Ambil data dari API pusat (CRM)
$response = $client->get('http://services-summit.my.id/api/zones');
// $response = $client->get('http://crmcomposer.local/api/zones');
$result = json_decode($response->getBody(), true);
if (!isset($result['data']) || !is_array($result['data'])) {
return $this->response->setJSON([
'status' => 'error',
'message' => 'Invalid or empty response from CRM API'
]);
}
$record = $this->model->synchronize($result['data']);
return $this->response->setJSON([
'status' => 'success',
'message' => 'Zones synchronized successfully',
'summary' => [
'inserted' => $record['inserted'],
'updated' => $record['updated'],
'deleted' => $record['deleted'],
'skipped' => $record['skipped']
]
]);
} catch (\Exception $e) {
return $this->response->setJSON([
'status' => 'error',
'message' => $e->getMessage()
]);
}
}
}