<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Project;
use App\Job;
use App\Building;
use App\Employee;
use App\Message;

class ProjectController extends Controller
{
    public function allProjectsForManager($id)
    {
        // $projects = Project::where("created_by", $id)->orderBy("id", 'desc')->get();
        $projects = Project::orderBy("id", 'desc')->get();

        foreach ($projects as $project) {
            $user = User::where("id", $project->created_by)->first();
            $employees = Message::where("project_id", $project->id)->get();
            foreach($employees as $message) {
                $employee = Employee::where('id', $message->employee_id)->first();
                if ($employee) {
                    $job = Job::where("id", $employee->position)->first();
                    $message->setAttribute("avatar", $employee->image);
                    $message->setAttribute("email", $employee->email);
                    if ($job) {
                        $message->setAttribute("position", $job->title);
                    } else {
                        $message->setAttribute("position", "N/A");
                    }
                } else {
                    $message->setAttribute("avatar", null);
                    $message->setAttribute("position", null);
                    $message->setAttribute("email", "N/A");
                }
                
            }
            $project->setAttribute("employees", $employees);
            $project->setAttribute("created_by_name", $user->first_name. " ".$user->last_name);
        }

        return [
            'status' => 200,
            'message' => "Projects Fetched Successfully",
            'projects' => $projects
        ];
    }

    public function allProjectsForEmployee($id)
    {
        $employees = Message::where("employee_id", $id)->orderBy("id", 'desc')->get();
        $projects = [];

        foreach ($employees as $employee) {
            $project = Project::where("id", $employee->project_id)->first();
            if ($project) {
                $_employees = Message::where("project_id", $project->id)->get();
                $project->setAttribute("employees", $_employees);
                $projects[] = $project;
            }
        }

        return [
            'status' => 200,
            'message' => "Projects Fetched Successfully",
            'projects' => $projects
        ];
    }

    public function getJobsByEmployeeId($id)
    {
        $employee = Employee::where("id", $id)->first();
        // $jobs = Job::where('created_by', $employee->created_by)->get();
        $jobs = Job::all();

        return [
            'status' => 200,
            'message' => "Jobs Fetched Successfully",
            'jobs' => $jobs
        ];
    }

    public function getBuildByEmployeeId($id)
    {
        $employee = Employee::where("id", $id)->first();
        // $buildings = Building::where('created_by', $employee->created_by)->get();
        $buildings = Building::all();

        return [
            'status' => 200,
            'message' => "Jobs Fetched Successfully",
            'buildings' => $buildings
        ];
    }

    public function getAllJobs($id)
    {
        // $jobs = Job::where('created_by', $id)->get();
        $jobs = Job::all();

        return [
            'status' => 200,
            'message' => "Jobs Fetched Successfully",
            'jobs' => $jobs
        ];
    }
    public function addJob()
    {
        $request = request(['title', 'id']);
        // dd($request);

        Job::create([
            'created_by' => $request['id'],
            'title' => $request['title']
        ]);

        return [
            'status' => 200,
            'message' => "job_created_successfully",
            'jobs' => Job::where('created_by', $request['id'])->get()
        ];
    }
    public function updateJob($id)
    {
        $request = request(['title', 'id']);
        $job = Job::where('id', $request['id'])->first();
        $job->title = $request['title'];
        $job->save();

        return [
            'status' => 200,
            'message' => "job_updated_successfully",
            'jobs' => Job::where('created_by', $id)->get()
        ];
    }
    public function deleteJob($id, $user_id)
    {
        Job::where('id', $id)->delete();

        return [
            'status' => 200,
            'message' => "job_removed_successfully",
            'jobs' => Job::where('created_by', $user_id)->get()
        ];
    }

    public function getAllBuildings($id)
    {
        // $buildings = Building::where('created_by', $id)->get();
        $buildings = Building::all();

        return [
            'status' => 200,
            'message' => "Buildings Fetched Successfully",
            'buildings' => $buildings
        ];
    }
    public function addBuilding()
    {
        $request = request(['title', 'id']);

        Building::create([
            'created_by' => $request['id'],
            'title' => $request['title']
        ]);

        return [
            'status' => 200,
            'message' => "building_created_successfully",
            'buildings' => Building::where('created_by', $request['id'])->get()
        ];
    }
    public function updateBuilding()
    {
        $request = request(['title', 'id']);
        $building = Building::where('id', $request['id'])->first();
        $building->title = $request['title'];
        $building->save();

        return [
            'status' => 200,
            'message' => "building_updated_successfully",
            'buildings' => Building::where('created_by', $building->created_by)->get()
        ];
    }
    public function deleteBuilding($id)
    {
        $building = Building::where('id', $id)->first();
        $created_by = "";
        if ($building) {
            $created_by = $building->created_by;
            $building->delete();
        }

        return [
            'status' => 200,
            'message' => "building_removed_successfully",
            'buildings' => Building::where('created_by', $created_by)->get()
        ];
    }
    public function getProjectFormData($id)
    {
        return [
            'status' => 200,
            'message' => "data_fetched_successfully",
            // 'buildings' => Building::where('created_by', $id)->get(),
            // 'employees' => Employee::where('created_by', $id)->get(),
            'buildings' => Building::all(),
            'employees' => Employee::all(),
        ];
    }



    public function deleteFile($id, $index)
    {
        $task = Project::where("id", $id)->first();
        $files = explode("****", $task->files);
        $allFiles = [];
        foreach ($files as $i => $file) {
            if ($i !== $index) {
                $allFiles[] = $file;
            } else {
                if (file_exists($file)) {
                    unlink($file);
                }
            }
        }
        $task->files = implode("****", $allFiles);
        return [
            "status" => 200
        ];
    }

    public function deleteProject($id)
    {
        Project::where("id", $id)->delete();
        Message::where("project_id", $id)->delete();
        return [
            "status" => 200
        ];
    }

    public function deleteAddedEmployee($id)
    {
        Message::where("id", $id)->delete();
        return [
            "status" => 200
        ];
    }

    public function completeProject($task_id, $id)
    {
        $task = Project::where("id", $task_id)->first();
        $progress = 0;
        $completed_by = [];
        if ($task->completed_by) {
            $completed_by = explode(",", $task->completed_by);
        }
        $completed_by[] = $id;
        $added_employees_count = Message::where("project_id", $task_id)->count();

        if ($added_employees_count) {
            $progress = count($completed_by) / $added_employees_count * 100;
        }

        $task->completed_by = implode(",", $completed_by);
        $task->progress = $progress;
        $task->save();

        return [
            "status" => 200
        ];
    }

    public function addNewTask($id, $check, request $request)
    {
        $filePaths = [];
        if ($check == "edit") {
            $task = Project::where('id', $request->id)->first();
            if ($task->files) {
                $filePaths = explode("****", $task->files);
            }
        } else {
            $task = new Project();
        }
        $fileCount = $request->filesCount;
        $employeeCount = $request->employeesCount;
        if ($fileCount) {
            for ($i = 1; $i <= $fileCount; $i++) {
                if ($request->hasFile('file' . $i)) {
                    $file = $request['file' . $i];
                    $destinationPath = public_path('uploads/');
                    $originalFile = $file->getClientOriginalName();
                    $filename = strtotime(date('Y-m-d-H:isa')) . $originalFile;
                    $file->move($destinationPath, $filename);
                    $filePaths[] = $filename;
                }
            }
        }
        $task->created_by = $id;
        $task->casenumber = $request->casenumber;
        $task->description = $request->description;
        $task->address = $request->address;
        $task->zip_code = $request->zip_code;
        $task->city = $request->city;
        $task->building = $request->building;
        $task->priority = $request->priority;
        $task->start_date = $request->start_date;
        $task->end_date = $request->end_date;
        if ($request->building) {
            $task->building = $request->building_title;
        }
        $task->files = implode("****", $filePaths);
        $task->save();

        if ($employeeCount) {
            for ($i = 1; $i <= $employeeCount; $i++) {
                $employee = $request['employee' . $i];
                $employee = explode("****", $employee);

                $added = Message::where('employee_id', $employee[0])->where('project_id', $request->id)->first();
                // return $added;
                if (!$added) {
                    $added = new Message();
                    $added->employee_id = $employee[0];
                    $added->created_by = $id;
                    $added->project_id = $task->id;
                }
                $added->name = $employee[1];
                $added->phone = $employee[2];
                $added->start_date = $employee[3];
                $added->end_date = $employee[4];
                $added->description = $employee[5];
                $added->save();
            }
        }

        $msg = "task_created_successfully";
        if ($request->id) {
            $msg = "task_updated_successfully";
        }

        return [
            'status' => 200,
            'message' => $msg,
        ];
    }
}
