<?php

namespace App\Http\Controllers\AdminControllers;

use Illuminate\Http\Request;
use App\Models\AdminModels\Brand;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;

class BrandController
{

    public function brandAdd(){
        return view('admin.brand-add');
    }

    public function brandSave(Request $request){

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'logo' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
            'status' => 'required|string|max:50',
        ]);

        $brand = new Brand();
        $brand->name = $request->name;
        $brand->description = $request->description;
        $brand->status = $request->status;
        $brand->slug = Str::slug($request->name);


        // Handle image upload
        if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $logoName = time() . '_' . $logo->getClientOriginalName();
            $logo->move(public_path('uploads/brands'), $logoName);
            $brand->logo = $logoName;
        }

        $brand->save();

        return redirect()->route('brand.list')->with('success', 'category inserted successfully!');
    }

    public function brandList(){

        $brand = Brand::select('*')->get();
        return view('admin.brand-list', ['brand'=>$brand]);

    }

    public function brandEdit($id){
        $brand = Brand::where('id', $id)->first();
        return view('admin.brand-edit', ['brand'=>$brand]);
    }

    public function brandUpdate(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'status' => 'required|string|max:50',
        ]);

        $brand = Brand::findOrFail($id);
        $brand->name = $request->name;
        $brand->description = $request->description;
        $brand->status = $request->status;
        $brand->slug = Str::slug($request->name);

        if ($request->hasFile('logo')) {
            // Delete old image if it exists
            $oldImage = public_path('uploads/brands/' . $brand->logo);
            if (File::exists($oldImage)) {
                File::delete($oldImage);
            }

            // Upload new image
            $file = $request->file('logo');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/brands'), $filename);
            $brand->logo = $filename;
        }

        $brand->save();

        return redirect()->route('brand.list')->with('success', 'Brand updated successfully!');
    }


    public function brandDelete($id){
        $brand = Brand::where('id', $id)->first();
        $brand->delete();
        return redirect()->route('brand.list')->with('success', 'Brand successfully deleted');
    }
    
}
