<?php

namespace App\Models;

use CodeIgniter\Model;

class CalendarEventsModel extends Model
{
    protected $table            = 't_calendar_events';
    protected $primaryKey       = 'PK_Event';

    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;

    protected $allowedFields    = [
        'FK_User',
        'Title',
        'Description',
        'Start_Date',
        'End_Date',
        'All_Day',
        'Status',
        'Color',
        'Created_At',
        'Updated_At'
    ];

    protected $useTimestamps    = false;

    /* =====================================================
     |  BASE QUERY CON USUARIO
     ===================================================== */

    /**
     * Query base con JOIN a usuarios
     */
    protected function baseWithUser()
    {
        return $this->select('
                t_calendar_events.*,
                t_users.Name AS Name
            ')
            ->join('t_users', 't_users.PK_User = t_calendar_events.FK_User', 'left');
    }

    /* =====================================================
     |  CORE
     ===================================================== */

    /**
     * Eventos por usuario y rango
     * (maneja eventos que cruzan fechas)
     */
    public function getEventsByUserAndRange(
        int $userId,
        string $start,
        string $end
    ): array {
        return $this->baseWithUser()
            ->where('t_calendar_events.FK_User', $userId)
            ->where('t_calendar_events.Start_Date <=', $end)
            ->where('t_calendar_events.End_Date >=', $start)
            ->orderBy('t_calendar_events.Start_Date', 'ASC')
            ->findAll();
    }

    /**
     * Eventos de TODOS los usuarios por rango (ADMIN)
     */
    public function getEventsByRangeAllUsers(
        string $start,
        string $end
    ): array {
        return $this->baseWithUser()
            ->where('t_calendar_events.Start_Date <=', $end)
            ->where('t_calendar_events.End_Date >=', $start)
            ->orderBy('t_calendar_events.Start_Date', 'ASC')
            ->findAll();
    }

    /* =====================================================
     |  HELPERS DE AGENDA
     ===================================================== */

    /**
     * Eventos del mes (usuario normal)
     */
    public function getMonthlyEvents(int $userId, int $year, int $month): array
    {
        $start = "$year-$month-01 00:00:00";
        $end   = date("Y-m-t 23:59:59", strtotime($start));

        return $this->getEventsByUserAndRange($userId, $start, $end);
    }

    /**
     * Eventos del mes (ADMIN)
     */
    public function getMonthlyEventsAll(int $year, int $month): array
    {
        $start = "$year-$month-01 00:00:00";
        $end   = date("Y-m-t 23:59:59", strtotime($start));

        return $this->getEventsByRangeAllUsers($start, $end);
    }

    /**
     * Eventos de la semana (usuario normal)
     */
    public function getWeeklyEvents(int $userId, string $date): array
    {
        $start = date(
            'Y-m-d 00:00:00',
            strtotime('monday this week', strtotime($date))
        );

        $end = date(
            'Y-m-d 23:59:59',
            strtotime('sunday this week', strtotime($date))
        );

        return $this->getEventsByUserAndRange($userId, $start, $end);
    }

    /**
     * Eventos de la semana (ADMIN)
     */
    public function getWeeklyEventsAll(string $date): array
    {
        $start = date(
            'Y-m-d 00:00:00',
            strtotime('monday this week', strtotime($date))
        );

        $end = date(
            'Y-m-d 23:59:59',
            strtotime('sunday this week', strtotime($date))
        );

        return $this->getEventsByRangeAllUsers($start, $end);
    }

    /**
     * Eventos del día (usuario normal)
     */
    public function getDailyEvents(int $userId, string $date): array
    {
        $start = $date . ' 00:00:00';
        $end   = $date . ' 23:59:59';

        return $this->getEventsByUserAndRange($userId, $start, $end);
    }

    /**
     * Eventos del día (ADMIN)
     */
    public function getDailyEventsAll(string $date): array
    {
        $start = $date . ' 00:00:00';
        $end   = $date . ' 23:59:59';

        return $this->getEventsByRangeAllUsers($start, $end);
    }

    /* =====================================================
     |  MUTACIONES
     ===================================================== */

    /**
     * Crear evento
     */
    public function createEvent(array $data): bool
    {
        $data['Created_At'] = date('Y-m-d H:i:s');
        return $this->insert($data) !== false;
    }

    /**
     * Actualizar evento
     */
    public function updateEvent(int $eventId, array $data): bool
    {
        $data['Updated_At'] = date('Y-m-d H:i:s');
        return $this->update($eventId, $data);
    }

    /**
     * Eliminar evento
     */
    public function deleteEvent(int $eventId): bool
    {
        return $this->delete($eventId);
    }
}
