<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;
use App\Models\Absence;
use App\Models\PTSession;
use App\Models\PTVisit;

class AbsenceController extends Controller
{
    public function index()
    {
        return view('absensi.index');
    }

    public function scan(Request $request)
    {
        $kode = $request->input('kode'); // kode dari QR

        $member = Member::where('id', $kode)->first();
        if (!$member) {
            return response()->json(['status' => 'error', 'message' => 'Member tidak ditemukan!']);
        }
        if (!$member->is_active || \Carbon\Carbon::parse($member->expired_at)->isPast()) {
            return response()->json(['status' => 'error', 'message' => 'Member tidak aktif!']);
        }

        $sudah_absen = Absence::where('member_id', $member->id)
            ->whereDate('waktu_scan', now()->toDateString())->exists();

        if ($sudah_absen) {
            return response()->json(['status' => 'info', 'message' => 'Member sudah absen hari ini.']);
        }

        Absence::create([
            'member_id' => $member->id,
            'waktu_scan' => now(),
        ]);

        // --- INTEGRASI KE PT VISIT ---
        $todaySessions = \App\Models\PTSession::where('member_id', $member->id)
            ->whereDate('waktu', now()->toDateString())
            ->get();

        foreach ($todaySessions as $session) {
            $sudahVisit = \App\Models\PTVisit::where('pt_session_id', $session->id)
                ->whereDate('waktu_hadir', now()->toDateString())
                ->exists();

            if (!$sudahVisit) {
                \App\Models\PTVisit::create([
                    'pt_session_id' => $session->id,
                    'waktu_hadir' => now(),
                ]);
            }
        }
        // --- END ---

        return response()->json(['status' => 'success', 'message' => 'Absensi berhasil untuk ' . $member->nama]);
    }
    
    public function rekap(Request $request)
    {
        $query = Absence::with('member')->orderBy('waktu_scan', 'desc');

        // Filter tanggal
        $filter = $request->filter ?? 'harian';
        if ($filter == 'harian') {
            $query->whereDate('waktu_scan', now()->toDateString());
            } elseif ($filter == 'mingguan') {
                $startOfWeek = now()->startOfWeek();
                $endOfWeek = now()->endOfWeek();
                $query->whereBetween('waktu_scan', [$startOfWeek, $endOfWeek]);
            } elseif ($filter == 'bulanan') {
                $query->whereMonth('waktu_scan', now()->month)
                    ->whereYear('waktu_scan', now()->year);
            } elseif ($filter == 'tahunan') {
                $query->whereYear('waktu_scan', now()->year);
            }

        // Search (nama member / id member)
        if ($request->search) {
            $search = $request->search;
            $query->whereHas('member', function($q) use ($search) {
                $q->where('nama', 'LIKE', "%$search%");
                })->orWhere('member_id', 'LIKE', "%$search%");
        }

        $absensi = $query->paginate(10)->appends($request->all());

        return view('absensi.rekap', compact('absensi'));
    }
}