<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AbsensiModel;
use App\Models\KelasModel;

class Koreksi extends BaseController
{
    public function index()
    {
        $kelasModel = new KelasModel();
        $data = [
            'title' => 'Koreksi Kehadiran',
            'kelas' => $kelasModel->findAll(),
            'tampil_data' => false,
            'active_tab' => 'guru'
        ];
        return view('admin/koreksi/index', $data);
    }

    public function filter()
    {
        $absensiModel = new AbsensiModel();
        $kelasModel = new KelasModel();

        $userType = $this->request->getGet('user_type');
        $tglAwal = $this->request->getGet('tgl_awal');
        $tglAkhir = $this->request->getGet('tgl_akhir');
        $kelasId = $this->request->getGet('kelas_id');

        $dataLaporan = [];
        if ($userType && $tglAwal && $tglAkhir) {
            $dataLaporan = $absensiModel->getKoreksiData($tglAwal, $tglAkhir, $userType, $kelasId);
        }

        $data = [
            'title' => 'Koreksi Kehadiran',
            'kelas' => $kelasModel->findAll(),
            'tampil_data' => true,
            'absensi' => $dataLaporan,
            'p_type' => $userType,
            'p_awal' => $tglAwal,
            'p_akhir' => $tglAkhir,
            'p_kelas' => $kelasId,
            'active_tab' => $userType
        ];

        return view('admin/koreksi/index', $data);
    }

    public function delete($id)
    {
        $absensiModel = new AbsensiModel();
        
        if ($id) {
            $absensiModel->delete($id);
            return redirect()->back()->with('success', 'Data absensi berhasil dihapus (Reset ke Alfa).');
        }
        
        return redirect()->back()->with('error', 'ID Absensi tidak valid.');
    }

    public function bulkAction()
    {
        $absensiModel = new AbsensiModel();
        $action = $this->request->getPost('bulk_action');
        $selectedItems = $this->request->getPost('selected_items');

        if (empty($selectedItems)) {
            return redirect()->back()->with('error', 'Tidak ada data yang dipilih.');
        }

        $status = $this->request->getPost('bulk_status');
        $jamMasukInput = $this->request->getPost('bulk_jam_masuk');
        $jamPulangInput = $this->request->getPost('bulk_jam_pulang');
        $keterangan = $this->request->getPost('bulk_keterangan');

        if (empty($keterangan)) $keterangan = 'Koreksi Massal';

        $countSuccess = 0;

        foreach ($selectedItems as $item) {
            list($userId, $tanggal, $userType) = explode('|', $item);

            $existing = $absensiModel->where('user_id', $userId)
                                     ->where('user_type', $userType)
                                     ->where('tanggal', $tanggal)
                                     ->first();

            if ($action == 'delete') {
                if ($existing) {
                    $absensiModel->delete($existing['id']);
                    $countSuccess++;
                }
            } elseif ($action == 'update') {
                
                $data = [
                    'status' => $status,
                    'keterangan' => $keterangan
                ];

                if ($status == 'Hadir' || $status == 'Terlambat') {
                    $data['jam_masuk'] = !empty($jamMasukInput) ? $jamMasukInput : '07:00:00';
                    
                    if (!empty($jamPulangInput)) {
                        $data['jam_pulang'] = $jamPulangInput;
                    } else {
                        $data['jam_pulang'] = null; 
                    }
                } else {
                    $data['jam_masuk'] = null;
                    $data['jam_pulang'] = null;
                }

                if ($existing) {
                    $absensiModel->update($existing['id'], $data);
                } else {
                    $data['user_id'] = $userId;
                    $data['user_type'] = $userType;
                    $data['tanggal'] = $tanggal;
                    $data['lokasi_lat'] = '-';
                    $data['lokasi_long'] = '-';
                    $absensiModel->insert($data);
                }
                $countSuccess++;
            }
        }

        $msg = ($action == 'delete') ? "$countSuccess Data berhasil dihapus (Reset ke Alfa)." : "$countSuccess Data berhasil diperbarui.";
        return redirect()->back()->with('success', $msg);
    }
}