<?php

namespace App\Http\Controllers;

use App\Models\Bestseller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BestsellerController extends Controller
{
    public function index()
    {
        $bestsellers = Bestseller::all();
        return view('admin.bestseller.index', compact('bestsellers'));
    }

    public function getBestsellers()
    {
        $bestsellers = Bestseller::all();
        return $bestsellers;
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $image = $request->file('image');
        $imageName = time() . '.' . $image->extension();
        $image->storeAs('public/bestsellers', $imageName);

        Bestseller::create([
            'name' => $request->name,
            'description' => $request->description,
            'image' => $imageName
        ]);

        return redirect()->back()->with('success', 'Bestseller added successfully');
    }

    public function update(Request $request, Bestseller $bestseller)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $data = [
            'name' => $request->name,
            'description' => $request->description
        ];

        if ($request->hasFile('image')) {
            // Delete old image
            if ($bestseller->image) {
                Storage::delete('public/bestsellers/' . $bestseller->image);
            }

            // Store new image
            $image = $request->file('image');
            $imageName = time() . '.' . $image->extension();
            $image->storeAs('public/bestsellers', $imageName);
            $data['image'] = $imageName;
        }

        $bestseller->update($data);
        return redirect()->back()->with('success', 'Bestseller updated successfully');
    }

    public function destroy(Bestseller $bestseller)
    {
        if ($bestseller->image) {
            Storage::delete('public/bestsellers/' . $bestseller->image);
        }
        
        $bestseller->delete();
        return redirect()->back()->with('success', 'Bestseller deleted successfully');
    }
} 