<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LeadMagnet;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class LeadMagnetController extends Controller
{
    public function index(): View
    {
        LeadMagnet::seedDefault();

        return view('admin.lead-magnets.index', [
            'leadMagnets' => LeadMagnet::latest()->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validated($request);
        if ($request->hasFile('download_file')) {
            $data['file_path'] = $request->file('download_file')->store('lead-magnets', 'public');
        }

        LeadMagnet::create($data);

        return back()->with('success', 'Lead magnet created.');
    }

    public function update(Request $request, LeadMagnet $leadMagnet): RedirectResponse
    {
        $data = $this->validated($request);
        if ($request->hasFile('download_file')) {
            if ($leadMagnet->file_path) {
                Storage::disk('public')->delete($leadMagnet->file_path);
            }
            $data['file_path'] = $request->file('download_file')->store('lead-magnets', 'public');
        }

        $leadMagnet->update($data);

        return back()->with('success', 'Lead magnet updated.');
    }

    public function destroy(LeadMagnet $leadMagnet): RedirectResponse
    {
        if ($leadMagnet->file_path) {
            Storage::disk('public')->delete($leadMagnet->file_path);
        }
        $leadMagnet->delete();

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

    private function validated(Request $request): array
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:5000'],
            'download_file' => ['nullable', 'file', 'mimes:pdf', 'max:5120'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        unset($data['download_file']);
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
