<?php

namespace App\Http\Controllers;

use DateTime;
use App\Models\Employee;
use App\Models\Latetime;
use App\Models\Attendance;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\AttendanceEmp;
use App\Models\Presensi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class AttendanceController extends Controller
{   
    //show attendance 
    public function index(Request $request)
    {  
        $query = Presensi::with('user')
            ->select('presensi.*')
            ->join('users', 'presensi.user_id', '=', 'users.id')
            ->orderBy('presensi.created_at', 'desc');

        // Always filter by today's date if no date is specified
        if (!$request->has('date')) {
            $query->whereDate('presensi.created_at', Carbon::today());
        } else {
            $date = Carbon::parse($request->date);
            $query->whereDate('presensi.created_at', $date);
        }

        $presensis = $query->get();

        return view('admin.attendance', compact('presensis'));
    }

    //show late times
    public function indexLatetime()
    {
        return view('admin.latetime')->with(['latetimes' => Latetime::all()]);
    }

    

    // public static function lateTime(Employee $employee)
    // {
    //     $current_t = new DateTime(date('H:i:s'));
    //     $start_t = new DateTime($employee->schedules->first()->time_in);
    //     $difference = $start_t->diff($current_t)->format('%H:%I:%S');

    //     $latetime = new Latetime();
    //     $latetime->emp_id = $employee->id;
    //     $latetime->duration = $difference;
    //     $latetime->latetime_date = date('Y-m-d');
    //     $latetime->save();
    // }

    public static function lateTimeDevice($att_dateTime, Employee $employee)
    {
        $attendance_time = new DateTime($att_dateTime);
        $checkin = new DateTime($employee->schedules->first()->time_in);
        $difference = $checkin->diff($attendance_time)->format('%H:%I:%S');

        $latetime = new Latetime();
        $latetime->emp_id = $employee->id;
        $latetime->duration = $difference;
        $latetime->latetime_date = date('Y-m-d', strtotime($att_dateTime));
        $latetime->save();
    }
  
    public function destroy($id)
    {
        try {
            $presensi = Presensi::findOrFail($id);
            
            // Hapus file foto jika ada
            if ($presensi->foto) {
                Storage::delete('public/' . $presensi->foto);
            }
            
            // Hapus record dari database
            $presensi->delete();

            return redirect()->route('admin.attendance')
                ->with('success', 'Data presensi berhasil dihapus');
        } catch (\Exception $e) {
            return redirect()->route('admin.attendance')
                ->with('error', 'Gagal menghapus data presensi: ' . $e->getMessage());
        }
    }
}
