<?php

namespace App\Http\Controllers\TaskManager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use App\Models\PipelineStage;
use App\Models\TaskGroup;


class PipelineStagesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $task_group_id   = $request->get('task_group_id') ?? '';
        $pipeline_stages = PipelineStage::leftJoin('task_groups' , 'task_groups.id' , '=' , 'pipeline_stages.task_group_id')
            ->select(
                'pipeline_stages.id as pipeline_stages_id',
                'pipeline_stages.name as name',
                'pipeline_stages.sequence as sequence',
                'pipeline_stages.status as status',
                'pipeline_stages.priority as priority',
                'pipeline_stages.task_group_id as task_group_id',
                'task_groups.name as task_group_name',
            )->orderBy('pipeline_stages.sequence', 'ASC')
            ->when(!empty($task_group_id), function ($query) use ($task_group_id) {
                return $query->where('pipeline_stages.task_group_id', 'like', '%'.$task_group_id.'%');
            });

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

            $pipeline_stages = $pipeline_stages->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('pipeline_stages.name', 'like', '%'.$search_query.'%')
                    ->orWhere('task_groups.name', 'like', '%'.$search_query.'%');
            })->paginate($sort_by);

            return view('task-manager.pipeline-stages.table', compact('pipeline_stages'));
        } else {
            $pipeline_stages = $pipeline_stages->paginate(10);
            $task_groups     = TaskGroup::select('id','name')->get();

            return view('task-manager.pipeline-stages.index', compact('pipeline_stages' ,'task_groups' ,'task_group_id'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function createPipelineStage()
    {
        $sequence   = PipelineStage::max('sequence');
        $sequence   = $sequence != '' ? $sequence : 0;

        $task_groups = TaskGroup::select('id' , 'name')->get();

        return view('accounts.create-pipeline-stages', compact('sequence' , 'task_groups'));
    } 

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storePipelineStage(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'          => 'required',
            'sequence'      => 'required',
            'task_group_id' => 'required'
        ]);

        if ($validator->fails()) {

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

        $pipeline_stages = PipelineStage::create([
            'name'          => $request->name,
            'sequence'      => $request->sequence,
            'task_group_id' => $request->task_group_id,
        ]);

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


    /**
     * 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)
    {
        $pipeline_stages = PipelineStage::findOrFail($id);

        $task_groups = TaskGroup::select('id' , 'name')->get();

        return view('accounts.edit-pipeline-stages', compact('pipeline_stages' , 'task_groups'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updatePipelineStage(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name'          => 'required',
            'sequence'      => 'required',
            'task_group_id' => 'required'
        ]);

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

        $pipeline_stages = PipelineStage::findOrFail($id);
        $pipeline_stages->update($request->all());

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

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

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

    public function searchStages(Request $request)
    {
        $pipeline_stages = PipelineStage::where('task_group_id', $request->task_group)->select('id','name')->get();

        return response()->json([
            'success' => true,
            'data' => $pipeline_stages
        ]);
    }

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

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