<?php

namespace App\Controllers\Panel\Elearning;

use App\Controllers\Panel\BC;
use CodeIgniter\API\ResponseTrait;
use GuzzleHttp\Client;

class JadwalLibur extends BC
{
    use ResponseTrait;
    public function index()
    {
        return view('Panel/Elearning/JadwalLibur/index', ['page_title' => "Jadwal Libur"]);
    }
    private function getWeekend($start, $end, $withSaturday = false)
    {
        $start = strtotime($start);
        $end = strtotime($end);
        $date = [];
        while (date("Y-m-d", $start) != date("Y-m-d", $end)) {
            $day_index = date("w", $start);
            if ($day_index == 0 || ($day_index == 6 && $withSaturday)) {
                // Print or store the weekends here
                $date[] = [
                    "tanggal" => date('Y-m-d', $start),
                    "title" => "Libur",
                    "is_nasional" => 1
                ];
            }
            $start = strtotime(date("Y-m-d", $start) . "+1 day");
        }
        return $date;
    }

    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $db = db_connect();
        $events = $db->table('jadwal_libur')->select("id,title,tanggal as start");
        if ($this->request->getGet('nasional') == "no") $events->where('is_nasional', 0);
        if ($this->request->getGet('nasional') == "yes") $events->where('is_nasional', 1);
        $events = $events->get()->getResultArray();
        return $this->respond($events);
    }
    public function sinkronisasi_libur()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $text = "Berhasil Mensikronkan Data, Silahkan Cek Kembali Apabila Ada Kesalahan";
        $data = $this->sync1();
        if (!$data) $data = $this->sync2();
        if (!$data) return $this->fail(['message' => "Tidak Dapat Menyinkronkan"]);
        if ($this->request->getGet('j') == '6d') $data = [...$data, ...$this->getWeekend(date("Y") . "-01-01", date("Y") . "-12-31", false)];
        if ($this->request->getGet('j') == '5d') $data = [...$data, ...$this->getWeekend(date("Y") . "-01-01", date("Y") . "-12-31", true)];
        $sql = [];
        $escData = [];
        foreach ($data as $k => $v) {
            $sql[] = "(?,?,?)";
            $escData[] = $v['tanggal'];
            $escData[] = $v['title'];
            $escData[] = $v['is_nasional'];
        }
        if ($this->request->getGet('j') == '6d') $data = [...$data, ...$this->getWeekend(date("Y") . "-01-01", date("Y") . "-12-31", false)];
        if ($this->request->getGet('j') == '5d') $data = [...$data, ...$this->getWeekend(date("Y") . "-01-01", date("Y") . "-12-31", true)];

        $sql = "INSERT INTO jadwal_libur(tanggal,title,is_nasional) VALUES " . implode(',', $sql) . " ON DUPLICATE KEY UPDATE tanggal=VALUES(tanggal), title=VALUES(title), is_nasional=VALUES(is_nasional),updated_at=CURRENT_TIMESTAMP";
        $db = db_connect();
        $db->transStart();
        $db->query($sql, $escData);
        if ($this->request->getGet('j') == '6d') {
            $db->query("DELETE FROM jadwal_libur WHERE DAYOFWEEK(tanggal) = 7");
        } else if ($this->request->getGet('j') != '5d') {
            $db->query("DELETE FROM jadwal_libur WHERE DAYOFWEEK(tanggal) IN (1, 7)");
        }
        $db->transComplete();
        if ($db->transStatus() === FALSE) return $this->respond(['message' => "Gagal Menyimpan Data"]);
        return $this->respond(['message' => $text]);
    }
    private function sync1()
    {
        $client = new Client([
            'verify' => false
        ]);
        try {
            $response = $client->request('GET', "https://api-harilibur.vercel.app/api", [
                'query' => ['year' => date("Y")]
            ]);
            $data = json_decode($response->getBody()->getContents(), true);
            if ($response->getStatusCode() != 200 && !$data) return false;
            $d = [];
            foreach ($data as $k => $v) {
                //tanggal
                //title
                //is_nasional
                $d[] = [
                    'tanggal' => $v['holiday_date'],
                    'title' => $v['holiday_name'],
                    'is_nasional' => $v['is_national_holiday'] ? 1 : 0
                ];
            }
            return $d;
        } catch (\Throwable $th) {
            return false;
        }
    }
    private function sync2()
    {

        $client = new Client([
            'verify' => false
        ]);
        try {
            $response = $client->request('GET', "https://raw.githubusercontent.com/guangrei/Json-Indonesia-holidays/master/calendar.json");
            $data = json_decode($response->getBody()->getContents(), true);
            if ($response->getStatusCode() != 200 && !$data) return false;
            $d = [];
            foreach ($data as $k => $v) {
                //tanggal
                //title
                //is_nasional
                if (!is_numeric($k) && $v['status'] != 'CONFIRMED') continue;
                $d[] = [
                    'tanggal' => date("Y-m-d", strtotime($k)),
                    'title' => $v['deskripsi'],
                    'is_nasional' => 0
                ];
            }
        } catch (\Throwable $th) {
            return false;
        }
    }

    public function detail()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $db = db_connect();
        $event = $db->table('jadwal_libur');
        $id = $this->request->getGet('id');
        $tanggal = $this->request->getGet('tanggal');
        if (!$id && !$tanggal) return $this->failForbidden();
        if ($id) $event->where('id', $id);
        if ($tanggal) $event->where('tanggal', $tanggal);
        $event = $event->get()->getRowArray();
        return $this->respond(['data' => $event]);
    }

    public function delete()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $db = db_connect();
        if ($this->request->getVar('id')) $db->table('jadwal_libur')->where('id', $this->request->getVar('id'))->delete();
        if ($this->request->getVar('tanggal')) $db->table('jadwal_libur')->where('tanggal', $this->request->getVar('tanggal'))->delete();
        if ($db->affectedRows() > 0) return $this->respond(['message' => "Berhasil Menghapus"]);
        return $this->fail(['message' => "Gagal Menghapus"]);
    }

    public function save()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $tanggal = $this->request->getVar('tanggal');
        $title = $this->request->getVar('title');
        $is_nasional = $this->request->getVar('is_nasional') ?? 1;
        $sql = "INSERT INTO jadwal_libur(tanggal,title,is_nasional) VALUES ('$tanggal','$title',$is_nasional) ON DUPLICATE KEY UPDATE tanggal=VALUES(tanggal), title=VALUES(title), is_nasional=VALUES(is_nasional),updated_at=CURRENT_TIMESTAMP";
        $db = db_connect();
        $db->query($sql);
        if ($db->affectedRows() > 0) return $this->respond(['message' => "Berhasil Memasukan Data"]);
        return $this->fail(['message' => "Gagal Memasukan Data"]);
    }
}
