<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{Attendance, User, AutomationLog, Holiday};
use Carbon\Carbon;
use RealRashid\SweetAlert\Facades\Alert;

class AttendanceController extends Controller
{
    public function index(Request $request)
    {
        $query = Attendance::with('user');

        $this->applyFilters($query, $request);

        return view('admin.rekap.index', [
            'attendance' => $query->orderBy('date', 'desc')->orderBy('check_in_time', 'asc')->paginate(5)
        ]);
    }

    private function applyFilters($query, Request $request)
    {
        if ($request->start_date) {
            $query->whereDate('date', '>=', $request->start_date);
        }
        
        if ($request->end_date) {
            $query->whereDate('date', '<=', $request->end_date);
        }
        
        if ($request->status) {
            $query->where('status', $request->status);
        }
        
        if ($request->search) {
    $query->whereHas('user', function ($q) use ($request) {
        $q->where('username', 'like', '%' . $request->search . '%')
          ->orWhereHas('siswa', function ($qs) use ($request) {
              $qs->where('nama_siswa', 'like', '%' . $request->search . '%');
          });
    });
}

    }

    public function edit($id)
    {
        $attendance = Attendance::with('user')->findOrFail($id);
        
        return response()->json([
            'id' => $attendance->id,
            'user_name' => $attendance->user->name,
            'date' => $attendance->date->format('Y-m-d'),
            'status' => $attendance->status,
            'check_in_time' => $attendance->check_in_time ? $attendance->check_in_time->format('H:i') : '',
            'check_out_time' => $attendance->check_out_time ? $attendance->check_out_time->format('H:i') : '',
            'notes' => $attendance->notes
        ]);
    }

    public function update(Request $request, $id)
    {
        $attendance = Attendance::findOrFail($id);
        
        $validated = $request->validate([
            'status' => 'required|in:hadir,izin,alfa',
            'check_in_time' => 'nullable|date_format:H:i',
            'check_out_time' => 'nullable|date_format:H:i',
            'notes' => 'nullable|string|max:500'
        ]);

        $updateData = $this->prepareUpdateData($validated, $attendance);
        
        $attendance->update($updateData);
        Alert::success('Berhasil!', 'Data presensi berhasil di update');
        return back();
    }

    private function prepareUpdateData($validated, $attendance)
    {
        $updateData = [
            'status' => $validated['status'], 
            'notes' => $validated['notes']
        ];

        if ($validated['status'] === 'hadir') {
            if ($validated['check_in_time']) {
                $checkInDateTime = Carbon::createFromFormat(
                    'Y-m-d H:i', 
                    $attendance->date->format('Y-m-d') . ' ' . $validated['check_in_time'], 
                    'Asia/Jakarta'
                );
                $updateData['check_in_time'] = $checkInDateTime->toDateTimeString();
            }
            
            if ($validated['check_out_time']) {
                $checkOutDateTime = Carbon::createFromFormat(
                    'Y-m-d H:i', 
                    $attendance->date->format('Y-m-d') . ' ' . $validated['check_out_time'], 
                    'Asia/Jakarta'
                );
                $updateData['check_out_time'] = $checkOutDateTime->toDateTimeString();
            }
        } else {
            $updateData['check_in_time'] = null;
            $updateData['check_out_time'] = null;
        }

        return $updateData;
    }

    public function destroy($id)
    {
        $attendance = Attendance::findOrFail($id);
        $userName = $attendance->user->name;
        $date = $attendance->date->format('d/m/Y');
        
        $attendance->delete();
        
        Alert::success('Berhasil!', "Data presensi {$userName} tanggal {$date} berhasil dihapus");
        return back();
    }
}