<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\File;
use App\Brands;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class BrandsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $brands = Brands::all();
        return view('brands.index', compact('brands'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('brands.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate the request data
        $request->validate([
            'brand_name' => 'required|string|max:255',
            'brands_abbrevation' => 'nullable|string|max:255',
            'barnd_status' => 'required|in:1,0',
            'brand_logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048' // Assuming you want to limit the file size to 2MB
        ]);

        $brand_logo = null;
        if ($request->hasFile('brand_logo')) {
            $image = $request->file('brand_logo');
            $img_ext = $image->getClientOriginalExtension(); // Get the file extension
            $brand_logo = substr(md5(mt_rand()), 0, 10) . '.' . $img_ext; // Generate a unique filename

            // Store the image file
            $destinationPath = public_path('uploads/brand_images');
            $image->move($destinationPath, $brand_logo);
        }

        // Create a new brand record
        Brands::create([
            'brands_name' => $request->brand_name,
            'brands_abbrevation' => $request->brands_abbrevation,
            'brands_logo' => $brand_logo,
            'created_by' => auth()->user()->name,
            'brands_status' => $request->barnd_status,
        ]);

        // Redirect back with success message
        return redirect()->route('brands.list')->with('success', 'Brand created successfully!');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Brands  $brands
     * @return \Illuminate\Http\Response
     */
    public function show(Brands $brands)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Brands  $brands
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // Decrypt the ID
        $brand_id = Crypt::decrypt($id);

        // Find the brand or return 404 if not found
        $brand = Brands::find($brand_id);
        if (!$brand) {
            return abort(404);
        }

        return view('brands.edit', compact('brand'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Brands  $brands
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Decrypt the ID
        $brand_id = Crypt::decrypt($id);

        // Validate the request data
        $request->validate([
            'brand_name' => 'required|string|max:255',
            'brands_abbrevation' => 'nullable|string|max:255',
            'barnd_status' => 'required|in:1,0',
            'brand_logo' => 'nullable|file|image|max:2048',
        ]);

        // Find the brand or return 404 if not found
        $brand = Brands::find($brand_id);
        if (!$brand) {
            return abort(404);
        }

        // Handle file upload
        if ($request->hasFile('brand_logo')) {
            // Delete the old logo if it exists
            if ($brand->brands_logo) {
                $old_logo_path = public_path('uploads/brand_images/' . $brand->brands_logo);
                if (file_exists($old_logo_path)) {
                    unlink($old_logo_path);
                }
            }

            // Store the new logo
            $image = $request->file('brand_logo');
            $img_ext = $image->getClientOriginalExtension();
            $brand_logo = substr(md5(mt_rand()), 0, 10) . "." . $img_ext;
            $destinationPath = public_path('uploads/brand_images');
            $image->move($destinationPath, $brand_logo);

            // Update the logo field in the database
            $brand->brands_logo = $brand_logo;
        }

        // Update the brand record
        $brand->update([
            'brands_name' => $request->brand_name,
            'brands_abbrevation' => $request->brands_abbrevation,
            'created_by' => auth()->user()->name,
            'brands_status' => $request->barnd_status,
        ]);

        // Redirect back with success message
        return redirect()->route('brands.list')->with('success', 'Brand updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Brands  $brands
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // Decrypt the ID
        // $brand_id = Crypt::decrypt($id);

        // Find the brand or return 404 if not found
        $brand = Brands::find($id);
        if (!$brand) {
            return abort(404);
        }

        // Delete the brand's logo from storage if it exists
        if ($brand->brands_logo) {
            $image_path = public_path('uploads/brand_images/' . $brand->brands_logo);
            if (file_exists($image_path)) {
                unlink($image_path);
            }
        }

        // Delete the brand record
        $brand->delete();

        // Redirect back with success message
        return redirect()->route('brands.list')->with('success', 'Brand deleted successfully!');
    }
}
