<?php

namespace App\Http\Controllers;

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

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

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

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

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

    $latestArticles = $query->orderBy('created_at', 'desc')->paginate(10);

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

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


        LatestArticles::create([
            'image'      => $imagePath,
            'alt_text'   => $request->alt_text,

            'title'      => $request->title,
            'category_id'       => $request->category_id,
            'amazon_link'       => $request->amazon_link,

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

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

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

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

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

        $request->validate([
            'image'       => 'nullable|image',
            'title'        => 'nullable|string',
            'alt_text' => 'nullable|string',
            'date' => 'nullable|string',
            'amazon_link'  => 'nullable|string',

            'category_id'  => 'nullable|string',

            'priority'    => 'nullable|integer',
            'status'      => 'nullable|in:1,2',
        ]);

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

        $imagePath = $latestArticle->image;

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

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

        $latestArticle->update([
            'image'       => $imagePath,
            'title'        => $request->title,
            'alt_text' => $request->alt_text,
            'date' => $request->date,
            'amazon_link'       => $request->amazon_link,


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

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

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

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

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

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

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