<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller;
use App\Models\SubCategoryModel;
use App\Models\ArticleModel;
use Illuminate\Http\Request;
use Redirect;

class HomeController extends Controller
{
    public function index()
    {
        $articleCm = ArticleModel::where('active', 1)
            ->where('category_id', 1)
            ->limit(4)
            ->orderBy('id', 'DESC')
            ->get();

        $articleWhereElse = ArticleModel::where('active', 1)
            ->where('category_id', 2)
            ->limit(4)
            ->orderBy('id', 'DESC')
            ->get();

        $lang = 'index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'index';
        } else {
            $lang = 'index-en';
        }
        return view($lang)
            ->with('itemView', $articleCm)
            ->with('itemViewWhereElse', $articleWhereElse);
    }
    public function about()
    {
        $lang = 'about/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'about/index';
        } else {
            $lang = 'about/index-en';
        }
        return view($lang);
    }

    public function privacyPolicy()
    {
        $lang = 'about/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'privacy-policy/index';
        } else {
            $lang = 'privacy-policy/index-en';
        }
        return view($lang);
    }

    public function category()
    {
        $data["sub_category"] = [];
        $data["count_article"] = 0;

        $subCategoryList = SubCategoryModel::where('category_id', 1)->where('active', 1)->paginate(20);

        if ($subCategoryList->isNotEmpty()) {
            $data["sub_category"] = $subCategoryList;
            $data["count_article"] = [];
            foreach ($subCategoryList as $subCate) {
                $subCategoryId = $subCate->id;
                $countSub = ArticleModel::where('active', 1)
                    ->whereRaw('FIND_IN_SET(?, sub_category_ids)', [$subCategoryId])->count();
                $data["count_article"][$subCategoryId] = $countSub;
            }
        }

        $lang = 'category/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'category/index';
        } else {
            $lang = 'category/index-en';
        }
        return view($lang)
            ->with('itemView', $data);
    }
    public function article($subCateId, Request $request)
    {
        $subCategory = SubCategoryModel::where('id', $subCateId)->where('active', 1)->first();
        if ($subCategory == null) {
            return Redirect::to("category/chiangmai")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        // Get query parameters from the request
        $keyword = $request->query('search');
        $fromDate = $request->query('from');
        $toDate = $request->query('to');

        $fromDateFormatted = $fromDate ? date('Y-m-d', strtotime($fromDate)) . ' 00:00:00' : null;
        $toDateFormatted = $toDate ? date('Y-m-d', strtotime($toDate)) . ' 23:59:59' : null;

        // Apply filters only if they are provided
        $query = ArticleModel::where('active', 1)
            ->where('category_id', 1)
            ->orderBy('id', 'DESC')
            ->whereRaw('FIND_IN_SET(?, sub_category_ids)', [$subCateId]);

        if ($keyword) {
            $query->where('name', 'like', "%{$keyword}%");
            $query->orWhere('name_en', 'like', "%{$keyword}%");
        }

        if ($fromDateFormatted && $toDateFormatted) {
            $query->whereBetween('due_date', [$fromDateFormatted, $toDateFormatted]);
        }

        $query->where('category_id', 1);
        $data = $query->paginate(20);

        $lang = 'category/article/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'category/article/index';
        } else {
            $lang = 'category/article/index-en';
        }
        return view($lang)
            ->with('subCategoryView', $subCategory)
            ->with('itemView', $data)
            ->with('fromDateView', $fromDate)
            ->with('toDateView', $toDate)
            ->with('keywordView', $keyword);
    }
    public function articleDetail($id)
    {
        // get by id
        $data = ArticleModel::where('id', $id)->first();
        $subCategories = SubCategoryModel::where('active', 1)->where('category_id', 1)->get();

        $lang = 'category/article/detail-en';
        if (session()->get('locale') == 'th') {
            $lang = 'category/article/detail';
        } else {
            $lang = 'category/article/detail-en';
        }

        // get random
        $randomArticles = ArticleModel::inRandomOrder()
        ->where('id', '!=', $id)
        ->limit(4)
        ->get();

        return view($lang)
            ->with('itemView', $data)
            ->with('subCategoriesView', $subCategories)
            ->with('randomArticlesView', $randomArticles);
    }
    public function updateArticleCount(Request $request)
    {
        $id = $request->input('id');
        // update count

        $data = ArticleModel::where('id', $id)->first();
        
        $count = $data->count_view ?? 0;  // If null, set to 0
        $dataUpdate = [
            'count_view' => $count + 1, // Increment the count by 1
        ];

        ArticleModel::where('id', $id)->update($dataUpdate);
        return response()->json([
                'status' => true,
                'message' => "successfully"
            ]);
    }


    public function categoryWhereElse()
    {
        $data["sub_category"] = [];
        $data["count_article"] = 0;

        $subCategoryList = SubCategoryModel::where('category_id', 2)->where('active', 1)->paginate(20);

        if ($subCategoryList->isNotEmpty()) {
            $data["sub_category"] = $subCategoryList;
            $data["count_article"] = [];
            foreach ($subCategoryList as $subCate) {
                $subCategoryId = $subCate->id;
                $countSub = ArticleModel::where('active', 1)->whereRaw('FIND_IN_SET(?, sub_category_ids)', [$subCategoryId])->count();
                $data["count_article"][$subCategoryId] = $countSub;
            }
        }

        $lang = 'category-where-else/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'category-where-else/index';
        } else {
            $lang = 'category-where-else/index-en';
        }
        return view($lang)
            ->with('itemView', $data);
    }
    public function articleWhereElse($subCateId, Request $request)
    {
        $subCategory = SubCategoryModel::where('id', $subCateId)->where('active', 1)->first();
        if ($subCategory == null) {
            return Redirect::to("category/where-else")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        // Get query parameters from the request
        $keyword = $request->query('search');
        $fromDate = $request->query('from');
        $toDate = $request->query('to');

        $fromDateFormatted = $fromDate ? date('Y-m-d', strtotime($fromDate)) . ' 00:00:00' : null;
        $toDateFormatted = $toDate ? date('Y-m-d', strtotime($toDate)) . ' 23:59:59' : null;

        // Apply filters only if they are provided
        $query = ArticleModel::where('active', 1)
            ->orderBy('id', 'DESC')
            ->whereRaw('FIND_IN_SET(?, sub_category_ids)', [$subCateId]);

        if ($keyword) {
            $query->where('name', 'like', "%{$keyword}%");
            $query->orWhere('name_en', 'like', "%{$keyword}%");
        }

        if ($fromDateFormatted && $toDateFormatted) {
            $query->whereBetween('due_date', [$fromDateFormatted, $toDateFormatted]);
        }

        $query->where('category_id', 2);
        $data = $query->paginate(20);

        $lang = 'category-where-else/article/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'category-where-else/article/index';
        } else {
            $lang = 'category-where-else/article/index-en';
        }
        return view($lang)
            ->with('subCategoryView', $subCategory)
            ->with('itemView', $data)
            ->with('fromDateView', $fromDate)
            ->with('toDateView', $toDate)
            ->with('keywordView', $keyword);
    }
    public function articleDetailWhereElse($id)
    {
        // get by id
        $data = ArticleModel::where('id', $id)->first();
        $subCategories = SubCategoryModel::where('active', 1)->where('category_id', 1)->get();

        $lang = 'category-where-else/article/detail-en';
        if (session()->get('locale') == 'th') {
            $lang = 'category-where-else/article/detail';
        } else {
            $lang = 'category-where-else/article/detail-en';
        }

        // get random
        $randomArticles = ArticleModel::inRandomOrder()
        ->where('id', '!=', $id)
        ->limit(4)
        ->get();


        return view($lang)
            ->with('itemView', $data)
            ->with('subCategoriesView', $subCategories)
            ->with('randomArticlesView', $randomArticles);
    }

    public function contact()
    {
        $lang = 'contact/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'contact/index';
        } else {
            $lang = 'contact/index-en';
        }
        return view($lang);
    }

    public function articleAll(Request $request)
    {
        // Get query parameters from the request
        $keyword = $request->query('search');

        // Apply filters only if they are provided
        $query = ArticleModel::where('active', 1)
            ->where('category_id', 1)
            ->orderBy('id', 'DESC');

        if ($keyword) {
            $query->where('name', 'like', "%{$keyword}%");
            $query->orWhere('name_en', 'like', "%{$keyword}%");
        }

        $data = $query->paginate(20);

        $lang = 'article/index-en';
        if (session()->get('locale') == 'th') {
            $lang = 'article/index';
        } else {
            $lang = 'article/index-en';
        }
        return view($lang)
            ->with('itemView', $data)
            ->with('keywordView', $keyword);
    }
}
