<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AbsensiModel;
use App\Models\GuruModel;
use App\Models\SiswaModel;
use App\Models\SettingJamModel;

class Absensi extends BaseController
{
    public function edit($id)
    {
        $absensiModel = new AbsensiModel();
        $guruModel = new GuruModel();
        $siswaModel = new SiswaModel();

        $absensi = $absensiModel->find($id);

        if (!$absensi) {
            return redirect()->back()->with('error', 'Data absensi tidak ditemukan.');
        }

        $namaUser = 'User Tidak Dikenal';
        
        if ($absensi['user_type'] == 'guru') {
            $guru = $guruModel->find($absensi['user_id']);
            if ($guru) {
                $namaUser = $guru['nama_guru'];
            }
        } else {
            $siswa = $siswaModel->find($absensi['user_id']);
            if ($siswa) {
                $namaUser = $siswa['nama_lengkap'];
            }
        }

        $data = [
            'title' => 'Edit Absensi Manual',
            'absensi' => $absensi,
            'nama_user' => $namaUser,
            'validation' => \Config\Services::validation()
        ];

        return view('absensi/manual_edit', $data);
    }

    public function updateManual()
    {
        $absensiModel = new AbsensiModel();
        $settingJamModel = new SettingJamModel();
        
        $id = $this->request->getPost('id');

        if (!$this->validate([
            'jam_masuk' => 'required',
            'status'    => 'required'
        ])) {
            return redirect()->back()->withInput()->with('error', 'Jam masuk dan status harus diisi.');
        }

        $dataLama = $absensiModel->find($id);
        if (!$dataLama) {
            return redirect()->back()->with('error', 'Data tidak ditemukan.');
        }

        $jamSetting = $settingJamModel->where('type', $dataLama['user_type'])->first();

        $jamMasukInput = $this->request->getPost('jam_masuk');
        $jamPulangInput = $this->request->getPost('jam_pulang');
        $statusInput = $this->request->getPost('status');
        $keteranganInput = $this->request->getPost('keterangan');

        if (in_array($statusInput, ['Hadir', 'Terlambat']) && $jamSetting) {
            $statusInput = 'Hadir'; 
            
            if ($jamMasukInput > $jamSetting['jam_masuk_akhir']) {
                $statusInput = 'Terlambat';
                if (strpos($keteranganInput, 'Terlambat') === false) {
                    $keteranganInput .= " [Terlambat Manual]";
                }
            }
        }

        if (!empty($jamPulangInput) && $jamSetting) {
            if ($jamPulangInput < $jamSetting['jam_pulang_mulai']) {
                if (strpos($keteranganInput, 'Cepat Pulang') === false) {
                    $keteranganInput = trim($keteranganInput . " (Cepat Pulang)");
                }
            }
        }

        if (empty($jamPulangInput)) {
            $jamPulangInput = null;
        }

        $data = [
            'jam_masuk'  => $jamMasukInput,
            'jam_pulang' => $jamPulangInput,
            'status'     => $statusInput,
            'keterangan' => trim($keteranganInput),
        ];

        $absensiModel->update($id, $data);

        return redirect()->to('/admin/koreksi')->with('success', 'Data absensi berhasil direvisi.');
    }

    public function input()
    {
        $guruModel = new GuruModel();
        $siswaModel = new SiswaModel();

        $userId = $this->request->getGet('user_id');
        $userType = $this->request->getGet('user_type');
        $tanggal = $this->request->getGet('tanggal');

        $namaUser = '-';
        if ($userType == 'guru') {
            $u = $guruModel->find($userId);
            $namaUser = $u ? $u['nama_guru'] : '-';
        } else {
            $u = $siswaModel->find($userId);
            $namaUser = $u ? $u['nama_lengkap'] : '-';
        }

        $absensi = [
            'id' => null,
            'user_id' => $userId,
            'user_type' => $userType,
            'tanggal' => $tanggal,
            'jam_masuk' => '',
            'jam_pulang' => '',
            'status' => 'Alfa',
            'keterangan' => 'Koreksi dari Alfa'
        ];

        $data = [
            'title' => 'Input Kehadiran Manual',
            'absensi' => $absensi,
            'nama_user' => $namaUser,
            'validation' => \Config\Services::validation()
        ];

        return view('absensi/manual_edit', $data);
    }

    public function saveManual()
    {
        $absensiModel = new AbsensiModel();
        $settingJamModel = new SettingJamModel();
        
        $userId = $this->request->getPost('user_id');
        $userType = $this->request->getPost('user_type');
        $tanggal = $this->request->getPost('tanggal');
        
        $jamMasukInput = $this->request->getPost('jam_masuk');
        $jamPulangInput = $this->request->getPost('jam_pulang');
        $statusInput = $this->request->getPost('status');
        $keteranganInput = $this->request->getPost('keterangan');

        $jamSetting = $settingJamModel->where('type', $userType)->first();

        if (in_array($statusInput, ['Hadir', 'Terlambat']) && $jamSetting) {
            $statusInput = 'Hadir'; 
            
            if ($jamMasukInput > $jamSetting['jam_masuk_akhir']) {
                $statusInput = 'Terlambat';
                if (strpos($keteranganInput, 'Terlambat') === false) {
                    $keteranganInput .= " [Terlambat Manual]";
                }
            }
        }

        if (!empty($jamPulangInput) && $jamSetting) {
            if ($jamPulangInput < $jamSetting['jam_pulang_mulai']) {
                if (strpos($keteranganInput, 'Cepat Pulang') === false) {
                    $keteranganInput = trim($keteranganInput . " (Cepat Pulang)");
                }
            }
        }

        if(empty($jamPulangInput)) $jamPulangInput = null;

        $absensiModel->insert([
            'user_id' => $userId,
            'user_type' => $userType,
            'tanggal' => $tanggal,
            'jam_masuk' => $jamMasukInput,
            'jam_pulang' => $jamPulangInput,
            'status' => $statusInput,
            'keterangan' => trim($keteranganInput),
            'lokasi_lat' => null,
            'lokasi_long' => null
        ]);

        return redirect()->to('/admin/koreksi')->with('success', 'Data kehadiran berhasil ditambahkan.');
    }
}