<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Partner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PartnerController extends Controller
{
    public function index()
    {
        $partners = Partner::orderBy('sort_order')->paginate(20);
        return view('admin.partners.index', compact('partners'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'logo'        => 'required|image|max:2048',
            'website'     => 'nullable|url|max:255',
            'sort_order'  => 'nullable|integer',
            'is_featured' => 'nullable|boolean',
            'is_active'   => 'nullable|boolean',
        ]);
        $data['logo'] = $request->file('logo')->store('partners', 'public');
        Partner::create($data);
        cache()->forget('nav.partners');
        return redirect()->route('admin.partners.index')->with('success', 'Харилцагч нэмэгдлээ.');
    }

    public function edit(Partner $partner)
    {
        return view('admin.partners.edit', compact('partner'));
    }

    public function update(Request $request, Partner $partner)
    {
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'logo'        => 'nullable|image|max:2048',
            'website'     => 'nullable|url|max:255',
            'sort_order'  => 'nullable|integer',
            'is_featured' => 'nullable|boolean',
            'is_active'   => 'nullable|boolean',
        ]);
        if ($request->hasFile('logo')) {
            if ($partner->logo) Storage::disk('public')->delete($partner->logo);
            $data['logo'] = $request->file('logo')->store('partners', 'public');
        }
        $partner->update($data);
        cache()->forget('nav.partners');
        return redirect()->route('admin.partners.index')->with('success', 'Шинэчлэгдлээ.');
    }

    public function destroy(Partner $partner)
    {
        if ($partner->logo) Storage::disk('public')->delete($partner->logo);
        $partner->delete();
        cache()->forget('nav.partners');
        return back()->with('success', 'Устгагдлаа.');
    }
}
