<?php

namespace App\Http\Controllers;

use App\Models\File;
use App\Models\Occupation;
use App\Models\Post;
use App\Models\Status;
use App\Models\TimePeriod;
use App\Models\User;
use Carbon\Carbon;
use Carbon\Traits\Date;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request): View
    {
        $search = $request->input("s");

        $posts = Post::query()
            ->join("statuses", "posts.status_id", "=", "statuses.id")
            ->join("occupations", "posts.occupation_id", "=", "occupations.id")
            ->where("posts.title", "LIKE", "%{$search}%")
            ->orWhere("posts.text", "LIKE", "%{$search}%")
            ->orWhere("statuses.name", "LIKE", "%{$search}%")
            ->orWhere("occupations.name", "LIKE", "%{$search}%")
            ->where("statuses.name", "NOT", "Pending")
            ->get();

        return view("index", [ "posts" => $posts]);
    }

    /**
     * @return Application|Factory|View
     */
    public function create() : View
    {
        $occupations = Occupation::all();

        $formats = TimePeriod::all();

        return view("create-post", [
            "occupations" => $occupations,
            "formats" => $formats
        ]);
    }

    /**
     * @param Request $request
     * @return RedirectResponse
     */

    public function store(Request $request) : RedirectResponse
    {
        $saved = false;


        $rawpost = $request->validate([
            'title' => 'required|string',
            'text' => 'required|string',
            'file' => 'nullable|file|mimes:pdf',
            'time' => 'required|integer',

            'time_period_id' => 'required|integer',
            'occupation_id' => 'required|integer',
        ]);

        $post = new Post();

        $post->title = $rawpost["title"];
        $post->post_time = Carbon::now();
        $post->time = $rawpost["time"];

        // Sets state to the default.
        $post->status()->associate(Status::where("name", "Pending")->first());

        // Sets the user to the current user.
        $post->user()->associate($request->user());

        if($request->user()->role->name === "Admin"){
            $post->status()->associate(Status::where("name", "Looking for collaborator")->first());
        }
        else {
            $post->status()->associate(Status::where("name", "Pending")->first());
        }
        // Sets status to the default.


        $post->timePeriod()->associate($rawpost["time_period_id"]);

        $post->occupation()->associate($rawpost["occupation_id"]);

//        if(key_exists("text", $rawpost) && $rawpost['text'] != null) {
            $post->text = $rawpost['text'];

            $saved = $post->save();
//        }
//        else {
            // Handle file upload.


        if(key_exists("file", $rawpost))
        {
            if($request->file("file") == null) {
                return \redirect("error");
            }

            $filePath = $request->file("file")->store("public/uploads");

            $file = new File();
            $file->link = $filePath;

            $saved = $post->save();

            $file->post()->associate($post);

            $file->save();
        }
        // }

        if($saved) {
            return redirect()->route("index");
        }

        return redirect()->route("error");
    }

    /**
     * Display the specified resource.
     *
     * @param Post $post
     * @return View
     */
    public function show(Post $post): View
    {

        $occupations = Occupation::all();

        $formats = TimePeriod::all();

        $states = Status::all();

        return view("admin.show-post", [
            "post" => $post,
            "occupations" => $occupations,
            "formats" => $formats,
            "states" => $states
        ]);
    }

    /**
     * @param Request $request
     * @param Post $post
     * @return Application|Factory|View
     */

    public function update(Request $request, Post $post)
    {
        Log::critical("REEEEE");

        $data = $request->validate([
            'title' => 'required|string',
//            'text' => 'required|string',
            'text' => 'required|string',
            'file' => 'nullable|file',
            'time' => 'required|integer',
            'occupation_id' => 'required|integer',
            'state_id' => 'required|integer',
            'time_period_id' => 'required|integer'
        ]);

        Log::critical("PRE UPDATE");


        $post->update($data);
        Log::critical("UPDATE");


        $saved = false;

//        if(key_exists("text", $data) && $data['text'] != null && $data['text'] != '') {
            $post->text = $data['text'];
            Log::critical("FIRST IF");

            $saved = $post->save();
//        }
//        else {
            // Handle file upload.


        if(key_exists("file", $data)) {
            if($request->file("file") == null) {
                return \redirect("error");
            }

            $filePath = "";

            if($post->files()->first()->exists()) {
                $filePath = $request->file("file")->storeAs("public/uploads", $post->files()->first()->link);
//                $saved = $post->save();
                Log::critical("IF");
            }
            else {
                $filePath = $request->file("file")->store("public/uploads");

                $file = new File();
                $file->link = $filePath;


                $file->post()->associate($post);

                $file->save();
                Log::critical("ELSE");

            }
        }
//        }

        $post->occupation()->associate(Occupation::find($data["occupation_id"]));
        $post->status()->associate(Status::find($data["state_id"]));
        $post->timePeriod()->associate(TimePeriod::find($data["time_period_id"]));

        $saved = $post->save();

        $occupations = Occupation::all();
        $formats = TimePeriod::all();
        $states = Status::all();

        if($saved){
            return view("admin.show-post", [
                "post" => $post,
                "occupations" => $occupations,
                "formats" => $formats,
                "states" => $states
            ]);
        }else{
            return view("admin.show-post", [
                "post" => $post,
                "occupations" => $occupations,
                "formats" => $formats,
                "states" => $states,
                "success" => "Opdaterede opslaget."
            ]);
        }
    }

    /**
     * @param Post $post
     * @return RedirectResponse
     */

    public function destroy(Post $post) : RedirectResponse
    {
        $post->delete();
        return redirect()->route("index");
    }
}