<?php

namespace App\Http\Controllers\Admin;

use App\Category;
use App\Country;
use App\Project;
use App\ProjectDetail;
use App\ProjectDetailDescription;
use Exception;
use App\ProjectDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\ProjectRequest;
use App\Http\Controllers\Controller;

class ProjectController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/projects';
    /** View folder */
    private $viewDirectory = 'admin.projects.';

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }
    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('projects.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',get_defined_vars());
    }

    /**
     * return data of the projects.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Project::orderBy('projects.id', 'DESC')
            ->join('project_descriptions AS pd', 'projects.id', 'pd.project_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('pd.language_id', currentLanguage()->id)
            ->select(['pd.name', 'projects.*']);

        if ($request->date_from) {
            $query->whereDate('projects.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('projects.created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('pd.name', 'LIKE', '%'.$request->name.'%');
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $projects= $query->paginate(100);

        return view($this->viewDirectory.'grid',get_defined_vars());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('projects.store');
        $head = metaFields('projects', 'new', getCurrentLocale()) ?? __('projects.new');
        $photos = [];
        $local = getCurrentLocale();
        $countries = Country::withDescription();
        $categories = Category::withDescription();
        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param ProjectRequest $request
     * @return JsonResponse
     */
    public function store(ProjectRequest $request) :JsonResponse
    {
        $project = Project::create($request->all());
        $this->saveData( $request, $project->id );
        session()->flash('message', __('dashboard.saveDone'));
        return  response()->json(['url' => route('projects.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Project $project
     * @return View
     */
    public function edit(Project $project) :View
    {
        $action= route('projects.update', $project->id);
        $head = metaFields('projects', 'edit', getCurrentLocale()) ?? __('projects.edit');

        $query = ProjectDescription::where('project_id', $project->id)
            ->join('languages', 'languages.id', 'project_descriptions.language_id')
            ->select(['project_descriptions.*', 'languages.local']);

        $projectDescription= $query->get();

        $work_scope = [];
        foreach ($projectDescription as $row) {
            $project[$row->local]= $row;
            $work_scope[$row->local]= $row->workScope;
        }

        $photos = is_string($project->images) ? json_decode($project->images, true) : $project->images;
        $local = getCurrentLocale();
        $countries = Country::withDescription();
        $categories = Category::withDescription();

        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ProjectRequest $request
     * @param Project $project
     * @return JsonResponse
     */
    public function update(ProjectRequest $request, Project $project) :JsonResponse
    {
        $project->update($request->all());

        // Delete old description
        ProjectDescription::where('project_id', $project->id)->delete();

        // Insert new description
        $this->saveData( $request, $project->id );

        session()->flash('message', __('dashboard.saveDone'));
        return  response()->json(['url' => route('projects.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param ProjectRequest $request
     * @param int $project_id
     * @return void
     */

    private function saveData(ProjectRequest $request, int $project_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'project_id'=> $project_id,
                'language_id'=> $lang->id,
            ];

            $workScopes = [];
            if (isset($requestData['work_scopes_'.$lang->local])){
                foreach ($requestData['work_scopes_'.$lang->local] as $i => $value) {
                    if ($value) {
                        $workScopes[] = $value;
                    }
                }
            }

            $data['work_scopes'] = $workScopes;

            ProjectDescription::create($data);
        }

    }


    public function details()
    {
        $head=  __('projects.page_details');
        $detail = ProjectDetail::first();
        $descriptions = ProjectDetailDescription::where('project_detail_id', $detail->id)
            ->join('languages', 'languages.id', 'project_detail_descriptions.language_id')
            ->select(['project_detail_descriptions.*', 'languages.local'])->get();

        foreach ($descriptions as $description) {
            $detail[$description->local] = $description;
        }

        $action= route('projects.updateDetails', $detail->id);

        return view($this->viewDirectory.'details', get_defined_vars());
    }

    public function updateDetails(ProjectRequest $request, ProjectDetail $projectDetail)
    {
        $data = $request->all();
        $projectDetail->update($data);
        ProjectDetailDescription::where('project_detail_id', $projectDetail->id)->delete();

        foreach (languages() as $lang) {
            $detailData=[
                'title'=> $data['title_'.$lang->local],
                'description'=> $data['description_'.$lang->local],
                'project_detail_id'=> $projectDetail->id,
                'language_id'=> $lang->id,
            ];
            ProjectDetailDescription::create($detailData);
        }

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));


    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $project = Project::withTrashed()->find($id);
        if ($project) {
            if ($project->deleted_at) {
                $project->forceDelete();
            } else {
                $project->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several projects by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Project::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Project::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $project = Project::withTrashed()->find($id);

        if ($project){
            $project->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several projects by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $projects = Project::whereIn('id', $request->ids)->onlyTrashed();
        if ($projects){
            $projects->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
