<?php

namespace App\Controllers\Potensiwilayah;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Kelolalokasi extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->LokasiModel = model('App\Models\Potensiwilayah\KelokasiModel');
    }



    public function index()
    {
        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        $user_id = auth()->id();
        
        // Get user data to get id_kantor
        $user_data = auth()->user();
        $id_kantor = $user_data->id_kantor ?? null;
        
        // Get kantor location
        $kantor_location = $this->LokasiModel->getKantorLocation($user_id);
        
        // Get kategori lokasi
        $kategori_lokasi = $this->LokasiModel->getLokasiKategori();

        return view('potwil/kelola_lokasi/page_map', [
            'title' => 'Kelola Lokasi',
            'map_api' => $map_api,
            'kantor_location' => $kantor_location,
            'kategori_lokasi' => $kategori_lokasi,
            'id_kantor' => $id_kantor
        ]);
    }

    public function saveLokasi()
    {
        $user_id = auth()->id();
        
        $data = [
            'id_kategori' => $this->request->getPost('kategori_id'),
            'nama_lokasi' => $this->request->getPost('nama'),
            'alamat' => $this->request->getPost('alamat'),
            'lati' => $this->request->getPost('latitude'),
            'longi' => $this->request->getPost('longitude'),
            'id_kantor' => $this->request->getPost('id_kantor'),
            'place_id' => $this->request->getPost('place_id'),
            'phone' => $this->request->getPost('phone'),
            'website' => $this->request->getPost('website'),
            'rating' => $this->request->getPost('rating'),
            'id_rek' => $user_id,
            'wkt_rek' => timestamp(),
        ];

        // Check if location already exists
        $existing = $this->LokasiModel->checkLocationExists($data['place_id']);
        if ($existing) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Lokasi sudah pernah disimpan sebelumnya'
            ])->setStatusCode(400);
        }

        $result = $this->LokasiModel->saveLokasiToMain($data);
        
        if ($result) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Lokasi berhasil disimpan'
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error', 
                'message' => 'Gagal menyimpan lokasi'
            ])->setStatusCode(500);
        }
    }
}