<?php

namespace App\Controllers\Pesaing;

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

class Kuralokasi extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->KuralokasiModel = model('App\Models\Pesaing\KuralokasiModel');
    }

    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->KuralokasiModel->getKantorLocation($user_id);

        return view('pesaing/kuralokasi/page_map', [
            'title' => 'Kurasi Lokasi Pesaing',
            'map_api' => $map_api,
            'kantor_location' => $kantor_location,
            'id_kantor' => $id_kantor
        ]);
    }

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

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

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