<?php

namespace App\Http\Controllers;


use App\Models\Article;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\Article as ArticleCollection;

class ArticleController extends Controller
{
    public function index(Request $request)
    {
        try {
            $limit = $request->query('limit', 10);
                $query = Article::query();
                // Get all parameters from the request
                $parameters = $request->all();

                // Loop through each parameter and apply filters to the query
                foreach ($parameters as $key => $value) {
                    // Make sure the key is not a reserved Laravel parameter
                    if ($key !== 'page' && $key !== 'limit' && $key !== 'myarticle') {
                        if (in_array($key, ['article_title'])) {
                            // Apply search functionality using 'like' for name, email, and phone
                            $query->where($key, 'like', "%$value%");
                        } else {
                            // Apply exact match for other fields
                            $query->where($key, $value);
                        }
                    }
                }

                if ($request->has('myarticle')) {
                    $query->where('user_id', $request->user()->id);
                }


                $articles = $query->orderBy('updated_at', 'desc')->paginate($limit);
                
                $articleCollection = ArticleCollection::collection($articles->items());

                $responseData = [
                    'records' => $articleCollection,
                    'pagination' => [
                        'current_page' => $articles->currentPage(),
                        'last_page' => $articles->lastPage(),
                        'per_page' => $articles->perPage(),
                        'total' => $articles->total(),
                    ],
                ];
                
            return response()->json($responseData);
        } catch (QueryException $e) {
            return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
    }


    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'article_title' => 'required|string',
            ]);

            DB::beginTransaction();
            $article = Article::create([
                'article_title' => $request->article_title,
                'article_content' => $request->article_content,
                'image_id' => $request->image_id,
                'user_id' => $request->user()->id,
                'status' => $request->status ?? true, // Default to true if status is not provided.
                'is_publish' => $request->is_publish ?? false,
            ]);
 
            DB::commit();
            return response()->json(['message' => 'Article created successfully', 'record' => new ArticleCollection($article)], 201);
        } catch (QueryException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        try{
            $article = Article::findOrFail($id);
            return response()->json(['message' => 'Article Details Fetached successfully', 'record' => new ArticleCollection($article)], 200);
        }catch (\Exception $e) {
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
        
    }


    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            $validatedData = $request->validate([
                'article_title' => 'required|string|max:100',
            ]);

            DB::beginTransaction();
    
            $article = Article::findOrFail($id); 
            // Update user data
            $article->article_title = $request->article_title;
            $article->article_content = $request->article_content;
            $article->image_id = $request->image_id;
            $article->status = $request->status ?? $article->status;
            $article->is_publish = $request->is_publish ?? $article->is_publish;
            $article->save();
            DB::commit();
    
            return response()->json(['message' => 'Article updated successfully', 'record' => new ArticleCollection($article)], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Article not found'], 404);
        } catch (QueryException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $ids = explode(",",$id);
            if (!empty($ids)) {
                // Fetch the article  with the specified IDs
                $articles = Article::whereIn('id', $ids)->get();
                
                // Delete the fetched article groups
                foreach ($articles as $article) {
                    $article->delete();
                }
            }
                return response()->json(['message' => 'Article and associated entries deleted successfully'], 200);
        } catch (ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Article not found'], 404);
        } catch (QueryException $e) {
            DB::rollBack();
            return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
    }

    public function publishArticle(Request $request)
    {
        try {
            $limit = $request->query('limit', 10);
                $query = Article::query();
                // Get all parameters from the request
                $parameters = $request->all();

                // Loop through each parameter and apply filters to the query
                foreach ($parameters as $key => $value) {
                    // Make sure the key is not a reserved Laravel parameter
                    if ($key !== 'page' && $key !== 'limit') {
                        if (in_array($key, ['article_title'])) {
                            // Apply search functionality using 'like' for name, email, and phone
                            $query->where($key, 'like', "%$value%");
                        } else {
                            // Apply exact match for other fields
                            $query->where($key, $value);
                        }
                    }
                }
                $query->where('is_publish', 1)->where('status',1);
                $articles = $query->orderBy('updated_at', 'desc')->paginate($limit);
                
                $articleCollection = ArticleCollection::collection($articles->items());

                $responseData = [
                    'records' => $articleCollection,
                    'pagination' => [
                        'current_page' => $articles->currentPage(),
                        'last_page' => $articles->lastPage(),
                        'per_page' => $articles->perPage(),
                        'total' => $articles->total(),
                    ],
                ];
                
            return response()->json($responseData);
        } catch (QueryException $e) {
            return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
    }
}
