<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\BaseShow;
use App\Http\Requests\Api\DocumentIndex;
use App\Http\Resources\DocumentListResource;
use App\Http\Resources\DocumentResource;
use App\Models\Document;
use App\Models\GenericBackoffice\WebsiteObject;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;

class DocumentController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @param DocumentIndex $request
     * @return JsonResource|JsonResponse
     */
    public function index(DocumentIndex $request)
    {
        $data = $request->validated();

        $query = Document::full()
            ->select('documents.*', 'document_languages.*', 'website_objects.*', 'website_objects_lang.*')
            ->where('status', 'published')
            ->where(function ($query) {
                $query->whereNull('publish_date')
                    ->orWhere('publish_date', '<=', Carbon::now('Europe/Brussels'));
            })->where(function ($query) {
                $query->whereNull('expiration_date')
                    ->orWhere('expiration_date', '>', Carbon::now('Europe/Brussels'));
            });

        if (!empty($data['topic'])) {
            $topicTree = WebsiteObject::select('tree_ids')
                ->where('object_id', $data['topic'])
                ->where('content_type', 'topics')
                ->first();

            if ($topicTree) {
                $treeIds = $topicTree->tree_ids;
                $query->whereHas('topics', function ($topicQuery) use ($treeIds) {
                    $topicQuery->whereIn('topics.id', $treeIds);
                });
            }
        }

        if (!empty($data['subtopic'])) {
            $query->whereHas('topics', function ($topicQuery) use ($data) {
                $topicQuery->where('topics.id', $data['subtopic']);
            });
        }

        if (!empty($data['documentType'])) {
            $query->where('document_type_id', $data['documentType']);
        }

        if (!empty($data['country'])) {
            $query->where('country_id', $data['country']);
        }

        switch ($data['orderBy']) {
            case 'country':
                $query->join('country_languages', function ($join) {
                    $join->on('country_languages.country_id', 'documents.country_id')
                        ->where('country_languages.language_id', getActiveLanguage());
                    })
                    ->orderBy('country_languages.title', 'asc');
                break;
            case 'alphabetical':
                $query->orderBy('title', 'asc');
                break;
            default:
                # latest
                $query->orderByRaw('ISNULL(publish_date), documents.publish_date DESC, documents.created_at DESC');
                break;
        }

        $perPage = $data['perPage'] ?? 9;
        $page = $data['page'] ?? 1;

        $query->with([
            'topics' => function($query) {
                $query->full();
            },
            'documentType' => function($query) {
                $query->full();
            },
            'country' => function($query) {
                $query->full()->with('flag');
            },
            'image',
            'documentFile',
            'tags' => function($query) {
                $query->full()->select('*');
            }
        ]);

        $documents = $query->paginate($perPage, ['*'], 'page', $page);

        $paginationData = [
            'currentPage' =>  intval($documents->currentPage()),
            'lastPage' => intval($documents->lastPage()),
            'perPage' =>  intval($documents->perPage()),
            'total' =>  intval($documents->total()),
            'count' =>  intval($documents->count()),
            'hasMorePages' => $documents->hasMorePages(),
            'nextPageUrl' => $documents->nextPageUrl(),
            'prevPageUrl' => $documents->previousPageUrl(),
        ];

        if ($documents) {
            // DB::enableQueryLog();
            // $tests = DocumentListResource::collection($documents);
            // collect($tests)->toArray();
            // dd(DB::getQueryLog());
            return [
                'data' => DocumentListResource::collection($documents),
                'pagination' => $paginationData,
            ];
        }
        return response()->json([], 404);
    }

    /**
     * Display the specified resource.
     *
     * @param BaseShow $request
     * @return JsonResource|JsonResponse
     */
    public function show(BaseShow $request)
    {
        $data = $request->validated();

        $query = Document::full()
            ->select('documents.*', 'document_languages.*')
            ->where('status', 'published')
            ->where('lang_slug', $data['slug'])
            ->where(function ($query) {
                $query->whereNull('publish_date')
                    ->orWhere('publish_date', '<=', Carbon::now('Europe/Brussels'));
            })->where(function ($query) {
                $query->whereNull('expiration_date')
                    ->orWhere('expiration_date', '>', Carbon::now('Europe/Brussels'));
            });

        $query->with([
            'topics' => function($query) {
                $query->full();
            },
            'documentType' => function($query) {
                $query->full();
            },
            'country' => function($query) {
                $query->full()->with('flag');
            },
            'image',
            'documentFile',
            'tags' => function($query) {
                $query->full()->select('*');
            }
        ]);

        $document = $query->first();

        if ($document) {

            $queryRelated = Document::full()
                ->select('documents.*', 'document_languages.*')
                ->where('status', 'published')
                ->where('lang_slug', '!=' , $data['slug'])
                ->where(function ($queryRelated) {
                    $queryRelated->whereNull('publish_date')
                        ->orWhere('publish_date', '<=', Carbon::now('Europe/Brussels'));
                })->where(function ($queryRelated) {
                    $queryRelated->whereNull('expiration_date')
                        ->orWhere('expiration_date', '>', Carbon::now('Europe/Brussels'));
                })
                ->where(function ($queryRelated) use ($document) {
                    $queryRelated->where('document_type_id', $document->document_type_id)
                        ->orWhere('country_id', $document->country_id)
                        ->orWhereHas('topics', function ($topicQuery) use ($document) {
                            $topicQuery->whereIn('topics.id', $document->topics->pluck('id'));
                        })
                        ->orWhereHas('tags', function ($query) use ($document) {
                            $query->whereIn('tag_id', $document->tags->pluck('id'));
                        });
                });

            $queryRelated->with([
                'topics' => function($query) {
                    $query->full();
                },
                'documentType' => function($query) {
                    $query->full();
                },
                'country' => function($query) {
                    $query->full()->with('flag');
                },
                'image',
                'documentFile',
                'tags' => function($query) {
                    $query->full()->select('*');
                }
            ]);

            $related = $queryRelated->take(3)->get();

            return [
                'document' => new DocumentResource($document),
                'related' => DocumentResource::collection($related),
            ];
        }

        return response()->json([], 404);
    }
}
