<?php

namespace App\Controllers;

use App\Models\AbsensiModel;
use CodeIgniter\RESTful\ResourceController;

class Absensi extends ResourceController
{
    protected $modelName = AbsensiModel::class;
    protected $format    = 'json';

    // GET /absensi?nisn=123&start_date=2025-08-01&end_date=2025-08-07
   public function index()
{
    $nisn       = $this->request->getGet('nisn');
    $startDate  = $this->request->getGet('start_date');
    $endDate    = $this->request->getGet('end_date');

    // Mulai builder dengan join ke tabel siswa
    $builder = $this->model
        ->select('absensi.*, siswa.nama as nama_siswa, siswa.rombel')
        ->join('siswa', 'siswa.nisn = absensi.nisn', 'left');

    if ($nisn) {
        $builder = $builder->where('absensi.nisn', $nisn);
    }

    if ($startDate && $endDate) {
        $builder = $builder->where('absensi.tanggal >=', $startDate)
                           ->where('absensi.tanggal <=', $endDate);
    } else {
        // Default: 7 hari terakhir
        $builder = $builder->where('absensi.tanggal >=', date('Y-m-d', strtotime('-7 days')));
    }

    $data = $builder->orderBy('absensi.tanggal', 'DESC')
                    ->orderBy('absensi.waktu', 'DESC')
                    ->paginate(10);

    return $this->respond([
        'status' => true,
        'data'   => $data,
        'pager'  => $this->model->pager->getDetails()
    ]);
}


    // POST /absensi
    public function create()
{
    // Ambil data baik dari JSON maupun form-data
    $data = $this->request->getJSON(true);
    if (!$data) {
        $data = $this->request->getPost();
    }

    log_message('debug', 'Data diterima: ' . json_encode($data));

    if (empty($data)) {
        return $this->fail('Tidak ada data untuk disimpan', 400);
    }

    $nisn   = $data['nisn'] ?? null;
    $status = strtolower($data['status'] ?? '');
    $tanggalHariIni = $data['tanggal'] ?? date('Y-m-d');

    if (!$nisn || !$status) {
        return $this->fail('NISN dan status wajib diisi', 400);
    }

    // Pastikan field tanggal ada
    if (!isset($data['tanggal'])) {
        $data['tanggal'] = $tanggalHariIni;
    }

    // Cegah absen ganda
    $cekStatusSama = $this->model
        ->where('nisn', $nisn)
        ->where('status', $status)
        ->where('tanggal', $tanggalHariIni)
        ->first();

    if ($cekStatusSama) {
        return $this->fail("Anda sudah melakukan absen {$status} hari ini", 400);
    }

    // Cegah pulang sebelum hadir
    if ($status === 'pulang') {
        $cekHadir = $this->model
            ->where('nisn', $nisn)
            ->where('status', 'hadir')
            ->where('tanggal', $tanggalHariIni)
            ->first();

        if (!$cekHadir) {
            return $this->fail('Anda belum absen hadir, tidak bisa absen pulang.', 400);
        }
    }

    if ($this->model->insert($data)) {
        return $this->respondCreated([
            'status'  => true,
            'message' => 'Absensi berhasil disimpan',
            'data'    => $data
        ]);
    }

    return $this->failValidationErrors($this->model->errors());
}


    // GET /absensi/{id}
    public function show($id = null)
    {
        $data = $this->model->find($id);

        if (!$data) {
            return $this->failNotFound('Data tidak ditemukan');
        }

        return $this->respond(['status' => true, 'data' => $data]);
    }
}