<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Storage;
use App\Services\ImageOptimizer;

class StorefrontController extends Controller
{
    public function index()
    {
        // Fetch banners ordered by sort_order
        $banners = Banner::orderBy('sort_order')->get();

        return Inertia::render('cp/Settings/Storefront', [
            'banners' => $banners
        ]);
    }

    public function storeBanner(Request $request)
    {
        if (Banner::count() >= 10) {
            return back()->withErrors(['error' => 'Maximum of 10 banners allowed. Please delete or edit existing ones.']);
        }

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'image' => 'required|image|mimes:jpeg,png,jpg,webp|max:5120', // 5MB max
            'link' => 'nullable|url|max:500',
            'sort_order' => 'integer',
            'is_active' => 'boolean'
        ]);

        if ($request->hasFile('image')) {
            // <-- UPDATED: Using ImageOptimizer instead of store()
            $validated['image_path'] = ImageOptimizer::upload($request->file('image'), 'banners');
        }

        Banner::create($validated);

        return back()->with('success', 'Banner added successfully.');
    }

    public function updateBanner(Request $request, Banner $banner)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
            'link' => 'nullable|url|max:500',
            'sort_order' => 'integer',
            'is_active' => 'boolean'
        ]);

        if ($request->hasFile('image')) {
            if ($banner->image_path) {
                Storage::disk('public')->delete($banner->image_path);
            }
            // <-- UPDATED: Using ImageOptimizer instead of store()
            $validated['image_path'] = ImageOptimizer::upload($request->file('image'), 'banners');
        }

        $banner->update($validated);

        return back()->with('success', 'Banner updated successfully.');
    }

    public function destroyBanner(Banner $banner)
    {
        if ($banner->image_path) {
            Storage::disk('public')->delete($banner->image_path);
        }
        
        $banner->delete();

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