<?php

namespace App\Controllers\Location;

use App\Controllers\BaseController;
use App\Models\Location\LocationModel;
use App\Models\Location\LocationPhotosModel;
use CodeIgniter\HTTP\Response;
use CodeIgniter\API\ResponseTrait;


$allowedOrigins = [
    // 'https://catchef.bravecatstudios.com',  // Producción
    'http://localhost:4200', // Desarrollo en local
    'http://localhost:8000',
];

if (isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins)) {
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}

header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

class LocationController extends BaseController
{
    protected $locationModel;

    public function __construct(){
        $this->locationModel = new LocationModel();
        $this->locationPhotoModel = new LocationPhotosModel();
    }

    public function options($id = null)
    {
        return $this->response->setStatusCode(200);
    }


    public function GetAllLocations(){
        $locations = $this->locationModel->findAll();
        return $this->response->setJSON($locations);
    }

    public function GetLocationByFK($fk){
        $location = $this->locationModel->find($fk);
        if($location){
            return $this->response->setJSON($location);
        }else{
            return $this->response->setJSON(['status' => 'error', 'message' => 'Location not found']);
        }
    }

    public function create()
    {
        helper(['form']);

        $data = [
            'Name' => $this->request->getPost('Name'),
            'Location' => $this->request->getPost('Location'),
            'Water' => $this->request->getPost('Water'),
            'Light' => $this->request->getPost('Light'),
            'Wifi' => $this->request->getPost('Wifi'),
            'Kitchen' => $this->request->getPost('Kitchen'),
            'Yard' => $this->request->getPost('Yard'),
            'Measure' => $this->request->getPost('Measure'),
            'Bath' => $this->request->getPost('Bath'),
            'Rooms' => $this->request->getPost('Rooms'),
            'ParkingSpaces' => $this->request->getPost('ParkingSpaces'),
            'PropertyType' => $this->request->getPost('PropertyType'),
            'Description' => $this->request->getPost('Description'),
            'Price' => $this->request->getPost('Price'),
        ];

        // Inserta los datos
        $locationModel = new LocationModel();
        $locationPhotosModel = new LocationPhotosModel();

        $insertedID = $locationModel->insert($data);

        if (!$insertedID) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'No se pudo insertar la ubicación']);
        }

        // Manejo de imágenes
        $files = $this->request->getFiles();

        if (isset($files['images'])) {
            foreach ($files['images'] as $file) {
                if ($file->isValid() && !$file->hasMoved()) {
                    $path = 'uploads/locations/' . $insertedID;
                    if (!is_dir($path)) {
                        mkdir($path, 0777, true);
                    }

                    $newName = $file->getRandomName();
                    $file->move($path, $newName);

                    // Guardar en la base de datos
                    
                    $locationPhotosModel->insert([
                        'FK_Location' => $insertedID,
                        'ImagePath' => $path . '/' . $newName
                    ]);
                }
            }

            return $this->response->setJSON(['status' => 'success']);
        }
        return $this->response
            ->setContentType('application/json')
            ->setJSON(['status' => 'ok', 'id' => $insertedID]);
    }

    public function update($id)
    {
        // Obtener datos JSON en array asociativo
        $data = $this->request->getJSON(true);

        if (empty($data)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'No se recibieron datos'
            ]);
        }

        $updated = $this->locationModel->update($id, $data);

        if ($updated) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Ubicación actualizada correctamente',
                'id' => $id,
                'data' => $data
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'No se pudo actualizar'
            ]);
        }
    }

}