<?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;
use App\Reply;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\UploadedFile;

class EmployeeController extends Controller
{
    public function getDashboardData($id)
    {
        // $task_count = Project::where('created_by', $id)->count();
        // $task_inProgress_count = Project::where('created_by', $id)->where('progress', "!=", 100)->count();
        // $task_completed_count = Project::where('created_by', $id)->where('progress', 100)->count();
        
        // $job_count = Job::where('created_by', $id)->count();
        // $building_count = Building::where('created_by', $id)->count();
        // $employee_count = Employee::where('created_by', $id)->count();
        // $conversations = Message::where('created_by', $id)->get();
        
        $task_count = Project::count();
        $task_inProgress_count = Project::where('progress', "!=", 100)->count();
        $task_completed_count = Project::where('progress', 100)->count();
        
        $job_count = Job::count();
        $building_count = Building::count();
        $employee_count = Employee::count();
        $conversations = Message::all();
        $conversations_count = count($conversations);
        $replies_count = 0;
        
        foreach ($conversations as $chat) {
            $replies_count += Reply::where('message_id', $chat->id)->where('type', '!=', 'employee')->count();
        }
        
        
        return [
            "status" => 200,
            'message' => "Fetched",
            'task_count' => $task_count,
            'task_inProgress_count' => $task_inProgress_count,
            'task_completed_count' => $task_completed_count,
            'job_count' => $job_count,
            'building_count' => $building_count,
            'employee_count' => $employee_count,
            'conversations_count' => $conversations_count,
            'replies_count' => $replies_count,
        ];
    }
    public function getEmployeeFormData($id)
    {
        return [
            "status" => 200,
            'message' => "",
            // 'jobs' => Job::where('created_by', $id)->get()
            'jobs' => Job::all()
        ];
    }

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

    public function addEmployee($id, Request $request)
    {
        // return $request;
        $emp = Employee::where('email', $request->email)->first();
        if ($emp) {
            return [
                'status' => 100,
                'message' => 'Email already exist'
            ];
        }
        $filename = null;
        $file = $request->image;
        if ($file) {
            $destinationPath = public_path('uploads/');
            $originalFile = $file->getClientOriginalName();
            $filename = strtotime(date('Y-m-d-H:isa')) . $originalFile;
            $file->move($destinationPath, $filename);
        }
        if ($filename) {
            $filename =  $filename;
        }

        Employee::create([
            'name'       => $request->name,
            'address'    => $request->address,
            'zip_code'   => $request->zip_code,
            'city'       => $request->city,
            'phone'      => $request->phone,
            'email'      => $request->email,
            'password'   => bcrypt($request->password),
            'position'   => $request->position,
            'image'      => $filename,
            'created_by' => $id,
        ]);

        return [
            "status" => 200,
            'message' => "employee_added_successfully"
        ];
    }

    public function updateEmployeeProfile($id, Request $request)
    {
        $filename = null;
        $file = $request->image;
        $employee = Employee::where('id', $id)->first();
        if ($file) {
            $destinationPath = public_path('uploads/');
            $originalFile = $file->getClientOriginalName();
            $filename = strtotime(date('Y-m-d-H:isa')) . $originalFile;
            $file->move($destinationPath, $filename);
        } else {
            $filename = $employee->image;
        }

        Employee::where("id", $id)->update([
            'name'     => $request->name,
            'address'  => $request->address,
            'zip_code' => $request->zip_code,
            'city'     => $request->city,
            'phone'    => $request->phone,
            'email'    => $request->email,
            'position' => $request->position,
            'image'    => $filename,
        ]);

        $messages = Message::where('employee_id', $id)->get();

        foreach ($messages as $message) {
            $message->name  = $request->name;
            $message->phone = $request->phone;
            $message->save();
        }

        return [
            'profile' => Employee::where("id", $id)->first(),
            "status"  => 200,
            'message' => "employee_updated_successfully"
        ];
    }
    public function updateEmployee($id, Request $request)
    {
        $filename = null;
        $file = $request->image;
        $employee = Employee::where('id', $request->id)->first();
        if ($file) {
            $destinationPath = public_path('uploads/');
            $originalFile = $file->getClientOriginalName();
            $filename = strtotime(date('Y-m-d-H:isa')) . $originalFile;
            $file->move($destinationPath, $filename);
        } else {
            $filename = $employee->image;
        }

        Employee::where("id", $request->id)->update([
            'name'     => $request->name,
            'address'  => $request->address,
            'zip_code' => $request->zip_code,
            'city'     => $request->city,
            'phone'    => $request->phone,
            'email'    => $request->email,
            'position' => $request->position,
            'image'    => $filename,
        ]);

        $messages = Message::where('employee_id', $request->id)->get();

        foreach ($messages as $message) {
            $message->name  = $request->name;
            $message->phone = $request->phone;
            $message->save();
        }

        return [
            "status"  => 200,
            'message' => "employee_updated_successfully"
        ];
    }


    public function getEmployees($id)
    {
        $employees = Employee::all();
        
        foreach ($employees as $employee) {
            $user = User::where('id', $employee->created_by)->first();
            if ($user) {
                $employee->setAttribute("created_by_name", $user->name);
            } else {
                $employee->setAttribute("created_by_name", "N/A");
            }
        }
        
        return [
            'status' => 200,
            'message' => "Employees Data Fetched Successfully",
            // 'employees' => Employee::where('created_by', $id)->get()
            'employees' => $employees
        ];
    }

    public function getConversations($id)
    {
        // $messages = Message::where('created_by', $id)->orderBy("id", "desc")->get();
        $messages = Message::orderBy("id", "desc")->get();

        foreach ($messages as $message) {
            $project = Project::where("id", $message->project_id)->first();
            $employee = Employee::where('id', $message->employee_id)->first();
            $replies = Reply::where('message_id', $message->id)->orderBy('id', "desc")->get();
            // dd($replies);
            $message->setAttribute("task", $project);
            if ($replies) {
                $unread_count = 0;
                foreach ($replies as $reply) {
                    $read_by = [];
                    if ($reply->read_by) {
                        $read_by = explode(",", $reply->read_by);
                    }
                    $is_read = 0;
                    foreach ($read_by as $read_id) {
                        if ((int)$read_id == $id) {
                            $is_read = 1;
                        }
                    }
                    if ($is_read == 0) {
                        $unread_count += 1;
                    }
                }
                $message->setAttribute("unread", $unread_count);
            } else {
                $message->setAttribute("unread", 0);
            }
            if ($employee) {
                $position = Job::where('id', $employee->position)->first();
                $message->setAttribute("avatar", $employee->image);
                if ($position) {
                    $message->setAttribute("position", $position->title);
                } else {
                    $message->setAttribute("position", "N/A");
                }
            } else {
                $message->setAttribute("avatar", null);
                $message->setAttribute("position", "N/A");
            }
            // $message->setAttribute("replies", $replies);
        }

        return [
            'status' => 200,
            'message' => "Employees Data Fetched Successfully",
            'messages' => $messages
        ];
    }

    public function getMyMessages($id)
    {
        $messages = Message::where('employee_id', $id)->orderBy("id", "desc")->get();

        foreach ($messages as $message) {
            $project = Project::where("id", $message->project_id)->first();
            // $replies = Reply::where('message_id', $message->id)->get();
            $message->setAttribute("task", $project);
            // $message->setAttribute("replies", $replies);
        }

        return [
            'status' => 200,
            'message' => "Employees Data Fetched Successfully",
            'messages' => $messages
        ];
    }

    public function getReplies($id, $man_id = null)
    {
        $replies = Reply::where('message_id', $id)->get();
        foreach ($replies as $reply) {
            if ($reply->read_by) {
                $read_by = explode(",", $reply->read_by);
                $is_added = 0;
                foreach ($read_by as $read) {
                    if ((int)$read == $man_id) {
                        $is_added = 1;
                    }
                }
                if ($is_added !== 0) {
                    $read_by[] = $man_id;
                }
                $reply->read_by = implode(",", $read_by);
            } else {
                $reply->read_by = $man_id;
            }
            $reply->save();
        }
        return [
            'status' => 200,
            'message' => "Fetched",
            'replies' => $replies
        ];
    }

    public function addNewReply(request $request)
    {
        $reply = new Reply();
        $reply->message_id = $request->message_id;
        $reply->text = $request->text;
        $reply->type = $request->type;

        $filename = "";
        $file = $request->file("file");
        if ($file) {
            $destinationPath = public_path('uploads/');
            $originalFile = $file->getClientOriginalName();
            $filename = strtotime(date('Y-m-d-H:isa')) . $originalFile;
            $file->move($destinationPath, $filename);
        }
        if ($filename) {
            $filename = $filename;
        }
        $reply->file = $filename;
        $reply->save();

        return [
            'status' => 200,
            'message' => "Fetched",
        ];
    }
}
