<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\UserPost;
use App\Models\User;
use App\Models\Checklist;
use App\Models\UserChecklisttransaction;
use DB;
use App\Models\ChecklistCount;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try{
            if($request->search!=''){
             $posts=Post::where('name','like', '%'.$request->search.'%')->paginate(10);
        }
        else{

            $posts=Post::orderBy('created_at','DESC')->paginate(10);
        }
            return view('posts.index',compact('posts'));
        }catch (Exception $e) {
            return \Response::json(["status" => "danger", "message" => $e->getMessage()]);
        }
    }

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

    public function postdetail($id){

        $post =Post::where('id',$id)->first();
         
         return \Response::json(['status'=>"success", 'message'=>'post show  successfully.', 'post'=>$post]);
    }

    public function poststatus(Request $request,$id)
    {
       //return $request;
       try{
            //return $id;
            //return $request;
            $client = Post::where('id',$id)->update(['status'=>$request['stat']]);
           return \Response::json(["status" => "success", "message" => "Post updated successfully!"]);
        }catch (Exception $e) {
            return \Response::json(["status" => "danger", "message" => $e->getMessage()]);
        }
    }

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

         Post::create($request->except('_token'));
         return redirect()->route('post.index');

        }catch (Exception $e) {
            return \Response::json(["status" => "danger", "message" => $e->getMessage()]);
        }
    }

    public function showuser(Request $request,$id){
        //return $id;
        $postname= Post::where('id',$id)->select('id','name')->first();
        $posts = UserPost::where('post_id',$id)->with('postdetail','userdetail')->get();

        

        $users=User::select('id','name')->get();

       $checklists=Checklist::where('post_id',$id)->with('checklistdetail','postdetail','checklistcount')->orderBy('created_at','DESC')->get();

        //checkid=[];
        //foreach($checklists as $list){
           // array_push($checkid,$list->id);
        //}
        $detailid=[];
        $checklistsid=[];
        foreach($checklists as $list){

        array_push($checklistsid,$list->id);
            foreach($list->checklistdetail as $checkdetailid){
                array_push($detailid, $checkdetailid->id);
            }
        }
        //return $detailid;
        //return  $checklistsid;
        $counts= DB::table('checklist_counts')->select(DB::raw('COUNT(id) as totalcount'),'checklist_counts.id_checklist','checklist_counts.checklist_count','checklist_counts.checklist_detail_id')->whereIN('id_checklist',$checklistsid)->groupBy('id_checklist')->orderBy('created_at','Desc')->get();

        //$checkcount=ChecklistCount::whereIN('id_checklist',$checklistsid)->orderBy('created_at', 'DESC')->groupBy('id_checklist')->count();

        $totalcount =  ChecklistCount::whereIN('id_checklist',$checklistsid)->orderBy('created_at', 'DESC')->count();


        $userid=[];
        foreach($posts as $post){                  
            foreach($post->userdetail as $user){
                //return $user->id;
                //return $userv=User::where('id',$user->id)->select('id','name')->get();
                array_push($userid, $user->id);
            }
        }

        //return $userid;

        $userdetail=User::whereIN('id',$userid)->select('id','name','joining_date')->orderBy('created_at','Desc')->get();

        $userv=UserChecklisttransaction::whereIN('user_id',$userid)->get();
        // $userid;
        foreach($userv as $user){
        if(isset($user)){
        $userdata= explode('<br>', $user->checklist_item_details);
        $userdata1= implode(',', $userdata);
        $userdata2= explode(',', $userdata1);
        }

        $userdata3=[];
         foreach($userdata2 as $data){
           //return $data;
             $userdata3[]= explode('|', $data);
        }

         //return $userdata3;

         $useridvalue=[];
         $userdatevalue=[];
                                        
        foreach($userdata3 as $key=>$user){
        //$user123=$user[0];     
        array_push($useridvalue, $user[0]);
        array_push($userdatevalue, $user[3]);                                                                    
        }
        //return $useridvalue;
        $newval= DB::table('checklist_details')->select(DB::raw('count(id) as total'),'checklist_details.id','checklist_details.id_checklist')->whereIN('id',$useridvalue)->groupBy('id_checklist')->get();

        return view('posts.assignuser',compact('posts','postname','users','checklistsid','newval','userdetail','counts','totalcount','detailid','userv'));
    }
    }

    public function storeuser(Request $request){
        //return $request;
        //return count($request['user_id']);
        for($i = 0; $i< count($request['user_id']); $i++){

                $post['user_id'] = $request['user_id'][$i];
                $post['post_id'] = $request['post_id'];
                UserPost::create($post);
        }

            return redirect()->back();
    }


     public function postuser($id,$postid){
        //return $id;
        $user_id=$id;
        $username=User::where('id',$id)->select('id','name')->first();
        $postname= Post::where('id',$postid)->select('id','name')->first();
        $users=UserPost::where('user_id',$id)->where('post_id',$postid)->with('postdetail')->select('id','post_id')->get();
         //return count( $users);
         //$checklists=[];
        //foreach($users as $user){
        $checklists= Checklist::where('post_id',$postid)->with('checklistdetail','postdetail','checklistcount')->orderBy('created_at','DESC')->paginate(10);
        //}
       $checklistsid=[];
       foreach($checklists as $list){
        array_push($checklistsid,$list->id);
        }
        //return  $checklistsid;
        $user=UserChecklisttransaction::where('user_id',$user_id)->first();
        if(isset($user)){
        $userdata= explode('<br>', $user->checklist_item_details);
        $userdata1= implode(',', $userdata);
        $userdata2= explode(',', $userdata1);

        $userdata3=[];
         foreach( $userdata2 as $data){
           // return $data;
             $userdata3[]= explode('|', $data);
         }

         //return $userdata3;

         $useridvalue=[];
         $userdatevalue=[];
                                        
        foreach($userdata3 as $key=>$user){
        //$user123=$user[0];     
        array_push($useridvalue, $user[0]);
        array_push($userdatevalue, $user[3]);                                                                    
        }

        $newval= DB::table('checklist_details')->select(DB::raw('count(id) as total'),'checklist_details.id_checklist')->whereIN('id',$useridvalue)->groupBy('id_checklist')->get();

        return view('posts.postuser',compact('users','checklists','user_id','useridvalue','newval','postname','checklistsid','username'));
        }else{
            return view('posts.postuser',compact('users','checklists','user_id','postname','username'));
        }

    } 


    public function postsearch(Request $request){
        //return $request;
        if($request->get('query')!=''){
            $query = $request->get('query');
            //$query=ucfirst($request->query);
        $post=Post::where('name','like', '%'.$query.'%')->select('name','id')->get(); 
        }
       return response()->json($post);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        
        try{
            $post = Post::where('id',$id)->first();
            return view('posts.edit',compact('post'));
        }catch (Exception $e) {
            return \Response::json(["status" => "danger", "message" => $e->getMessage()]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        try{
            $post = Post::where('id',$id)->first();
            return view('posts.edit',compact('post'));
        }catch (Exception $e) {
            return \Response::json(["status" => "danger", "message" => $e->getMessage()]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try{
            $post = Post::where('id',$id)->update($request->except('_token','_method'));
            return redirect()->route('post.index');

        }catch (Exception $e) {
            return \Response::json(["status" => "danger", "message" => $e->getMessage()]);
        }
    }

    public function postdelete(Request $request, $id)
    {
        //return  $request;
        try{
            $post = Post::where('id',$id)->delete();
            return \Response::json(["status" => "success", "message" => "Post delete"]);
        }catch (Exception $e) {
            return \Response::json(["status" => "danger", "message" => $e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
