<?php

namespace App\Http\Controllers\Employee;

use App\Enums\UserType;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreSalaryCertificateRequest;
use App\Models\SalaryCertificateRequest;
use App\Models\User;
use App\Services\NotificationService;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response as InertiaResponse;

class SalaryCertificateController extends Controller
{
    public function index(Request $request): InertiaResponse
    {
        $requests = SalaryCertificateRequest::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return Inertia::render('Employee/Profile/Partials/SalaryCertificate/CertificateRequestList', [
            'requests' => $requests,
        ]);
    }

    public function store(StoreSalaryCertificateRequest $request)
    {
        $certRequest = SalaryCertificateRequest::create([
            'user_id' => $request->user()->id,
            'reason' => $request->reason,
            'status' => SalaryCertificateRequest::STATUS_PENDING,
        ]);

        // Notify Manager and Super Admins
        $manager = $request->user()->employeeProfile?->manager;
        $superAdmins = User::where('type', UserType::SUPER_ADMIN)->get();

        $notifiables = collect();
        if ($manager) {
            $notifiables->push($manager);
        }
        $notifiables = $notifiables->merge($superAdmins)->unique('id');

        $notificationService = app(NotificationService::class);
        foreach ($notifiables as $notifiable) {
            $notificationService->info(
                $notifiable->id,
                'New Salary Certificate Request',
                "{$request->user()->name} has requested a salary certificate.",
                [
                    'request_id' => $certRequest->id,
                    'type' => 'salary_certificate_request',
                ],
                route('admin.payroll.certificate.index')
            );
        }

        return back()->with('success', 'Salary certificate request submitted successfully.');
    }

    public function download(SalaryCertificateRequest $salaryCertificateRequest)
    {
        if ($salaryCertificateRequest->user_id !== auth()->id()) {
            abort(403);
        }

        if ($salaryCertificateRequest->status !== SalaryCertificateRequest::STATUS_APPROVED) {
            return back()->with('error', 'Certificate is not approved yet.');
        }

        $employee = auth()->user()->load(['employeeProfile.departmentRel', 'salaryAssignment.payrollStructure']);

        $pdf = Pdf::loadView('pdf.salary_certificate', [
            'employee' => $employee,
            'companyName' => config('branding.theme.app_name', config('app.name')),
        ])->setPaper('a4');

        $filename = 'salary_certificate_'.$employee->name.'.pdf';

        return $pdf->download($filename);
    }
}
