<?php

namespace App\Http\Controllers;

use App\Models\BioTimeAttendanceLog;
use App\Models\BioTimeSyncLog;
use App\Models\DailyAttendance;
use App\Models\Employee;
use App\Services\BioTimeService;
use App\Services\AttendanceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

        if (!$user->is_admin) {
            $employee = $user->employee;
            if ($employee) {
                $query->where('employee_id', $employee->id);
            }
        }

        if ($request->has('date')) {
            $query->whereDate('date', $request->date);
        }

        $attendances = $query->latest('date')->paginate(10);
        return view('attendance.index', compact('attendances'));
    }

    public function logs(Request $request)
    {
        $user = Auth::user();
        $query = BioTimeAttendanceLog::with('employee');

        if (!$user->is_admin) {
            $employee = $user->employee;
            if ($employee) {
                $query->where('employee_id', $employee->id);
            }
        }

        $logs = $query->latest('punch_time')->paginate(20);
        return view('attendance.logs', compact('logs'));
    }

    public function syncLogs()
    {
        /*
        if (!Auth::user()->is_admin) {
            abort(403);
        }
        */

        $syncLogs = BioTimeSyncLog::latest()->paginate(20);
        return view('attendance.sync_logs', compact('syncLogs'));
    }

    public function sync(BioTimeService $bioTimeService, AttendanceService $attendanceService)
    {
        /*
        if (!Auth::user()->is_admin) {
            abort(403);
        }
        */

        $newLogsCount = $bioTimeService->fetchTransactions(null, null, 'admin');
        if ($newLogsCount === false) {
            return redirect()->back()->with('error', 'BioTime Sync Failed. Check logs.');
        }

        $dailyCount = $attendanceService->processLogsToDailyAttendance();

        return redirect()->back()->with('success', "Synced {$newLogsCount} new logs and updated {$dailyCount} daily attendance records.");
    }
}
