<?php
namespace App\Models;

use PDO;

/**
 * Modelo de horarios del contenedor
 */
class Schedule extends BaseModel
{
    protected $table = 'schedules';
    
    /**
     * Obtiene todos los horarios ordenados por día
     */
    public function getAll()
    {
        $stmt = $this->db->query("SELECT * FROM schedules ORDER BY day_of_week");
        return $stmt->fetchAll();
    }
    
    /**
     * Obtiene el horario de un día específico
     */
    public function getByDay($dayOfWeek)
    {
        $stmt = $this->db->prepare("SELECT * FROM schedules WHERE day_of_week = ?");
        $stmt->execute([$dayOfWeek]);
        return $stmt->fetch();
    }
    
    /**
     * Actualiza el horario de un día
     */
    public function updateDay($dayOfWeek, $openingTime1, $openingTime2)
    {
        $sql = "INSERT INTO schedules (day_of_week, opening_time_1, opening_time_2) 
                VALUES (:day, :time1, :time2)
                ON DUPLICATE KEY UPDATE 
                opening_time_1 = :time1_upd, 
                opening_time_2 = :time2_upd";
        
        $stmt = $this->db->prepare($sql);
        
        $t1 = $openingTime1 ?: null;
        $t2 = $openingTime2 ?: null;
        
        return $stmt->execute([
            'day' => $dayOfWeek,
            'time1' => $t1,
            'time2' => $t2,
            'time1_upd' => $t1,
            'time2_upd' => $t2
        ]);
    }
    
    /**
     * Obtiene los horarios en formato array asociativo
     */
    public function getScheduleArray()
    {
        $schedules = $this->getAll();
        $result = [];
        
        foreach ($schedules as $schedule) {
            $result[$schedule['day_of_week']] = [
                'opening_time_1' => $schedule['opening_time_1'],
                'opening_time_2' => $schedule['opening_time_2']
            ];
        }
        
        return $result;
    }
}
