<?php

namespace App\Http\Controllers;

use App\Constants\Status;
use App\Models\Frontend;
use App\Models\Knowledge;
use App\Models\KnowledgeCategory;
use App\Models\KnowledgeView;
use App\Models\Language;
use App\Models\LikeDislike;
use App\View\Components\ViserForm;
use Illuminate\Http\Request;

class SiteController extends Controller
{
    public function index()
    {
        $pageTitle = 'Home';
        return view('Template::home', compact('pageTitle'));
    }

    public function category($slug = null)
    {
        $category = KnowledgeCategory::active()->where('slug', $slug)->firstOrFail();

        if ($category->knowledge_category_id) {
            $pageTitle = 'Knowledge of ' . $category->name;
            $category->load('subcategoriesKnowledge');
            $knowledgeList = Knowledge::active()->where('knowledge_subcategory_id', $category->id)->paginate(getPaginate());
            return view('Template::knowledge', compact('pageTitle', 'category', 'knowledgeList'));
        } else {
            $pageTitle = 'Subcategories of ' . $category->name;
            $category->load(['subcategories' => function ($subcategory) {
                $subcategory->withCount('subcategoriesKnowledge');
            }]);
            return view('Template::category', compact('pageTitle', 'category'));
        }
    }

    public function knowledge(Request $request)
    {
        $pageTitle      = 'Knowledge List';
        $knowledge      = Knowledge::searchable(['title', 'subtitle', 'description']);
        $knowledgeCount = (clone $knowledge)->count();
        $knowledgeList  = (clone $knowledge)->paginate(getPaginate());

        return view('Template::knowledge', compact('pageTitle', 'knowledgeCount', 'knowledgeList'));
    }

    public function knowledgeDetails($id)
    {
        $pageTitle = 'Knowledge Details';

        $knowledge = Knowledge::active()->whereHas('category', function ($q) {
            $q->active();
        })->whereHas('subcategory', function ($q) {
            $q->active();
        })->active()->with('category', 'subcategory')->withCount('likes', 'dislikes')->findOrFail($id);

        $isLikeDislike = LikeDislike::where('knowledge_id', $id)->where('user_id', auth()->id())->first();

        return view('Template::knowledge_details', compact('pageTitle', 'knowledge', 'isLikeDislike'));
    }

    public function loadKnowledgeComment(Request $request, $id)
    {
        $knowledge = Knowledge::active()->find($id);

        if (!$knowledge) {
            return response()->json([
                'status'  => 'error',
                'message' => 'No knowledge found',
            ]);
        }

        $comments   = $knowledge->comments()->with('replies')->latest()->paginate(getPaginate(10));
        $isLastPage = !$comments->hasMorePages();

        $html = view('Template::comment', compact('comments'))->render();

        return response()->json([
            'status'       => 'success',
            'html'         => $html,
            'is_last_page' => $isLastPage,
        ]);
    }

    public function storeViewCount($id)
    {
        $knowledge = Knowledge::active()->find($id);

        if (!$knowledge) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Knowledge not found',
            ]);
        }

        $visitorKey = md5($knowledge->id . '|' . request()->ip() . '|' . request()->header('User-Agent'));

        if (cache()->has($visitorKey)) {
            return null;
        }

        cache()->put($visitorKey, true, now()->addDay());

        $knowledgeView = KnowledgeView::where('date', today())->where('knowledge_id', $knowledge->id)->first();

        if ($knowledgeView) {
            $knowledgeView->increment('view');
        } else {
            $knowledgeView               = new KnowledgeView();
            $knowledgeView->knowledge_id = $knowledge->id;
            $knowledgeView->date         = today();
            $knowledgeView->view         = 1;
            $knowledgeView->save();
        }
    }

    public function loadDepartmentForm($id)
    {
        $component = new ViserForm('department_id', $id);

        $html = $component->render()->with([
            'form'     => $component->form,
            'formData' => $component->formData,
        ])->render();

        return response()->json(['html' => $html]);
    }

    public function policyPages($slug)
    {
        $policy    = Frontend::where('slug', $slug)->where('data_keys', 'policy_pages.element')->firstOrFail();
        $pageTitle = $policy->data_values->title;
        return view('Template::policy', compact('policy', 'pageTitle'));
    }

    public function changeLanguage($lang = null)
    {
        $language = Language::where('code', $lang)->first();
        if (!$language) {
            $lang = 'en';
        }

        session()->put('lang', $lang);
        return back();
    }

    public function placeholderImage($size = null)
    {
        $imgWidth  = explode('x', $size)[0];
        $imgHeight = explode('x', $size)[1];
        $text      = $imgWidth . '×' . $imgHeight;
        $fontFile  = realpath('assets/font/solaimanLipi_bold.ttf');
        $fontSize  = round(($imgWidth - 50) / 8);
        if ($fontSize <= 9) {
            $fontSize = 9;
        }
        if ($imgHeight < 100 && $fontSize > 30) {
            $fontSize = 30;
        }

        $image     = imagecreatetruecolor($imgWidth, $imgHeight);
        $colorFill = imagecolorallocate($image, 100, 100, 100);
        $bgFill    = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $bgFill);
        $textBox    = imagettfbbox($fontSize, 0, $fontFile, $text);
        $textWidth  = abs($textBox[4] - $textBox[0]);
        $textHeight = abs($textBox[5] - $textBox[1]);
        $textX      = ($imgWidth - $textWidth) / 2;
        $textY      = ($imgHeight + $textHeight) / 2;
        header('Content-Type: image/jpeg');
        imagettftext($image, $fontSize, 0, $textX, $textY, $colorFill, $fontFile, $text);
        imagejpeg($image);
        imagedestroy($image);
    }

    public function maintenance()
    {
        $pageTitle = 'Maintenance Mode';
        if (gs('maintenance_mode') == Status::DISABLE) {
            return to_route('home');
        }
        $maintenance = Frontend::where('data_keys', 'maintenance.data')->first();
        return view('Template::maintenance', compact('pageTitle', 'maintenance'));
    }
}
