<?php

namespace App\Http\Controllers;

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

class PopularController extends Controller
{
    /**
     * Display a listing of the resource.
     */
   public function index(Request $request)
{
    $catagories = Catagory::all();
    $query = Popular::with('category');
    if ($request->filled('search')) {
        $search = $request->search;

        $query->where(function ($q) use ($search) {
            $q->where('title', 'like', "%{$search}%")
              ->orWhere('author', 'like', "%{$search}%");
        });
    }

    $populars = $query->orderBy('created_at', 'DESC')->paginate(20);

    return view('backend.pages.popular.index', compact('populars','catagories'));
}
    /**
     * Show the form for creating a new resource.
     */
   public function create()
{
     $catagories = Catagory::get();
    return view('backend.pages.popular.create', compact('catagories'));
}

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
         $request->validate([
            'image'       => 'required|image',
            'alt_text'    => 'nullable|string',

            'title'       => 'required|string',
            'author'       => 'required|string',
            //  'slug'       => 'required|string',


            'price'  => 'nullable|integer',
            'amazon_link'  => 'nullable|string',
            'category_id' => 'required|integer',
            'priority'    => 'nullable|integer',
            'status'      => 'required|in:1,2',
        ]);


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

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


        Popular::create([
            'image'      => $imagePath,
            'title'      => $request->title,
            'category_id'       => $request->category_id,
            'alt_text'   => $request->alt_text,
            'author'   => $request->author,
            // 'slug'   => $request->slug,

            'price' => $request->price,
            'amazon_link' => $request->amazon_link,
            'priority'   => $request->priority,
            'status'     => $request->status,
        ]);

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

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

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

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

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

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

        $imagePath = $popular->image;

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

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

        $popular->update([
            'image'       => $imagePath,
            'title'        => $request->title,
            'alt_text' => $request->alt_text,
            'price' => $request->price,
            'amazon_link' => $request->amazon_link,
            'author' => $request->author,
            'category_id' => $request->category_id,
            'slug'       => $slug,
            'priority'    => $request->priority,
            'status'      => $request->status,
        ]);

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

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

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

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

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

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