<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\NewsArticleCategory;
use App\Models\NewsArticle;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Exception;
use Validator;

class ManageNewsAndArticlesController extends Controller
{
    /**
     * Created By : sayali parab
     * Created at : 27 May 2024
     * Use : To get newsarticle page.
     */

    public function index()
    {


        try {
            $news_article = NewsArticle::with('category')->latest()->get()->toArray();
            return view('Admin.pages.manage_cms.manage_new.manage_news', compact('news_article'));
        } catch (Exception $e) {
            Log::error("Manage Article Page Not Load: " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

    /**
     * Created By : sayali parab
     * Created at : 27 May 2024
     * Use : To change status.
     */
    public function change_news_article_Status(Request $request)
    {


        try {
            $status = NewsArticle::find($request->program_id);

            if (!$status) {
                return response()->json(['error' => 'Aboutus entry not found.'], 404);
            }

            $status->is_active = $request->status;
            $status->save();

            return response()->json(['success' => 'Status change successfully.']);
        } catch (\Exception $e) {
            // Log the exception or handle it in a way that makes sense for your application
            return response()->json(['error' => 'An error occurred while changing the status.'], 500);
        }
    }

    /**
     * Created By : sayali parab
     * Created at : 27 May 2024
     * Use : To edit.
     */
    public function edit($id)
    {

        try {
            $news_article_data = NewsArticle::find($id);
            $news_categories =  NewsArticleCategory::all()->toArray();
            return view('Admin.pages.manage_cms.manage_new.manage_news_edit', compact('news_article_data', 'news_categories'));
        } catch (\Exception $e) {
            // Handle the exception, you can log it or return an error response
            return response()->json(['success' => false, 'error' => $e->getMessage(), 'status' => 500]);
        }
    }

    // public function update(Request $request)
    // {
    //         try {


    //         $update_news_article = NewsArticle::find($request->article_id);
    //         $update_news_article->name = $request->input('article_name');
    //         // dd( $update_news_article->name);
    //         $update_news_article->description = $request->input('article_dis');
    //         // dd($update_news_article->description);

    //         // if ($request->hasFile('article_image')) {
    //         //     if ($update_news_article->image) {
    //         //         Storage::disk('public')->delete($update_news_article->image);
    //         //     }

    //         //     $uploadedFile = $request->file('article_image');
    //         //     $extension = $uploadedFile->getClientOriginalExtension();
    //         //     $filename = date('YmdHi') . '_' . str_replace(' ', '', $uploadedFile->getClientOriginalName());
    //         //     $path = $uploadedFile->storeAs('uploads/news_article', $filename, 'public');
    //         //     $update_news_article->image = $path;
    //         // }

    //         if ($request->hasFile('article_thmb')) {
    //             if ($update_news_article->image) {
    //                 Storage::disk('public')->delete($update_news_article->thumbnail_image);
    //             }

    //             $uploadedFile = $request->file('article_thmb');
    //             $extension = $uploadedFile->getClientOriginalExtension();
    //             $filename = date('YmdHi') . '_' . str_replace(' ', '', $uploadedFile->getClientOriginalName());
    //             $path = $uploadedFile->storeAs('uploads/news_article_thumb', $filename, 'public');
    //             $update_news_article->thumbnail_image = $path;
    //         }

    //         $update_news_article->save();
    //         // dd(  $update_news_article);
    //         return response()->json(['success' => true,'status'=>200]);
    //     } catch (\Exception $e) {
    //         return response()->json(['success' => false, 'error' => $e->getMessage(), 'status' => 500]);
    //     }
    // }

    /**
     * Created By : sayali parab
     * Created at : 27 May 2024
     * Use : To update.
     */

    public function update(Request $request)
    {
        try {
            $update_news_article = NewsArticle::find($request->article_id);
            $update_news_article->name = $request->input('article_name');
            $update_news_article->description = $request->input('article_dis');




            if ($request->hasFile('article_thmb')) {
                if ($update_news_article->image) {
                    Storage::disk('public')->delete($update_news_article->thumbnail_image);
                }

                $uploadedFile = $request->file('article_thmb');
                $extension = $uploadedFile->getClientOriginalExtension();
                $filename = date('YmdHi') . '_' . str_replace(' ', '', $uploadedFile->getClientOriginalName());
                $path = $uploadedFile->storeAs('uploads/news_article_thumb', $filename, 'public');
                $update_news_article->thumbnail_image = $path;
            }

            $update_news_article->save();

            return response()->json(['success' => true, 'status' => 200]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'error' => $e->getMessage(), 'status' => 500]);
        }
    }
    /**
     * Created By : sayali parab
     * Created at : 28 May 2024
     * Use : To delete.
     */
    public function delete_newsarticle($id)
    {

        try {
            $blog = NewsArticle::find($id);

            if (!$blog) {
                return response()->json(['error' => 'Aboutus entry not found.'], 404);
            }

            $blog->delete();

            return response()->json(['success' => 'Aboutus entry deleted successfully.']);
        } catch (\Exception $e) {
            // Log the exception or handle it in a way that makes sense for your application
            return response()->json(['error' => 'An error occurred while deleting the Aboutus entry.'], 500);
        }
    }

    /**
     * Created By : sayali parab
     * Created at : 28 May 2024
     * Use : To add.
     */
    public function add()
    {
        $news_categories =  NewsArticleCategory::all()->toArray();
        return view('Admin.pages.manage_cms.manage_new.manage_news_add', compact('news_categories'));
    }


    /**
     * Created By : sayali parab
     * Created at : 28 May 2024
     * Use : To insert.
     */
    // public function insert(Request $request)
    // {
    //     try {
    //         // Validate the incoming request
    //         // $request->validate([
    //         //     // 'article_name' => 'required|string',
    //         //     // 'article_des' => 'required|string',
    //         //     'article_thmb' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
    //         //     'category' => 'required|string', // Assuming 'category' is the field for category selection
    //         // ]);

    //         DB::beginTransaction();

    //         // Handle thumbnail image upload
    //         if ($request->hasFile('article_thmb')) {
    //             $uploadedFile = $request->file('article_thmb');
    //             $filename = date('YmdHi') . '_' . str_replace(' ', '', $uploadedFile->getClientOriginalName());
    //             $path = $uploadedFile->storeAs('uploads/news_article_thumb', $filename, 'public');
    //         }
    //           // Handle the image upload
    //     if ($request->hasFile('article_image')) {
    //         $image = $request->file('article_image');
    //         $imageName = date('YmdHi') . '_' . str_replace(' ', '',$image->getClientOriginalName());
    //         $image_path= $image->storeAs('uploads/news_article_image', $imageName, 'public');
    //     }

    //         // Create a new instance of NewsArticle model and populate it with data
    //         $blog = NewsArticle::create([
    //             'name' => $request->input('article_name'),
    //             'description' => $request->input('article_des'),
    //             'news_articles_category_xid' => $request->input('category'),
    //             'thumbnail_image' => $path, // Set thumbnail image path
    //             'image'=> $image_path
    //         ]);
    //         // dd( $blog);

    //         DB::commit();

    //         return response()->json([
    //             'success' => true,
    //             'status' => 200,
    //             'message' => 'News article added successfully',
    //         ]);
    //     } catch (\Exception $exception) {
    //         DB::rollBack();
    //         // Log the exception for further analysis
    //         Log::error('Error in insert method: ' . $exception->getMessage() . ' at ' . $exception->getFile() . ':' . $exception->getLine());

    //         // Return an error response
    //         return response()->json(['error' => 'Failed to add news article'], 500);
    //     }
    // }



public function insert(Request $request)
{

    try {
        $blog = new NewsArticle;
        $blog->name = $request->input('article_name');
        $blog->description = $request->input('article_des');
        $blog->news_articles_category_xid = $request->input('category');

        if ($request->hasFile('article_image')) {
            $uploadedFile = $request->file('article_image');
            $extension = $uploadedFile->getClientOriginalExtension();
            $filename = date('YmdHi') . '_' . str_replace(' ', '', $uploadedFile->getClientOriginalName());
            $path = $uploadedFile->storeAs('uploads/news_article', $filename, 'public');
            $blog->image = $path;
        }
        if ($request->hasFile('article_thmb')) {
            $uploadedFile = $request->file('article_thmb');
            $extension = $uploadedFile->getClientOriginalExtension();
            $filename = date('YmdHi') . '_' . str_replace(' ', '', $uploadedFile->getClientOriginalName());
            $path = $uploadedFile->storeAs('uploads/news_article_thumb', $filename, 'public');
            $blog->thumbnail_image = $path;
        }
        $blog->save();
       return response()->json(['success' => true,'status'=>200]);
    } catch (\Exception $e) {
        // Handle the exception, you can log it or return an error response
        return response()->json(['success' => false, 'error' => $e->getMessage(), 'status' => 500]);
    }
}

}
