<?php

namespace App\Http\Controllers\Workplace;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\MenuModelPermission;
use App\Models\Projects;
use App\Models\Task;
use App\Models\TaskAttachment;
use App\Models\TaskCharges;
use App\Models\TaskEntry;
use App\Models\TaskPriority;
use App\Models\TaskStatus;
use App\Models\TaskTracking;
use App\Models\TaskType;
use App\Models\TaskGroup;
use App\Models\PipelineStage;
use App\Models\User;
use Illuminate\Http\Request;

class TasksController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:task-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id)
    {
        $taskStatus = PipelineStage::select('id','name')->get();
        $taskPriority = TaskPriority::select('id','name')->get();

        $data = Task::select(
            'id',
            'title',
            'details',
            'date',
            'project_id',
            'task_status_id',
            'task_priority_id',
            'account_id',
            'assigned_to',
            'status',
            'is_default',
        )
            ->with('getAccount')
            ->with('getProject')
            ->with('getTaskType')
            ->with('getUser')
            ->where('project_id', $id);

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

            $data = $data->when(!empty($search_query), function ($q) use ($search_query) {
                return $q->where(function ($query) use ($search_query) {
                    return $query->whereHas('getUser', 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('task_status_id', $task_status);
            })
            ->when(!empty($task_priority), function ($query) use ($task_priority) {
                return $query->where('task_priority_id', $task_priority);
            });

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

            return view('tasks.table', compact('data','taskStatus','taskPriority'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('id', 'ASC')
                ->paginate(10);
            $project = Projects::select('title')->where('id', $id)->first();
            return view('tasks.index', compact('data', 'id', 'project','taskStatus','taskPriority'));
        }
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $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();
        $module_code = MenuModelPermission::select('id', 'code')->where('status',1)->get();
        $assignTo    = User::select('id','name','email')->where('status',1)->get();
        $charge_id   = TaskCharges::select('id','name')->where('status',1)->get();

        return view('tasks.create', compact('project', 'taskType', 'account', 'module_code','assignTo','charge_id'));
    }

    /**
     * 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',
        ]);
        $data['date']      = date('Y-m-d', strtotime($request->date));
        $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;


        $default_check = Task::where(['is_default' => 1, 'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

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

        $taskTracking = TaskTracking::insert([
            'task_id'  => $data->id,
            // 'assign_to'=> $request->assignTo,
            'assign_to'=> $request->assigned_to,
        ]);
        // dd($taskTracking);

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

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Task::select([
            'tasks.id',
            'tasks.title',
            'tasks.details',
            'tasks.date',
            'tasks.status',
            'tasks.project_id',
            'tasks.task_status_id',
            'tasks.task_priority_id',
            'tasks.task_group_id',
            'tasks.task_type_id',
            'tasks.task_point',
        ])
            ->with('getProject')
            ->leftjoin('responsible_teams','responsible_teams.task_id','tasks.id')
            ->where('tasks.id', $id)
            ->when(!in_array('Admin',\Auth()->user()->roles->pluck('name')->all()), function($query) {
                // $query->where('responsible_teams.assigned_to_id', \Auth()->id());
            })
            ->first();

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

        $taskStatus      = PipelineStage::select('id','name')->get();
        $taskPriority    = TaskPriority::select('id','name')->get();

        $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();

        return view('tasks.show', compact('id', 'data','taskStatus','taskPriority','task_groups','project','taskType'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $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();;
        $module_code = MenuModelPermission::select('id', 'code')->get();
        $assignTo    = User::select('id','name')->where('status',1)->get();
        $charge_id   = TaskCharges::select('id','name')->where('status',1)->get();
        $data        = Task::find($id);

        return view('tasks.edit', compact('project', 'taskType', 'account', 'module_code', 'data','assignTo','charge_id'));
    }

    /**
     * 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']      = date('Y-m-d', strtotime($request->date));

        $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.index')
            ->with('success', 'Tasks updated successfully');
    }

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

        Task::find($request->id)->delete();

        $Redirect = 'budget-types';

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


    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status);
            $Update = Task::where('id', '=', $request->id)->update($data);

            $Redirect = 'tasks';

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Task status successfully change'],
                    'data'    => [
                        'redirect' => $Redirect,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data'    => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function isDefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status);
            $count  = Task::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default speecial case!'],
                    'data'    => []
                ]);
            } else {
                $Update = Task::where('id', '=', $request->id)->update($data);

                if ($Update) {
                    return response()->json([
                        'success' => true,
                        'message' => ['Task default status successfully changed.'],
                        'data' => []
                    ]);
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => ['Error for change default'],
                        'data' => [
                            'redirect' => '',
                        ]
                    ]);
                }
            }
        }
    }

    public function taskAttachment(Request $request, $id)
    {
        $taskAttachment = TaskAttachment::where('task_id', $id)->get();

        return view('task-attachments.table', compact('taskAttachment'));
    }

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

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

    //     $data->update(['task_status_id' => $request->input('task_status_id')]);


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

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

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

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

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

        $task->taskTracking()->update(['task_status_id' => $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');
    }
    public function storeTaskPriority(Request $request, $id)
    {
        $task = Task::find($id);

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

        $task->update(['task_priority_id' => $request->input('status_id')]);

        $task->taskTracking()->update(['task_priority_id' => $request->input('status_id')]);

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

        return redirect()->route('task.index')->with('success', 'Task updated successfully');
    }
    public function storeTaskProject(Request $request, $id)
    {
        $task = Task::find($id);

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

        $task->update(['project_id' => $request->input('status_id')]);

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

        return redirect()->route('task.index')->with('success', 'Task updated successfully');
    }
    public function storeTaskGroup(Request $request, $id)
    {
        $task = Task::find($id);

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

        $task->update(['task_group_id' => $request->input('status_id')]);

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

        return redirect()->route('task.index')->with('success', 'Task updated successfully');
    }
    public function storeTaskType(Request $request, $id)
    {
        $task = Task::find($id);

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

        $task->update(['task_type_id' => $request->input('status_id')]);

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

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


    public function taskEntry(Request $request, $id)
    {
        $taskEntry = TaskEntry::with('getAssignTo')->where('task_id', $id)->get();

        return view('task-entries.table', compact('taskEntry'));
    }

    public function taskTracking(Request $request, $id)
    {
        $taskTracking = TaskTracking::with('getAssignTo')
        ->with('getTaskStatus')
        ->with('getTaskPriority')
        ->with('getTasks')
        ->where('task_id', $id)
        ->get();

        return view('task-trackings.table', compact('taskTracking'));
    }
    public function searchAccounts(Request $request)
    {
        $searchTerm = $request->search_text;
        $results = Account::where('name', 'LIKE', '%' . $searchTerm . '%')
        ->get();
        // dd($results);
        return response()->json(['result' => $results, 'status' => true]);
    }

}
