<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class HariLibur_model extends CI_Model
{
    const TABLE = 'tb_hari_libur';

    public function get_all($tahun = NULL)
    {
        if ($tahun) $this->db->where('YEAR(tanggal)', $tahun);
        return $this->db->order_by('tanggal', 'ASC')->get(self::TABLE)->result();
    }

    public function get_by_id($id)
    {
        return $this->db->where('id_libur', $id)->get(self::TABLE)->row();
    }

    public function get_by_tanggal($tanggal)
    {
        return $this->db->where('tanggal', $tanggal)->get(self::TABLE)->row();
    }

    public function tanggal_exists($tanggal, $exclude_id = NULL)
    {
        if ($exclude_id) $this->db->where('id_libur !=', $exclude_id);
        return $this->db->where('tanggal', $tanggal)->count_all_results(self::TABLE) > 0;
    }

    public function insert($data)
    {
        $this->db->insert(self::TABLE, $data);
        return $this->db->insert_id();
    }

    public function update($id, $data)
    {
        $this->db->where('id_libur', $id)->update(self::TABLE, $data);
    }

    public function delete($id)
    {
        $this->db->where('id_libur', $id)->delete(self::TABLE);
    }

    public function sync_nasional_batch(array $items)
    {
        $result = [
            'inserted' => 0,
            'updated' => 0,
            'skipped' => 0,
        ];

        foreach ($items as $item) {
            $existing = $this->get_by_tanggal($item['tanggal']);

            if (!$existing) {
                $this->insert($item);
                $result['inserted']++;
                continue;
            }

            if ((string) $existing->jenis === 'PERUSAHAAN') {
                $result['skipped']++;
                continue;
            }

            if ((string) $existing->nama_libur !== (string) $item['nama_libur'] || (string) $existing->jenis !== 'NASIONAL') {
                $this->update((int) $existing->id_libur, $item);
                $result['updated']++;
                continue;
            }

            $result['skipped']++;
        }

        return $result;
    }

    public function get_tahun_list()
    {
        $rows = $this->db->select('YEAR(tanggal) as tahun')
                         ->group_by('YEAR(tanggal)')
                         ->order_by('tahun', 'DESC')
                         ->get(self::TABLE)->result();
        return array_column((array) $rows, 'tahun');
    }
}
