<?php

namespace App\Http\Controllers;

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

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

    $query = BookOffers::with('category');

    if ($request->filled('search')) {
        $search = $request->search;

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

    $bookOffers = $query->orderBy('created_at', 'DESC')->paginate(10);

    return view('backend.pages.bookOffers.index', compact('bookOffers','catagories'));
}

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $catagories = Catagory::get();
        return view('backend.pages.bookOffers.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',



            '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/bookOffers_images'), $filename);
            $imagePath = 'storage/bookOffers_images/'.$filename;
        }


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


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

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

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

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

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

        $request->validate([
            'image'       => 'nullable|image',
            'title'        => 'nullable|string',
            'alt_text' => '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) : $bookOffer->slug);

        $imagePath = $bookOffer->image;

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

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

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

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

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

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

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

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

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