<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';

class BotRegistroMovilizador extends REST_Controller
{
    public function __construct()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Content-Type, Cache-Control');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT');

        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            exit;
        }

        parent::__construct();
    }

    public function index_post()
    {
        $payload = $this->getRequestPayload();

        $text = isset($payload['text']) ? trim((string) $payload['text']) : '';
        $cycle = isset($payload['cycle']) ? (int) $payload['cycle'] : -1;

        if ($cycle < 1 || $cycle > 3) {
            $this->set_response([
                'status' => false,
                'codigo' => 422,
                'message' => 'Invalid cycle for flujo de registro de movilizador.',
                'data' => ['cycle' => $cycle, 'valid_cycles' => [1, 2, 3]],
            ], REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
            return;
        }

        switch ($cycle) {
            case 1:
                $data = $this->handleNombre($text);
                $this->sendResponse($data);
                break;

            case 2:
                $data = $this->handleCedula($text);
                $this->sendResponse($data);
                break;

            case 3:
                $data = $this->handleConfirmacion($text);
                $this->sendResponse($data);
                break;

            default:
                $this->set_response([
                    'status' => false,
                    'codigo' => 422,
                    'message' => 'Cycle not implemented.',
                    'data' => $cycle,
                ], REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
                break;
        }
    }

    public function index_options()
    {
        $this->set_response(null, REST_Controller::HTTP_NO_CONTENT);
    }

    private function handleNombre($text)
    {
        if ($text === '') {
            return $this->validationResponse(
                'El nombre es obligatorio.',
                ['cycle' => 1, 'hint' => 'Por favor escribe tu nombre completo (como aparece en tu cedula).']
            );
        }

        if (!preg_match('/^[a-zA-Z\s]{5,120}$/', $text)) {
            return $this->validationResponse(
                'Nombre invalido. Usa solo letras y espacios (minimo 5 caracteres).',
                ['cycle' => 1, 'hint' => 'Vuelve a escribir tu nombre completo.']
            );
        }

        return [
            'status' => true,
            'codigo' => 1,
            'message' => 'OK',
            'data' => [
                'next_cycle' => 2,
                'message' => 'Gracias. Ahora escribe tu numero de cedula (solo numeros, sin puntos ni espacios).',
                'captured' => ['nombre' => $text],
            ],
            'http_code' => REST_Controller::HTTP_OK,
        ];
    }

    private function handleCedula($text)
    {
        if (!preg_match('/^[0-9]{5,20}$/', $text)) {
            return $this->validationResponse(
                'Cedula invalida. Debe contener solo numeros (5 a 20 digitos).',
                ['cycle' => 2, 'hint' => 'Escribe nuevamente la cedula sin puntos ni espacios.']
            );
        }

        return [
            'status' => true,
            'codigo' => 1,
            'message' => 'OK',
            'data' => [
                'next_cycle' => 3,
                'message' => 'Confirma que tus datos son correctos. Responde: Confirmar o Corregir.',
                'captured' => ['cedula' => $text],
            ],
            'http_code' => REST_Controller::HTTP_OK,
        ];
    }

    private function handleConfirmacion($text)
    {
        $decision = $this->normalize($text);

        if ($decision === 'confirmar') {
            return [
                'status' => true,
                'codigo' => 1,
                'message' => 'OK',
                'data' => [
                    'next_cycle' => 100,
                    'completed' => true,
                    'message' => 'Registro exitoso. Ahora puedes usar el menu principal.',
                    'next_options' => ['Registrar votantes', 'Registrar voto', 'Consultar estado'],
                ],
                'http_code' => REST_Controller::HTTP_OK,
            ];
        }

        if ($decision === 'corregir') {
            return [
                'status' => true,
                'codigo' => 1,
                'message' => 'OK',
                'data' => [
                    'next_cycle' => 1,
                    'completed' => false,
                    'message' => 'Entendido. Reiniciemos el registro del movilizador. Escribe tu nombre completo.',
                ],
                'http_code' => REST_Controller::HTTP_OK,
            ];
        }

        return $this->validationResponse(
            'Respuesta no valida. Debes responder Confirmar o Corregir.',
            ['cycle' => 3, 'hint' => 'Responde exactamente: Confirmar o Corregir.']
        );
    }

    private function getRequestPayload()
    {
        $text = $this->post('text', true);
        $cycle = $this->post('cycle', true);

        if ($text !== null || $cycle !== null) {
            return [
                'text' => $text,
                'cycle' => $cycle,
            ];
        }

        $raw = json_decode($this->input->raw_input_stream, true);
        return is_array($raw) ? $raw : [];
    }

    private function normalize($text)
    {
        $text = trim(strtolower((string) $text));
        return preg_replace('/\s+/', ' ', $text);
    }

    private function validationResponse($message, array $data = [])
    {
        return [
            'status' => false,
            'codigo' => 422,
            'message' => $message,
            'data' => $data,
            'http_code' => REST_Controller::HTTP_UNPROCESSABLE_ENTITY,
        ];
    }

    private function sendResponse(array $payload)
    {
        $httpCode = isset($payload['http_code']) ? (int) $payload['http_code'] : REST_Controller::HTTP_OK;
        unset($payload['http_code']);
        $this->set_response($payload, $httpCode);
    }
}
