<?php

namespace App\Controllers\Incidence;

use App\Controllers\BaseController;
use App\Models\Incidence\IncidenceModel;
use CodeIgniter\HTTP\Response;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;


$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 IncidenceController extends BaseController
{
    protected $incidenceModel;

    public function __construct(){
        $this->incidenceModel = new IncidenceModel();
    }

    public function GetAllIncidence(){
        $incidence = $this->incidenceModel->findAll();
        return $this->response->setJSON($incidence);
    }

    public function create()
    {
        try {
            $rules = [
                'FK_Location' => 'required|is_natural_no_zero',
                'AffectedArea' => 'required|max_length[80]',
                'Description'  => 'required|max_length[500]',
                'Priority'     => 'required|in_list[Alta,Media,Baja]',
                'RequestDate'  => 'required|valid_date[Y-m-d]',
                // 'Status'    => 'permit_empty|in_list[pendiente,en_proceso,resuelto,cancelado]',
            ];

            if (! $this->validate($rules)) {
                return $this->response->setJSON([
                    'ok' => false,
                    'message' => 'Validación fallida',
                    'errors' => $this->validator->getErrors(),
                ])->setStatusCode(ResponseInterface::HTTP_BAD_REQUEST);
            }

            $data = [
                'FK_Location'  => (int) $this->request->getPost('FK_Location'),
                'AffectedArea' => trim((string) $this->request->getPost('AffectedArea')),
                'Description'  => trim((string) $this->request->getPost('Description')),
                'Priority'     => trim((string) $this->request->getPost('Priority')),
                'RequestDate'  => trim((string) $this->request->getPost('RequestDate')),
                'Status'       => $this->request->getPost('Status') ?: 'pendiente',
            ];

            // Manejo de imagen (opcional)
            $file = $this->request->getFile('image');
            if ($file && $file->isValid() && ! $file->hasMoved()) {
                $ext = $file->getExtension();
                $newName = uniqid('evi_').'.'.$ext;
                $targetDir = WRITEPATH . 'uploads/incidences'; // asegúrate que exista y tenga permisos
                if (! is_dir($targetDir)) {
                    @mkdir($targetDir, 0775, true);
                }
                $file->move($targetDir, $newName);
                // Guarda la ruta relativa para servir estático si tienes un handler público
                $data['Evidence'] = 'uploads/incidences/' . $newName;
            }

            $model = new IncidenceModel();
            $id = $model->insert($data, true);

            if (! $id) {
                return $this->response->setJSON([
                    'ok' => false,
                    'message' => 'No se pudo guardar',
                ])->setStatusCode(ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
            }

            return $this->response->setJSON([
                'ok' => true,
                'id' => (int) $id,
                'message' => 'Incidencia creada',
                'data' => $data,
            ]);
        } catch (\Throwable $e) {
            return $this->response->setJSON([
                'ok' => false,
                'message' => 'Error inesperado',
                'error' => $e->getMessage(),
            ])->setStatusCode(ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function updateStatus($id = null)
    {
        try {
            if (! $id || ! is_numeric($id)) {
                return $this->response->setJSON([
                    'ok' => false,
                    'message' => 'ID inválido'
                ])->setStatusCode(ResponseInterface::HTTP_BAD_REQUEST);
            }

            // Verifica que exista la incidencia
            $incidence = $this->incidenceModel->find($id);
            if (! $incidence) {
                return $this->response->setJSON([
                    'ok' => false,
                    'message' => 'Incidencia no encontrada'
                ])->setStatusCode(ResponseInterface::HTTP_NOT_FOUND);
            }

            // Obtiene JSON o form-data
            $status = $this->request->getJSON()->Status
                ?? $this->request->getPost('Status');

            if (! $status) {
                return $this->response->setJSON([
                    'ok' => false,
                    'message' => 'Status requerido'
                ])->setStatusCode(ResponseInterface::HTTP_BAD_REQUEST);
            }

            // Normaliza
            $status = trim($status);

            // Validación de status permitido
            $allowedStatus = ['Pendiente', 'En Proceso', 'Resuelto'];
            if (! in_array($status, $allowedStatus)) {
                return $this->response->setJSON([
                    'ok' => false,
                    'message' => 'Status no válido',
                    'allowed' => $allowedStatus
                ])->setStatusCode(ResponseInterface::HTTP_BAD_REQUEST);
            }

            // Actualiza
            $this->incidenceModel->update($id, [
                'Status' => $status
            ]);

            return $this->response->setJSON([
                'ok' => true,
                'message' => 'Status actualizado',
                'data' => [
                    'id' => (int) $id,
                    'Status' => $status
                ]
            ]);
        } catch (\Throwable $e) {
            return $this->response->setJSON([
                'ok' => false,
                'message' => 'Error al actualizar status',
                'error' => $e->getMessage()
            ])->setStatusCode(ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

}