<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Repositories\TiendaRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class TiendaController
{
    private TiendaRepository $tiendas;

    public function __construct(TiendaRepository $tiendas)
    {
        $this->tiendas = $tiendas;
    }

    public function listar(Request $request, Response $response): Response
    {
        return $this->json($response, $this->tiendas->todas());
    }

    public function ver(Request $request, Response $response, array $args): Response
    {
        $tienda = $this->tiendas->buscarPorId((int) $args['id']);

        if (!$tienda) {
            return $this->json($response, ['error' => 'Tienda no encontrada'], 404);
        }

        return $this->json($response, $tienda);
    }

    public function crear(Request $request, Response $response): Response
    {
        $body = (array) $request->getParsedBody();

        $requeridos = ['nombre', 'direccion', 'lat', 'lng'];
        foreach ($requeridos as $campo) {
            if (!isset($body[$campo]) || $body[$campo] === '') {
                return $this->json($response, ['error' => "El campo {$campo} es requerido"], 422);
            }
        }

        $id = $this->tiendas->crear([
            'usuario_id' => isset($body['usuario_id']) ? (int) $body['usuario_id'] : null,
            'zona_id' => isset($body['zona_id']) ? (int) $body['zona_id'] : null,
            'nombre' => (string) $body['nombre'],
            'direccion' => (string) $body['direccion'],
            'lat' => (float) $body['lat'],
            'lng' => (float) $body['lng'],
            'telefono' => (string) ($body['telefono'] ?? ''),
            'horario_apertura' => $body['horario_apertura'] ?? null,
            'horario_cierre' => $body['horario_cierre'] ?? null,
        ]);

        return $this->json($response, $this->tiendas->buscarPorId($id), 201);
    }

    public function actualizar(Request $request, Response $response, array $args): Response
    {
        $id = (int) $args['id'];
        $tienda = $this->tiendas->buscarPorId($id);
        if (!$tienda) {
            return $this->json($response, ['error' => 'Tienda no encontrada'], 404);
        }

        $body = (array) $request->getParsedBody();
        $this->tiendas->actualizar($id, [
            'zona_id' => isset($body['zona_id']) ? (int) $body['zona_id'] : $tienda['zona_id'],
            'nombre' => (string) ($body['nombre'] ?? $tienda['nombre']),
            'direccion' => (string) ($body['direccion'] ?? $tienda['direccion']),
            'lat' => (float) ($body['lat'] ?? $tienda['lat']),
            'lng' => (float) ($body['lng'] ?? $tienda['lng']),
            'telefono' => (string) ($body['telefono'] ?? $tienda['telefono']),
            'horario_apertura' => $body['horario_apertura'] ?? $tienda['horario_apertura'],
            'horario_cierre' => $body['horario_cierre'] ?? $tienda['horario_cierre'],
        ]);

        return $this->json($response, $this->tiendas->buscarPorId($id));
    }

    private function json(Response $response, $data, int $status = 200): Response
    {
        $response->getBody()->write(json_encode($data));

        return $response->withHeader('Content-Type', 'application/json')->withStatus($status);
    }
}
