<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Certification;
use App\Services\FileUploadService;
use Illuminate\Http\Request;

class CertificationController extends Controller
{
    public function index()
    {
        $certifications = Certification::orderBy('sort_order')->paginate(20);

        return view('admin.certifications.index', compact('certifications'));
    }

    public function create()
    {
        return view('admin.certifications.create');
    }

    public function store(Request $request)
    {
        $validated = $this->validateCertification($request);

        if ($request->hasFile('image')) {
            $validated['image'] = FileUploadService::store($request->file('image'), 'certifications');
        }
        if ($request->hasFile('file')) {
            $validated['file'] = FileUploadService::store($request->file('file'), 'certifications/files');
        }

        Certification::create($validated);

        return redirect()->route('admin.certifications.index')->with('success', 'Certification created.');
    }

    public function edit(Certification $certification)
    {
        return view('admin.certifications.edit', compact('certification'));
    }

    public function update(Request $request, Certification $certification)
    {
        $validated = $this->validateCertification($request);

        if ($request->hasFile('image')) {
            $validated['image'] = FileUploadService::store($request->file('image'), 'certifications');
        }
        if ($request->hasFile('file')) {
            $validated['file'] = FileUploadService::store($request->file('file'), 'certifications/files');
        }

        $certification->update($validated);

        return redirect()->route('admin.certifications.index')->with('success', 'Certification updated.');
    }

    public function destroy(Certification $certification)
    {
        $certification->delete();

        return back()->with('success', 'Certification deleted.');
    }

    protected function validateCertification(Request $request): array
    {
        return $request->validate([
            'name' => 'required|string|max:255',
            'issuing_organization' => 'nullable|string|max:255',
            'certificate_number' => 'nullable|string|max:255',
            'issue_date' => 'nullable|date',
            'expiry_date' => 'nullable|date',
            'image' => 'nullable|image|mimes:jpeg,jpg,png,webp|max:4096',
            'file' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:10240',
            'description' => 'nullable|string',
            'status' => 'nullable|boolean',
            'sort_order' => 'nullable|integer|min:0',
        ]);
    }
}
