<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ScheduleTimeslotModel;

class ScheduleTimeslot extends BaseController
{
    protected ScheduleTimeslotModel $model;

    public function __construct()
    {
        $this->model = new ScheduleTimeslotModel();
    }

    // ----------------------------------------------------------
    // INDEX
    // ----------------------------------------------------------
    public function index(): string
    {
        $grouped     = $this->model->getGroupedByDay();
        $selectedDay = (int)($this->request->getGet('day') ?? 1);

        return view('schedule_timeslot/index', [
            'title'       => 'Setting Slot Waktu Jadwal',
            'grouped'     => $grouped,
            'selectedDay' => $selectedDay,
            'slotTypes'   => ScheduleTimeslotModel::slotTypes(),
        ]);
    }

    // ----------------------------------------------------------
    // STORE
    // ----------------------------------------------------------
    public function store()
    {
        $rules = [
            'day'         => 'required|integer|in_list[1,2,3,4,5,6]',
            'slot_number' => 'required|integer|greater_than[0]',
            'label'       => 'required|max_length[30]',
            'start_time'  => 'required',
            'end_time'    => 'required',
            'slot_type'   => 'required|in_list[kbm,istirahat,upacara,keagamaan,lainnya]',
        ];

        if (!$this->validate($rules)) {
            $errors = implode('<br>', $this->validator->getErrors());
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $errors]);
            }
            return redirect()->back()->withInput()->with('error', $errors);
        }

        $day        = (int)$this->request->getPost('day');
        $slotNumber = (int)$this->request->getPost('slot_number');

        if ($this->model->isDuplicate($day, $slotNumber)) {
            $msg = 'Slot ke-' . $slotNumber . ' pada hari ' . ScheduleTimeslotModel::dayName($day) . ' sudah ada.';
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $msg]);
            }
            return redirect()->back()->withInput()->with('error', $msg);
        }

        $this->model->insert([
            'day'         => $day,
            'slot_number' => $slotNumber,
            'label'       => $this->request->getPost('label'),
            'start_time'  => $this->request->getPost('start_time'),
            'end_time'    => $this->request->getPost('end_time'),
            'slot_type'   => $this->request->getPost('slot_type'),
            'is_active'   => 1,
        ]);

        if ($this->request->isAJAX()) {
            return $this->response->setJSON(['success' => true, 'message' => 'Slot waktu berhasil ditambahkan.']);
        }

        return redirect()->to('/schedule-timeslot?day=' . $day)
            ->with('success', 'Slot waktu berhasil ditambahkan.');
    }

    // ----------------------------------------------------------
    // UPDATE
    // ----------------------------------------------------------
    public function update(int $id)
    {
        $slot = $this->model->find($id);
        if (!$slot) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => 'Data tidak ditemukan.']);
            }
            return redirect()->to('/schedule-timeslot')->with('error', 'Data tidak ditemukan.');
        }

        $rules = [
            'label'      => 'required|max_length[30]',
            'start_time' => 'required',
            'end_time'   => 'required',
            'slot_type'  => 'required|in_list[kbm,istirahat,upacara,keagamaan,lainnya]',
        ];

        if (!$this->validate($rules)) {
            $errors = implode('<br>', $this->validator->getErrors());
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $errors]);
            }
            return redirect()->back()->withInput()->with('error', $errors);
        }

        $this->model->update($id, [
            'label'      => $this->request->getPost('label'),
            'start_time' => $this->request->getPost('start_time'),
            'end_time'   => $this->request->getPost('end_time'),
            'slot_type'  => $this->request->getPost('slot_type'),
        ]);

        if ($this->request->isAJAX()) {
            return $this->response->setJSON(['success' => true, 'message' => 'Slot waktu berhasil diperbarui.']);
        }

        return redirect()->to('/schedule-timeslot?day=' . $slot['day'])
            ->with('success', 'Slot waktu berhasil diperbarui.');
    }

    // ----------------------------------------------------------
    // DELETE
    // ----------------------------------------------------------
    public function delete(int $id)
    {
        $slot = $this->model->find($id);
        if (!$slot) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => 'Data tidak ditemukan.']);
            }
            return redirect()->to('/schedule-timeslot')->with('error', 'Data tidak ditemukan.');
        }

        $this->model->delete($id);

        if ($this->request->isAJAX()) {
            return $this->response->setJSON(['success' => true, 'message' => 'Slot waktu berhasil dihapus.']);
        }

        return redirect()->to('/schedule-timeslot?day=' . $slot['day'])
            ->with('success', 'Slot waktu berhasil dihapus.');
    }

    // ----------------------------------------------------------
    // TOGGLE ACTIVE
    // ----------------------------------------------------------
    public function toggleActive(int $id)
    {
        $slot = $this->model->find($id);
        if (!$slot) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => 'Data tidak ditemukan.']);
            }
            return redirect()->to('/schedule-timeslot')->with('error', 'Data tidak ditemukan.');
        }

        $this->model->update($id, ['is_active' => $slot['is_active'] ? 0 : 1]);

        if ($this->request->isAJAX()) {
            return $this->response->setJSON(['success' => true, 'message' => 'Status slot berhasil diubah.']);
        }

        return redirect()->to('/schedule-timeslot?day=' . $slot['day'])
            ->with('success', 'Status slot berhasil diubah.');
    }

    // ----------------------------------------------------------
    // COPY DAY
    // ----------------------------------------------------------
    public function copyDay()
    {
        $fromDay = (int)$this->request->getPost('from_day');
        $toDays  = $this->request->getPost('to_days') ?? [];

        if (empty($fromDay) || empty($toDays)) {
            $msg = 'Pilih hari sumber dan hari tujuan.';
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $msg]);
            }
            return redirect()->to('/schedule-timeslot')->with('error', $msg);
        }

        $sourceSlots = $this->model->where('day', $fromDay)->orderBy('slot_number')->findAll();
        if (empty($sourceSlots)) {
            $msg = 'Hari sumber belum memiliki slot waktu.';
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $msg]);
            }
            return redirect()->to('/schedule-timeslot?day=' . $fromDay)->with('error', $msg);
        }

        $inserted = 0;
        foreach ($toDays as $toDay) {
            $toDay = (int)$toDay;
            if ($toDay === $fromDay) continue;

            foreach ($sourceSlots as $slot) {
                if (!$this->model->isDuplicate($toDay, $slot['slot_number'])) {
                    $this->model->insert([
                        'day'         => $toDay,
                        'slot_number' => $slot['slot_number'],
                        'label'       => $slot['label'],
                        'start_time'  => $slot['start_time'],
                        'end_time'    => $slot['end_time'],
                        'slot_type'   => $slot['slot_type'],
                        'is_active'   => 1,
                    ]);
                    $inserted++;
                }
            }
        }

        $msg = "Berhasil menyalin {$inserted} slot ke " . count($toDays) . " hari.";
        if ($this->request->isAJAX()) {
            return $this->response->setJSON(['success' => true, 'message' => $msg]);
        }

        return redirect()->to('/schedule-timeslot?day=' . $fromDay)->with('success', $msg);
    }

    // ----------------------------------------------------------
    // DELETE DAY
    // ----------------------------------------------------------
    public function deleteDay()
    {
        $day = (int)$this->request->getPost('day');
        if ($day < 1 || $day > 6) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => 'Hari tidak valid.']);
            }
            return redirect()->to('/schedule-timeslot')->with('error', 'Hari tidak valid.');
        }

        $this->model->where('day', $day)->delete();

        if ($this->request->isAJAX()) {
            return $this->response->setJSON(['success' => true, 'message' => 'Semua slot waktu pada hari ' . ScheduleTimeslotModel::dayName($day) . ' berhasil dihapus.']);
        }

        return redirect()->to('/schedule-timeslot?day=' . $day)
            ->with('success', 'Semua slot waktu pada hari ' . ScheduleTimeslotModel::dayName($day) . ' berhasil dihapus.');
    }
}