<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\AttendancePunch;
use App\Models\BiometricDevice;
use App\Services\Biometric\ZktecoPunchIngestService;
use Illuminate\Http\Request;

class AttendancePunchController extends Controller
{
    public function index(Request $request)
    {
        $query = AttendancePunch::query()
            ->with(['device', 'user'])
            ->orderByDesc('punch_datetime')
            ->orderByDesc('id');

        if ($request->filled('status')) {
            $query->where('status', $request->string('status'));
        }
        if ($request->filled('device_id')) {
            $query->where('biometric_device_id', (int) $request->integer('device_id'));
        }
        if ($request->filled('emp_code')) {
            $query->where('emp_code', 'like', '%'.$request->string('emp_code').'%');
        }
        if ($request->filled('from')) {
            $query->whereDate('punch_datetime', '>=', $request->date('from'));
        }
        if ($request->filled('to')) {
            $query->whereDate('punch_datetime', '<=', $request->date('to'));
        }

        $punches = $query->paginate(50)->withQueryString();
        $devices = BiometricDevice::query()->orderBy('terminal_alias')->orderBy('terminal_sn')->get();

        return view('attendance-punches.index', compact('punches', 'devices'));
    }

    public function retry(AttendancePunch $attendancePunch, ZktecoPunchIngestService $ingestService)
    {
        $this->assertCompany($attendancePunch);

        if (! $attendancePunch->isRetryable() && $attendancePunch->status !== AttendancePunch::STATUS_IGNORED
            && $attendancePunch->status !== AttendancePunch::STATUS_APPLIED) {
            return redirect()->back()->with('error', 'Only pending/error/ignored/applied punches can be retried.');
        }

        $attendancePunch->update([
            'status' => AttendancePunch::STATUS_PENDING,
            'error_message' => null,
            'processed_at' => null,
            'processed_type' => null,
            'is_duplicate' => false,
        ]);

        $ingestService->applyPunch($attendancePunch->id);

        return redirect()->back()->with('success', 'Punch reprocessed.');
    }

    protected function assertCompany(AttendancePunch $punch): void
    {
        if ((int) $punch->company_id !== (int) auth()->user()->company_id) {
            abort(404);
        }
    }
}
