<?php

namespace App\Http\Controllers;

use App\Models\Catagory;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;

class CatagoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Catagory::query();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%");

            });
        }

        $catagories = $query->orderBy('created_at', 'DESC')->paginate(10);
        return view('backend.pages.catagory.index', compact('catagories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('backend.pages.catagory.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'image'       => 'required|image',
            'title'       => 'required|string',
            'alt_text'    => 'nullable|string',
            'amazon_link' => 'nullable|url',
            'priority'    => 'nullable|integer',
            'status'      => 'required|in:1,2',
        ]);


        // ✅ Image Upload
        $imagePath = null;
        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time().'_'.$file->getClientOriginalName();
            $file->move(public_path('storage/catagory_images'), $filename);
            $imagePath = 'storage/catagory_images/'.$filename;
        }


        Catagory::create([
            'image'      => $imagePath,
            'title'      => $request->title,
            'alt_text'   => $request->alt_text,
            'amazon_link' => $request->amazon_link,
            'priority'   => $request->priority,
            'status'     => $request->status,
        ]);

        Alert::success('Success', 'Catagory created successfully');
        return redirect()->route('catagory.index');
    }

    /**
     * Display the specified resource.
     */
    public function show( $id)
    {
        $catagory = Catagory::findOrFail($id);
        return view('backend.pages.catagory.show', compact('catagory'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $catagory = Catagory::findOrFail($id);
        return view('backend.pages.catagory.edit', compact('catagory'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request,  $id)
    {
        $catagory = Catagory::findOrFail($id);

        $request->validate([
            'image'       => 'nullable|image',
            'title'        => 'nullable|string',
            'alt_text' => 'nullable|string',
           'amazon_link' => 'nullable|url',
            'priority'    => 'nullable|integer',
            'status'      => 'nullable|in:1,2',
        ]);

        //  $slug = $request->slug
        //     ? Str::slug($request->slug)
        //     : ($request->title ? Str::slug($request->title) : $catagory->slug);

        $imagePath = $catagory->image;

        if ($request->hasFile('image')) {
            // Delete old image safely
            if ($catagory->image && file_exists(public_path($catagory->image))) {
                @unlink(public_path($catagory->image));
            }

            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('storage/catagory_images'), $filename);
            $imagePath = 'storage/catagory_images/' . $filename;
        }

        $catagory->update([
            'image'       => $imagePath,
            'title'        => $request->title,
            'alt_text' => $request->alt_text,
            'amazon_link' => $request->amazon_link,
            // 'slug'       => $slug,
            'priority'    => $request->priority,
            'status'      => $request->status,
        ]);

            Alert::success('Success ', 'catagory updated successfully.');
            return redirect()->route('catagory.index');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $catagory = Catagory::find($id);

        if (!$catagory) {
            return redirect()->route('catagory.index')->with('error', 'Catagory data not found!');
        }

        // Delete image
        if ($catagory->image && file_exists(public_path($catagory->image))) {
            @unlink(public_path($catagory->image));
        }

        // Delete record
        $catagory->delete();
         Alert::success('Success ', 'catagory deleted successfully.');

        return redirect()->route('catagory.index');
    }
}
