<?php

namespace App\Http\Controllers;

use App\Models\Banner;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AdminBannerController extends Controller
{
    public function index()
    {
        return view('admin.banners.index', [
            'banners' => Banner::query()->orderBy('sort_order')->latest()->paginate(20),
        ]);
    }

    public function create()
    {
        return view('admin.banners.form', [
            'banner' => new Banner(['is_active' => true, 'sort_order' => 0, 'url' => '#', 'tone' => 'blue']),
        ]);
    }

    public function store(Request $request)
    {
        Banner::create($this->validatedData($request));

        return redirect()->route('admin.banners.index')->with('status', 'تم إنشاء البانر.');
    }

    public function edit(Banner $banner)
    {
        return view('admin.banners.form', ['banner' => $banner]);
    }

    public function update(Request $request, Banner $banner)
    {
        $banner->update($this->validatedData($request, $banner));

        return redirect()->route('admin.banners.index')->with('status', 'تم تحديث البانر.');
    }

    public function destroy(Banner $banner)
    {
        $banner->update(['is_active' => false]);

        return back()->with('status', 'تم تعطيل البانر.');
    }

    private function validatedData(Request $request, ?Banner $banner = null): array
    {
        $data = $request->validate([
            'title_ar' => ['required', 'string', 'max:160'],
            'title_en' => ['required', 'string', 'max:160'],
            'subtitle_ar' => ['nullable', 'string', 'max:255'],
            'subtitle_en' => ['nullable', 'string', 'max:255'],
            'cta_label_ar' => ['nullable', 'string', 'max:80'],
            'cta_label_en' => ['nullable', 'string', 'max:80'],
            'url' => ['required', 'string', 'max:255'],
            'tone' => ['required', 'string', 'max:40'],
            'sort_order' => ['required', 'integer', 'min:0'],
            'image_path' => ['nullable', 'string', 'max:255'],
            'image' => ['nullable', 'image', 'max:6144'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        unset($data['image']);

        if ($request->hasFile('image')) {
            $directory = public_path('images/banners');
            if (! is_dir($directory)) {
                mkdir($directory, 0755, true);
            }

            $file = $request->file('image');
            $filename = 'banner-'.Str::random(10).'.'.$file->getClientOriginalExtension();
            $file->move($directory, $filename);
            $data['image_path'] = 'images/banners/'.$filename;
        } elseif ($banner && ! filled($data['image_path'] ?? null)) {
            $data['image_path'] = $banner->image_path;
        }

        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
