<?php

namespace App\Http\Controllers\TaskManager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Task;
use App\Models\Projects;
use App\Models\TaskPriority;
use App\Models\TaskType;
use App\Models\TaskGroup;
use App\Models\Account;
use App\Models\User;
use App\Models\PipelineStage;

class TasksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $taskStatus   = PipelineStage::select('id','name')->get();
        $taskPriority = TaskPriority::select('id','name')->get();
        $tastTeam     = User::select('id','name')->where('is_super_admin', 0)->get();

        $data = Task::select(
            'tasks.id as id',
            'tasks.title',
            'tasks.details',
            'tasks.date',
            'tasks.project_id',
            'tasks.task_status_id',
            'tasks.task_priority_id',
            'tasks.account_id',
            'tasks.status',
            'tasks.deadline',
            'tasks.amount',
            'users.name as member_name',
            'created_by.name as created_by',
            'task_groups.name as task_group',
            'task_types.title as task_type',
            'projects.title as project',
        )
            ->with('getAccount')
            ->with('getProject')
            ->with('getTaskType')
            ->leftjoin('responsible_teams as task_teams', function($join) {
                $join->on('task_teams.task_id','tasks.id')
                    ->where('task_teams.is_main' , '1');
            })
            ->leftjoin('projects','projects.id', '=', 'tasks.project_id')
            ->leftjoin('task_types','task_types.id', '=', 'tasks.task_type_id')
            ->leftjoin('task_groups','task_groups.id', '=', 'tasks.task_group_id')
            ->leftjoin('users','users.id', '=', 'task_teams.assigned_to_id')
            ->leftjoin('users as created_by','created_by.id', '=', 'tasks.created_by')->orderBy('tasks.created_at', 'desc');

            // echo "<pre>";
            // print_r($data);
            // echo "</pre>";
            // die();

            $sort_by = $request->get('sortby') ?? 10;

        if ($request->ajax()) {
            $sort_type     = $request->get('sorttype');
            $search_query  = $request->get('query');
            $taskTeam      = $request->get('taskTeam');
            $task_status   = $request->get('taskStatus');
            $task_priority = $request->get('taskpriority');

            $data = $data->when(!empty($taskTeam), function ($q) use ($taskTeam) {
                return $q->leftjoin('responsible_teams','responsible_teams.task_id','tasks.id')
                ->where('responsible_teams.task_accepted_status', '1')
                ->where('responsible_teams.assigned_to_id', $taskTeam);
            })
            ->when(!empty($search_query), function ($q) use ($search_query) {
                return $q->where(function ($query) use ($search_query) {
                    return $query->whereHas('getAccount', function ($query) use ($search_query) {
                            $query->where('name', 'like', '%'.$search_query.'%');
                        })
                            ->orWhere('title', 'like', '%' . $search_query . '%');
                });
            })
            ->when(!empty($task_status), function ($query) use ($task_status) {
                return $query->where('tasks.task_status_id', $task_status);
            })
            ->when(!empty($task_priority), function ($query) use ($task_priority) {
                return $query->where('tasks.task_priority_id', $task_priority);
            });

            $data = $data->orderBy('tasks.id', 'ASC')
                ->groupBy('tasks.id')
                ->paginate($sort_by);

            return view('task-manager.tasks.table', compact('data','taskStatus','taskPriority','sort_by'));
        } else {
            if(!in_array('Admin',\Auth()->user()->roles->pluck('name')->all())){
                // $data = $data->where('task_teams.assigned_to_id', \Auth()->id());
            }

            $data = $data->groupBy('tasks.id')
                ->orderBy('tasks.id', 'ASC')
                ->paginate(10);

            $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

            return view('task-manager.tasks.index', compact('data', 'taskStatus','taskPriority','sort_by','tastTeam','companyDateFormate'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $task_groups = TaskGroup::select('id','name')->get();
        $project     = Projects::select('id', 'title')->where('status',1)->get();
        $taskType    = TaskType::select('id', 'title')->where('status',1)->get();
        $account     = Account::select('id', 'name')->where('status',1)->get();
        $stages      = PipelineStage::select('id','name')->get();

        return view('task-manager.tasks.create', compact('project', 'taskType', 'task_groups', 'account','stages'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'title' => 'required|unique:tasks,title,NULL,id,deleted_at,NULL',
            'date'  => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'date',
            'deadline',
        ]);
        $data['date']      = date('Y-m-d', strtotime($request->date));
        $data['deadline']      = !empty($request->deadline) ? date('Y-m-d', strtotime($request->deadline)) : null;

        $data['deadline'] = $request->deadline ? date('Y-m-d', strtotime($request->deadline)) : null;
        $data['completion_date'] = $request->completion_date ? date('Y-m-d', strtotime($request->completion_date)) : null;

        $data['created_by']       = \Auth()->id();
        $taskPriority             = TaskPriority::select('id')->where('code', 'NORMAL_PRIORITY')->first();
        $data['task_priority_id'] = $taskPriority->id ?? '';
        $data['chargable'] = $request->amount > 0 ? 'Yes' : 'No';

        $data = Task::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Tasks created successfully',
                'data' => $data
            ]);
        }

        return redirect()->route('task-manager-tasks.index')
            ->with('success', 'Tasks created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $task_groups = TaskGroup::select('id','name')->get();
        $stages = PipelineStage::select('id','name')->get();
        $project     = Projects::select('id', 'title')->where('status',1)->get();
        $taskType    = TaskType::select('id', 'title')->where('status',1)->get();
        $account     = Account::select('id', 'name')->where('status',1)->get();
        $data        = Task::find($id);
        $companyDateFormate = ($this->companyDateFormate());

        return view('task-manager.tasks.edit', compact('project','task_groups' , 'taskType', 'account', 'data','stages','companyDateFormate'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'title'       => 'required|unique:tasks,title,'.$id.',id,deleted_at,NULL',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'date',
        ]);

        $data['date']            = !empty($request->date) ? date('Y-m-d', strtotime($request->date)) : '';
        $data['deadline']        = !empty($request->deadline) ? date('Y-m-d', strtotime($request->deadline)) : '';
        $data['completion_date'] = !empty($request->completion_date) ? date('Y-m-d', strtotime($request->completion_date)) : '';
        $data['estimated_time']  = !empty($request->estimated_time) ? date('Y-m-d', strtotime($request->estimated_time)) : '';
        $data['actual_time']     = !empty($request->actual_time) ? date('Y-m-d', strtotime($request->actual_time)) : '';

        $data['updated_by'] = \Auth()->id();
        $data['chargable'] = $request->amount > 0 ? 'Yes' : 'No';

        $data = Task::whereId($id)->update($data);
        $data = Task::find($id);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Tasks updated successfully',
                'data' => $data
            ]);
        }
        return redirect()->route('task-manager-tasks.index')
            ->with('success', 'Tasks updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $task = Task::find($request->id);

        $task->update(['deleted_by' => \Auth()->id()]);
        $task->delete();

        return response()->json([
            'success' => true,
            'message' => 'Task Group Deleted successfully',
            'data' => [
                'redirect' => '',
            ]
        ]);
    }

    public function searchUsers(Request $request)
    {
        $searchTerm = $request->search_text;
        $results = User::where('prepared_by', 'LIKE', '%' . $searchTerm . '%')->select('prepared_by as name', 'id')
        ->get();
        // dd($results);
        return response()->json(['result' => $results, 'status' => true]);
    }

    public function searchClient(Request $request)
    {
        $searchTerm = $request->search_text;
        $results    = Account::select(['accounts.id','accounts.name'])
                    ->leftjoin('accounting_groups', 'accounting_groups.id','accounts.accounting_group_id')
                    ->where('accounts.name', 'LIKE', '%' . $searchTerm . '%')
                    ->where(function($query) {
                        $query->where('accounting_groups.code','SUNDRY_CREDITORS')
                            ->orWhere('accounting_groups.code','SUNDRY_DEBTORS');
                    })
                    ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }

    public function clientTask(Request $request, $id)
    {
        $taskStatus   = PipelineStage::select('id','name')->get();
        $taskPriority = TaskPriority::select('id','name')->get();
        $tastTeam     = User::select('id','name')->where('is_super_admin', 0)->get();

        $data = Task::select(
            'tasks.id as id',
            'tasks.title',
            'tasks.details',
            'tasks.date',
            'tasks.project_id',
            'tasks.task_status_id',
            'tasks.task_priority_id',
            'tasks.account_id',
            'tasks.status',
        )
            ->with('getAccount')
            ->with('getProject')
            ->with('getTaskType')
            ->leftjoin('responsible_teams as task_teams','task_teams.task_id','tasks.id')
            ->where('tasks.account_id',$id);

            $sort_by       = $request->get('sortby') ?? 10;
        if ($request->ajax()) {
            $sort_type     = $request->get('sorttype');
            $search_query  = $request->get('query');
            $taskTeam      = $request->get('taskTeam');
            $task_status   = $request->get('taskStatus');
            $task_priority = $request->get('taskpriority');

            $data = $data->when(!empty($taskTeam), function ($q) use ($taskTeam) {
                return $q->leftjoin('responsible_teams','responsible_teams.task_id','tasks.id')
                ->where('responsible_teams.task_accepted_status', '1')
                ->where('responsible_teams.assigned_to_id', $taskTeam);
            })
            ->when(!empty($search_query), function ($q) use ($search_query) {
                return $q->where(function ($query) use ($search_query) {
                    return $query->whereHas('getAccount', function ($query) use ($search_query) {
                            $query->where('name', 'like', '%'.$search_query.'%');
                        })
                            ->orWhere('title', 'like', '%' . $search_query . '%');
                });
            })
            ->when(!empty($task_status), function ($query) use ($task_status) {
                return $query->where('tasks.task_status_id', $task_status);
            })
            ->when(!empty($task_priority), function ($query) use ($task_priority) {
                return $query->where('tasks.task_priority_id', $task_priority);
            });

            $data = $data->orderBy('tasks.id', 'ASC')
                ->groupBy('tasks.id')
                ->paginate($sort_by);

            return view('task-manager.tasks.table', compact('data','taskStatus','taskPriority','sort_by'));
        } else {
            if(!in_array('Admin',\Auth()->user()->roles->pluck('name')->all())){
                $data = $data->where('task_teams.assigned_to_id', \Auth()->id());
            }

            $data = $data->groupBy('tasks.id')
                ->orderBy('tasks.id', 'ASC')
                ->paginate(10);

            return view('task-manager.tasks.index', compact('data', 'taskStatus','taskPriority','sort_by','id','tastTeam'));
        }
    }

    public function storeTaskStatus(Request $request, $id)
    {
        $task = Task::find($id);

        if (!$task) {
            return redirect()->back()->with('error', 'Task not found.');
        }

        $task->update(['status' => $request->input('task_status_id')]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Task Status Changed successfully',
                'data'    => $task
            ]);
        }

        return redirect()->route('task.index')->with('success', 'Task updated successfully');
    }
}
