<?php

namespace App\Models;

use PDO;
use Config\Database;

class Holiday extends BaseModel
{
    protected static $table = 'holidays';

    public $id;
    public $holiday_day;      
    public $holiday_month;
    public $specific_year;
    public $description;
    public $active;
    public $created_at;
    public $updated_at;
    public $deleted_at;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->active = $data['active'] ?? 1;
    }

    public function save()
    {
        $db = Database::getConnection();

        if ($this->id) {
            $query = "UPDATE holidays 
                      SET holiday_day = :holiday_day, 
                          holiday_month = :holiday_month, 
                          specific_year = :specific_year,
                          description = :description, 
                          active = :active, 
                          updated_at = NOW()
                      WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':holiday_day' => $this->holiday_day,
                ':holiday_month' => $this->holiday_month,
                ':specific_year' => $this->specific_year,
                ':description' => $this->description,
                ':active' => $this->active
            ]);
        } else {
            $query = "INSERT INTO holidays 
                      (holiday_day, holiday_month, specific_year, description, active, created_at, updated_at) 
                      VALUES (:holiday_day, :holiday_month, :specific_year, :description, :active, NOW(), NOW())";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':holiday_day' => $this->holiday_day,
                ':holiday_month' => $this->holiday_month,
                ':specific_year' => $this->specific_year,
                ':description' => $this->description,
                ':active' => $this->active
            ]);
            $this->id = $db->lastInsertId();
        }
    }

    public static function allDatesForYear($year)
    {
        $holidays = self::getActives();
        $dates = [];

        foreach ($holidays as $h) {
            if (is_null($h->specific_year) || $h->specific_year == $year) {
                $dates[] = sprintf('%04d-%02d-%02d', $year, $h->holiday_month, $h->holiday_day);
            }
        }

        return $dates;
    }
}
