<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Services\ImageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class BannerController extends Controller
{
    public function __construct(
        protected ImageService $imageService
    ) {
    }

    public function index(): View
    {
        $banners = Banner::orderBy('sort_order')
            ->latest()
            ->paginate(20);

        return view('admin.banners.index', compact('banners'));
    }

    public function create(): View
    {
        return view('admin.banners.create');
    }

    public function store(Request $request): RedirectResponse
    {
        // Check banner limit (max 3)
        $activeBannerCount = Banner::count();
        if ($activeBannerCount >= 3) {
            return redirect()->route('admin.banners.index')
                ->with('error', 'Maximum limit of 3 banners reached. Please delete or deactivate an existing banner first.');
        }

        $request->validate([
            'title' => 'nullable|string|max:255',
            'image' => [
                'required',
                'image',
                'mimes:jpeg,png,jpg,gif,webp',
                'max:2048', // 2MB max
            ],
            'link' => 'nullable|url|max:255',
            'sort_order' => 'nullable|integer|min:1|max:3',
            'is_active' => 'nullable|boolean',
        ], [
            'image.required' => 'Please select a banner image.',
            'image.image' => 'The file must be an image.',
            'image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
            'image.max' => 'The image size must not exceed 2MB. Please choose a smaller image.',
        ]);

        $data = $request->only(['title', 'link', 'sort_order', 'is_active']);
        
        // Set default sort_order if not provided
        if (empty($data['sort_order'])) {
            $data['sort_order'] = Banner::max('sort_order') + 1;
            // Ensure it doesn't exceed 3
            if ($data['sort_order'] > 3) {
                $data['sort_order'] = 3;
            }
        }
        
        if ($request->hasFile('image')) {
            // Process and compress image automatically
            $data['image_path'] = $this->imageService->processBannerImage(
                $request->file('image'),
                1920, // max width
                600,  // max height
                85    // quality (85% for good balance)
            );
        }

        Banner::create($data);

        // Check if request came from settings page
        if (request()->has('from_settings')) {
            return redirect()->route('admin.settings.index', ['tab' => 'banners'])
                ->with('success', 'Banner created successfully!');
        }

        return redirect()->route('admin.banners.index')->with('success', 'Banner created successfully!');
    }

    public function edit(Banner $banner): View
    {
        return view('admin.banners.edit', compact('banner'));
    }

    public function update(Request $request, Banner $banner): RedirectResponse
    {
        $request->validate([
            'title' => 'nullable|string|max:255',
            'image' => [
                'nullable',
                'image',
                'mimes:jpeg,png,jpg,gif,webp',
                'max:2048', // 2MB max
            ],
            'link' => 'nullable|url|max:255',
            'sort_order' => 'nullable|integer|min:1|max:3',
            'is_active' => 'nullable|boolean',
        ], [
            'image.image' => 'The file must be an image.',
            'image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
            'image.max' => 'The image size must not exceed 2MB. Please choose a smaller image.',
        ]);

        $data = $request->only(['title', 'link', 'sort_order', 'is_active']);

        if ($request->hasFile('image')) {
            // Delete old image
            if ($banner->image_path) {
                Storage::disk('public')->delete($banner->image_path);
            }

            // Process and compress image automatically
            $data['image_path'] = $this->imageService->processBannerImage(
                $request->file('image'),
                1920, // max width
                600,  // max height
                85    // quality (85% for good balance)
            );
        }

        $banner->update($data);

        // Check if request came from settings page
        if (request()->has('from_settings')) {
            return redirect()->route('admin.settings.index', ['tab' => 'banners'])
                ->with('success', 'Banner updated successfully!');
        }

        return redirect()->route('admin.banners.index')->with('success', 'Banner updated successfully!');
    }

    public function destroy(Banner $banner): RedirectResponse
    {
        // Delete image if exists
        if ($banner->image_path) {
            Storage::disk('public')->delete($banner->image_path);
        }

        $banner->delete();

        return redirect()->route('admin.banners.index')->with('success', 'Banner deleted successfully!');
    }
}
