<?php

namespace App\Http\Controllers\TaskManager;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TaskTeam;
use App\Models\Task;
use App\Models\Account;

class TaskTeamsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $task_teams = TaskTeam::leftJoin('tasks' , 'task_teams.task_id' , '=' , 'tasks.id')
        ->leftJoin('accounts' , 'task_teams.user_id' , '=' , 'accounts.id')
        ->select(
            'task_teams.id as id',
            'task_teams.task_id as task_id',
            'accounts.name',
            'task_teams.role as role' ,
            'task_teams.responsibility as responsibility' ,
            'task_teams.task_accepted_status as task_accepted_status' ,
            'task_teams.reject_reason as reject_reason' ,
            'tasks.title as task_title' ,
        )->orderBy('tasks.title', 'ASC');

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

            $task_teams = $task_teams->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('task_teams.task_id', 'like', '%'.$search_query.'%')
                            ->orWhere('task_teams.role', 'like', '%'.$search_query.'%')
                            ->orWhere('task_teams.responsibility', 'like', '%'.$search_query.'%')
                            ->orWhere('task_teams.reject_reason', 'like', '%'.$search_query.'%');
            })->paginate($sort_by);

            return view('task-manager.task-teams.table', compact('task_teams'));
        } else {
            $task_teams = $task_teams->paginate(10);

            return view('task-manager.task-teams.index', compact('task_teams'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * 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_teams = TaskTeam::findOrFail($id);
        $tasks = Task::all();

        return view('accounts.edit-task-teams', compact('task_teams' , 'tasks'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $task_teams = TaskTeam::findOrFail($id);
        $task_teams->delete();

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

    public function createTaskTeam()
    {
        $task_teams = TaskTeam::select(
            'task_teams.id as task_teams_id',
            'task_teams.task_id as task_id',
            'task_teams.user_id as user_id',
            'task_teams.role as role' ,
            'task_teams.responsibility as responsibility' ,
            'task_teams.task_accepted_status as task_accepted_status' ,
            'task_teams.reject_reason as reject_reason' ,
        )->get();

        $tasks = Task::all();
        $accounts = Account::select('name')->get();

        return view('accounts.create-task-teams', compact('task_teams', 'tasks' , 'accounts'));
    }

    public function storeTaskTeam(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'task_id'        => 'required',
            'user_id'        => 'required',
            'role'           => 'required',
            'responsibility' => 'required',
        ]);

        if ($validator->fails()) {

            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                'redirect' => 'task-teams.index'],
            ]);
        }

        $task_teams = TaskTeam::create([
            'task_id'        => $request->task_id,
            'user_id'        => $request->user_id,
            'role'           => $request->role,
            'responsibility' => $request->responsibility,
        ]);

        return response()->json([
            'success'  => true,
            'message'  => 'Task Teams Created successfully',
            'data'     => [
            'redirect' => 'task-teams.index', 
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = ['task_accepted_status' => $request->status];
            $update = TaskTeam::where('id', $request->id)->update($data);

            if ($update) {
                return response()->json([
                    'success' => true,
                    'message' => 'Task Accepted Status successfully changed',
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Error changing status',
                    'data' => []
                ]);
            }
        }
    }

    public function createRejectReason($id){

        $task_teams = TaskTeam::find($id);
        return view('accounts.create-task-teams-reject-reason' , compact('task_teams'));
    }

    public function storeRejectReason(Request $request, $id)
    {
        $request->validate([
            'reject_reason' => 'required|string|max:255',
        ]);

        if ($request->ajax()) {
            $data = [
                'reject_reason'        => $request->reject_reason,
                'task_accepted_status' => 2,
            ];

            $update = TaskTeam::where('id', $id)->update($data);

            if ($update) {
                return response()->json([
                    'success' => true,
                    'message' => 'Task Reject Reason created successfully',
                    'data' => [
                        'redirect' => '',
                    ],
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'No changes were made, or record not found.',
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function updateTaskTeam(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'task_id'        => 'required',
            'user_id'        => 'required',
            'role'           => 'required',
            'responsibility' => 'required',
            'reject_reason'  => 'required',
        ]);

        if ($validator->fails()) {
           return response()->json([
                'success'  => true,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                'redirect' => 'task-teams.index'],
            ]);
        }

        $task_teams = TaskTeam::findOrFail($id);
        $task_teams->update($request->all());

        return response()->json([
            'success'  => true,
            'message'  => 'Task Teams updated successfully',
            'data'     => [
            'redirect' => 'task-teams.index', 
            ]
        ]);
    }



}