<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Services\StorageService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BannerController extends Controller
{
    public function index()
    {
        $banners = Banner::ordered()->paginate(10);
        return view('admin.banners.index', compact('banners'));
    }

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

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'subtitle' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:1000',
            'button_text' => 'nullable|string|max:100',
            'button_link' => 'nullable|string|max:500',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'background_color' => 'required|string|max:20',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        try {
            $data = $request->only(['title', 'subtitle', 'description', 'button_text', 'button_link', 'background_color', 'order']);
            $data['is_active'] = $request->has('is_active');

            // Handle image upload
            if ($request->hasFile('image')) {
                $data['image'] = StorageService::upload(
                    $request->file('image'),
                    'banners'
                );
            }

            Banner::create($data);

            return redirect()->route('admin.banners.index')
                ->with('success', 'Banner created successfully!');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Failed to create banner: ' . $e->getMessage())
                ->withInput();
        }
    }

    public function edit(Banner $banner)
    {
        return view('admin.banners.edit', compact('banner'));
    }

    public function update(Request $request, Banner $banner)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'subtitle' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:1000',
            'button_text' => 'nullable|string|max:100',
            'button_link' => 'nullable|string|max:500',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'background_color' => 'required|string|max:20',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        try {
            $data = $request->only(['title', 'subtitle', 'description', 'button_text', 'button_link', 'background_color', 'order']);
            $data['is_active'] = $request->has('is_active');

            // Handle image upload
            if ($request->hasFile('image')) {
                // Delete old image if exists
                if ($banner->image) {
                    StorageService::delete($banner->image);
                }
                
                $data['image'] = StorageService::upload(
                    $request->file('image'),
                    'banners'
                );
            }

            $banner->update($data);

            return redirect()->route('admin.banners.index')
                ->with('success', 'Banner updated successfully!');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Failed to update banner: ' . $e->getMessage())
                ->withInput();
        }
    }

    public function destroy(Banner $banner)
    {
        try {
            // Delete image if exists
            if ($banner->image) {
                StorageService::delete($banner->image);
            }

            $banner->delete();

            return redirect()->route('admin.banners.index')
                ->with('success', 'Banner deleted successfully!');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Failed to delete banner: ' . $e->getMessage());
        }
    }

    public function toggleStatus(Banner $banner)
    {
        try {
            $banner->is_active = !$banner->is_active;
            $banner->save();

            return redirect()->back()
                ->with('success', 'Banner status updated successfully!');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Failed to update banner status: ' . $e->getMessage());
        }
    }
}
