<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\CalendarEventsModel;
use App\Models\User\UserModel;
use CodeIgniter\HTTP\ResponseInterface;

class AgendaController extends BaseController
{
    protected CalendarEventsModel $eventsModel;

    public function __construct()
    {
        $this->eventsModel = new CalendarEventsModel();
        $this->userModel = new UserModel();
    }

    public function index()
    {
        $userId = session('PK_User');

        if (!$userId) {
            return redirect()->to('/login');
        }

        $view  = $this->request->getGet('view') ?? 'month';
        $date  = $this->request->getGet('date') ?? date('Y-m-d');

        $year  = (int) date('Y', strtotime($date));
        $month = (int) date('m', strtotime($date));

        $role = session('rol');

        switch ($view) {

            case 'week':
                $events = ($role == 1)
                    ? $this->eventsModel->getWeeklyEventsAll($date)
                    : $this->eventsModel->getWeeklyEvents($userId, $date);
                break;

            case 'day':
                $events = ($role == 1)
                    ? $this->eventsModel->getDailyEventsAll($date)
                    : $this->eventsModel->getDailyEvents($userId, $date);
                break;

            default:
                $events = ($role == 1)
                    ? $this->eventsModel->getMonthlyEventsAll($year, $month)
                    : $this->eventsModel->getMonthlyEvents($userId, $year, $month);
                $view = 'month';
                break;
        }
        $users = $this->userModel->findAll();
        return view('agenda/index', [
            'view'   => $view,
            'date'   => $date,
            'year'   => $year,
            'month'  => $month,
            'events' => $events,
            'users'  => $users,
        ]);
    }

    public function events()
    {
        $userId = session('PK_User');

        if (!$userId) {
            return $this->response
                ->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED)
                ->setJSON(['error' => 'No autenticado']);
        }

        // Parámetros opcionales
        $year  = $this->request->getGet('year')  ?? date('Y');
        $month = $this->request->getGet('month') ?? date('m');

        $events = $this->eventsModel->getMonthlyEvents(
            $userId,
            (int) $year,
            (int) $month
        );

        // Normalizamos para frontend
        $response = array_map(function ($event) {
            return [
                'id'        => $event['PK_Event'],
                'title'     => $event['Title'],
                'start'     => $event['Start_Date'],
                'end'       => $event['End_Date'],
                'variant'   => $event['Color'] ?? 'default',
                'allDay'    => (bool) $event['All_Day'],
            ];
        }, $events);

        return $this->response->setJSON($response);
    }

    public function save()
    {
        $data = $this->request->getPost();

        if (empty($data['FK_User'])) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Usuario no seleccionado'
            ]);
        }

        $this->eventsModel->createEvent($data);

        return $this->response->setJSON([
            'status' => 'ok',
            'message' => 'Evento creado'
        ]);
    }


    public function update($id)
    {
        $data = $this->request->getPost();

        if (empty($data['FK_User'])) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Usuario no seleccionado'
            ]);
        }

        $this->eventsModel->updateEvent($id, $data);

        return $this->response->setJSON([
            'status' => 'ok',
            'message' => 'Evento actualizado'
        ]);
    }


    public function delete($id)
    {
        $this->eventsModel->deleteEvent($id);

        return $this->response->setJSON([
            'status' => 'ok',
            'message' => 'Evento eliminado'
        ]);
    }

}
