<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App;
use Yajra\Datatables\Datatables;
use App\Notifications\TapalNotification;

class TapalController extends Controller
{
  protected $childarray=[];
  public function __construct()
  {
      $this->middleware('auth');
  }
  //creation of tapal
  public function creation_of_tapal(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $tnam=$request->session()->get('session_tname');
    $fnam= $request->session()->get('session_fname');
    if(($tnam==="") &&($fnam==="") )
    {
      $request->session()->put('session_tname',"Tapal");
      $request->session()->put('session_fname',"File");
    }
    /*else
    {
      $gcon=\App\Gcon::orderBy('id','updated_at','desc')->first();
      $tn=$gcon->tname;
      $fn=$gcon->fname;
      $request->session()->put('session_tname',"$tn");
      $request->session()->put('session_fname',"$fn");
    }*/
    ////////////////////////////////////////////////////////
    $subjects=App\Subject::where('office_id',$office_id)->get();
    $subject_groups=App\Subject_Group::where('office_id',$office_id)->get();
    $priority=App\Priority::where('office_id',$office_id)->get();
    $id = Auth::user()->id;
    $seat=$request->session()->get('session_seat');
    //dd($currentseat);
    $permission=0;
    $permissionobj=\App\Permission::where('permission','Creation of Tapal')->first();
    //$seatid_new = $us_arrlist->seat_id;
    //$seatname= $us_arrlist->seat_name;
    $roles=\App\Seat_Role::where('seat_id',$seat)->get();
    foreach ($roles as $role)
    {
      $role_id=$role->role_id;
      //check if there is permission for this role
      $permissioncount=\App\Role_Permission::where('role_id',$role_id)->where('permission_id',$permissionobj->id)->count();
      if($permissioncount)
        $permission=1;
    }
    $permissioncount =\App\Seat_Permission::where('seat_id',$seat)->where('permission_id',$permissionobj->id)->count();
    if($permissioncount)
    {
      $permission=1;
    }
    if(!$permission)
      // return view('permissiondenied', compact('permission','seat'));
    $yr="";
    //get tapal number
    $yr=date("Y");
    //dd($yr);
    $tapalsearch='%'.$yr;
    $tapalobj=\App\Tapal::select('tapal_no')->where("tapal_no",'like',$tapalsearch)->orderBy('id','desc')->first();
    if($tapalobj)
    {
        $lasttapalno=$tapalobj->tapal_no;
        $tapalarr=explode("/",$lasttapalno);
        $lasttapalint=$tapalarr[1];
        $tapalno=$lasttapalint+1;
    }
    else
        $tapalno=1;
    $tapalprint="TPL/".$tapalno."/".$yr;
    return view('creation_of_tapal', compact('seat','subjects','subject_groups','tapalprint','priority'));
  }
  public function permissiondenied()
  {
      return view('permissiondenied', compact('permission','seat'));
  }
  public function tapal_view($id,Request $request)
  {   
      $office_id=$request->session()->get('session_office');
      $tapal_id= $id;
      $creation_of_tapal=\App\Tapal::where('id',$id)->first();
      $priority=App\Priority::where('id',$creation_of_tapal->priority)->first();
      $priorityfile=App\Priority::all();
      //dd($creation_of_tapal);
      $subject_group =\App\Subject_Group::where('id',$creation_of_tapal->subject_group_id)->first();
      $subject =\App\Subject::where('id',$creation_of_tapal->subject_id)->first();
      $office=\App\Office::all();
      $department=\App\Department::all();
      $section =\App\Section::all();
      $seats =\App\Seat::all();
      $actions =\App\Action::all();
      $file_groups =\App\File_Group::all();
      $username = Auth::user()->name;
      $tapalattachedtofile_arr = \App\File_reference::where('tapal_id', $tapal_id)->with('file')->first();
      $values = \App\Comments::where('tapal_id',$tapal_id)->with('seat')->orderBy('created_at','desc')->get();
      //$tapal_action =\App\Tapal_action::all();
      $attachmentcount =\App\Documents::where('tapal_id',$tapal_id)->count();
      $attachments=\App\Documents::where('tapal_id',$tapal_id)->with('user')->get();
      $userseatattachment="";
      foreach ($attachments as $userattach) 
      {
       // $updateuser=$userattach->updated_by;
        $userattach_id=$userattach->user->id;
        $userseatattachment =\App\User_Seat::where('user_id',$userattach_id)->with('seat')->first();
      }
      $values1 = \App\Tapal_action::where('tapal_id',$tapal_id)->with('seat','action')->orderBy('created_at','desc')->get();
      $userid = Auth::user()->id;      
      $seatid=$request->session()->get('session_seat');
      $seatid_new=$seatid;
      $readflag="-1";
      $fromseat = \App\Tapal_forward::where('from_seat', $seatid)->where('tapal_id',$tapal_id)->get();
      foreach ($fromseat as $togetseat) 
      {
        $toseat=$togetseat->to_seat;
        //dd($toseat);
        $readflag=$togetseat->read_flag;
        //dd($flagread);
      }
      $seatobj=\App\Seat::where('id',$seatid)->first();
      $seatname= $seatobj->seat_name;
      $act_flg_status = 0;
      $match=[['to_seat',$seatid],['tapal_id',$id]];
      //print_r($match);
      $current_tapaluser=\App\Tapal_forward::where($match)->get();
      foreach($current_tapaluser as $tapvallist)
      {
        $active_flag = $tapvallist->active_flag;
        if($active_flag == 1)
        {
          $act_flg_status = 1;
        }
      }
      $tapalstatus = \App\Tapal::where('id',$tapal_id)->where('status',2)->count();
      if($tapalstatus>0)
      {
        // return view('duplicatetapal', compact('tapalstatus'));
        return view('tapaldenied');
      }
      else
      {
        ////////get the owner seatname 
        $tapalseat = \App\Tapal_forward::where('tapal_id',$tapal_id)->where('active_flag',1)->first();
        //dd($tapalseat);
        $tapaltoseat=$tapalseat->to_seat;
        $currentseatoftapalobj=\App\Seat::where('id',$tapaltoseat)->first();
        $currentseatotapal=$currentseatoftapalobj->seat_name;
        //get username of current tapal owner
        $userseatobj=\App\User_Seat::where('seat_id',$tapaltoseat)->with('user')->first();
        if(isset($userseatobj->user))
          $currentuseroftapal=$userseatobj->user->name;
        else
          $currentuseroftapal="No user assigned to this seat";
      }
      //get child seats of $seatid
      $charray=$this->getchildseats1($seatid);
      $enablecapture="";
      if(in_array($tapaltoseat, $charray))
      {
        $enablecapture=1;
      }
      else
      {
        $enablecapture=0;
      }
      //////////////
      $tapalconfflag=0;
      $newflag="";
      //echo "$tapaltoseat....$seatid_new";
      if($tapaltoseat!=$seatid_new)
      {
        //check if loggedin user is in fileforward fromseat for this fileid
        $tapalckecking = \App\Tapal_forward::where('tapal_id',$tapal_id)->where('from_seat',$seatid_new)->count();
        if($tapalckecking==0)
        {
          $tapalconf = \App\Tapal::where('id',$tapal_id)->where('confidential',1)->count();
          if($tapalconf>0)         
            $tapalconfflag=1;
        }
      }
      if($tapalconfflag==1)
        return view('tapaldenied', compact('tapalconfflag','tapaltoseat','seatid_new'));
      //if the loggedin user doesnt comes in the history of tapal
      $tapalcondition = \App\Tapal_forward::where('tapal_id',$tapal_id)->where('to_seat',$seatid_new)->count();
      if($tapalcondition==0)
      {
        $tapalconfflag=1;
      }
      $charray=$this->getchildseats1($seatid_new);
      if(in_array($tapaltoseat, $charray)||($tapalconfflag==0))
      {
        $newflag=1;
      }
      else
      {
        $newflag=0;
      }
      if($tapaltoseat==$seatid_new)
      {
        $newflag=1;
      }
      if($newflag==0)
        return view('tapaldenied', compact('newflag','tapaltoseat','seatid_new'));
      ////////////////get atleast one count of current user/////////////////////////////////////// 
      //$tapal_comment_count = \App\Comments::where('tapal_id',$tapal_id)->where('seat_id','=',$seatid_new)->count();
      $user_comment_flag='';
      $tapal_comment_last = \App\Comments::where('tapal_id',$tapal_id)->orderBy('created_at','DESC')->first();
      if(isset($tapal_comment_last)!='')
      {
          $userid_last_tapalcomment = $tapal_comment_last->updated_by;
          if($userid_last_tapalcomment == $userid)
          {
              $user_comment_flag = 1;
          }
      }
      else
      {
          $user_comment_flag=0;
      }
      ///////////////////////////////////////////////////////////////////////////////////////////////
      $tapal_forward = \App\Tapal_forward::where('to_seat', $seatid)
          ->where('tapal_id', $tapal_id)->where('read_flag',0)
          ->update(['read_flag' => 1]);
      $yr=date("Y");
      $filesearch='%'.$yr;
      $fileobj=\App\File::select('file_no')->where("file_no",'like',$filesearch)->orderBy('id','desc')->first();
      if($fileobj)
      {
          $lastfileno=$fileobj->file_no;

          $filearr=explode("/",$lastfileno);
          $lastfileint=$filearr[1];
          $fileno=$lastfileint+1;
      }
      else
          $fileno=1;
      $fileprint="FILE/".$fileno."/".$yr;
      //$new_tapaluser=\App\Tapal_forward::where('from_seat',$seatid)->get();
      return view('tapal_view', compact('values','values1','seatid_new','username','subject_group','subject','creation_of_tapal','department','section','seats','act_flg_status','actions','values1','file_groups','fileprint','seatname','attachmentcount', 'attachments','tapal_id','tapal_forward','priority','priorityfile','userseatattachment','tapalattachedtofile_arr','user_comment_flag','fromseat','readflag','office','currentseatotapal','currentuseroftapal','enablecapture','tapaltoseat','tapalconfflag','userseatobj'));
  }
  public function tapaldenied()
  {
    return view('tapaldenied', compact('tapalconfflag','tapaltoseat','seatid_new','newflag'));
  }
  public function duplicatetapal()
  {
      return view('duplicatetapal', compact('tapalstatus'));
  }
  /////////////to get the files in hand for auto complete/////////////////////////
  public function autocomplete_fileinhand(Request $request)
  {
    $term=$request->term;
    $data = \App\File::where('file_no','LIKE','%'.$term.'%')->take(10)->get();
    $result=array();
    foreach ($data as $key => $v)
    {
        $result[]=['value' =>$value->item];
    }
    return response()->json($results);
  }
  //modal file create
  public function file_createpost(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $this->validate($request,[
        'fileno' => 'required',//name of blade name
        'title' => 'required',
        'filedescription' => 'required',
        'referencenumber' => 'required',
        'priority' => 'required',
        'file_group' => 'required'
      ]);
    $id = Auth::user()->id;
    $priorityfile=App\Priority::all();
    $yr=date("Y");
    $filesearch='%'.$yr;
    $fileobj=\App\File::select('file_no')->where("file_no",'like',$filesearch)->orderBy('id','desc')->first();
    //dd($fileobj);
    if($fileobj)
    {
        $lastfileno=$fileobj->file_no;
        $filearr=explode("/",$lastfileno);
        $lastfileint=$filearr[1];
        $fileno=$lastfileint+1;
    }
    else
        $fileno=1;
    $fileprint="FILE/".$fileno."/".$yr;
    $title=$request->title;
    $description=$request->filedescription;
    $referencenum=$request->referencenumber;
    $priority=$request->priority;
    $confidential=$request->confidential;
    $file_group=$request->file_group;
    $tapalid=$request->tapalid;
    //////check max number of files exceeds or not///////////////////////////
    $slugname=$request->session()->get('slugname');
    $frequency=$request->session()->get('frequency');
    $stripe_status=$request->session()->get('stripe_status');
    if($stripe_status=="active")
    {
      if($frequency=="year")
      {
          $payment_interval_val = "annual";
      }
      if($frequency=="month")
      {
          $payment_interval_val = "monthly";
      }
      if($plan_name)
      {
        $prd_det = App\PaymentLink::where('slugname','=', $plan_name)->where('frequency',$payment_interval_val)->first();  
        if(isset($prd_det))
        {
            $max_num_files = $prd_det->no_of_files;
        }
      }
      $file_count = App\File::where('office_id',$office_id)->count();
      $next_file_count = $file_count+1;
      ////////////////////////////////////////////////////////////////////////////
      if($next_file_count<=$max_num_files)
      {
        $id = Auth::user()->id;
        $insert_id = \App\File::create([//model name database field name
          'file_no' => $fileprint,
          'title' => $title,
          'file_description' => $description,
          'reference_number' => $referencenum,
          'priority' => $priority,
          'confidential' => $confidential,
          'file_group_id' => $file_group,
          'created_by' =>$id,
          'updated_by'=>$id,
          'office_id' => $office_id,
          'status' => 0,
           ]);
        if($insert_id)
        {
          $id = Auth::user()->id;
          $creation_of_files =\App\File::where('id',$id)->first();
          //File Forward entry
          //get seat_id of current user
          $seat=\App\User_Seat::where('user_id',$id)->first();
          $seatid=$seat->seat_id;
          //$creation_of_tapal=\App\Tapal::where('id',$id)->first(); 
          $file_forward_id = \App\File_forward::create([//model name database field name
            'file_id' => $insert_id->id,
            'from_seat' => 0,
            'to_seat' => $seatid,
            'updated_by' =>$id,
            'active_flag' => 1,
            'read_flag' => 1
             ]);
          $file_reference = \App\File_reference::create([//model name database field name
            'tapal_id' => $tapalid,
            'file_id' => $insert_id->id,
            'created_by' =>$id
             ]);
          $status = \App\Tapal::where('id', $tapalid)->update(['status' => 1]);
          // $sendmessage="File Added!";
          notify()->success('File Added!');
          return redirect('fileinbox/');
        }
        else
          smilify('Error', 'Error Occurred Pls recheck!');      
      }
      else
      {
          smilify('Error', 'Maximum Number of Tapals Exceeds for this Organization.'); 
      }
    }
    else
    {
      smilify('Error', 'Your Subscription is not active. Please contact Administrator'); 
    }
    return redirect()->back();
  }
  //existing file
  public function file_existpost(Request $request)
  {
    $this->validate($request,[
          'filegroup' => 'required',
          'fileinhand' =>  'required'
        ]);
    $fileid=$request->creation_of_file_id;
    $name = Auth::user()->name;
    $filegroup=$request->filegroup;
    $file=$request->fileinhand;
    $tapalid=$request->tapal_id;
    $id = Auth::user()->id;
    if($file)
    {
      $file_number=\App\File::select('file_no')->where("id",$file)->first();
      $tapal_number=\App\Tapal::select('tapal_no')->where("id",$tapalid)->first();
      $file_reference = \App\File_reference::create([//model name database field name
          'tapal_id' => $tapalid,
          'file_id' => $file,
          'created_by' =>$id
        ]);
      $status = \App\Tapal::where('id', $tapalid)->update(['status' => 1]);
      notify()->success($tapal_number." Attached to ".$file_number." successfully  !");
      //$sendmessage=$tapal_number." Attached to ".$file_number." successfully  !";
      return redirect('fileinbox/');
    }
    else
    {
      smilify('Error', 'Error Occurred Pls recheck!');
      return redirect()->back();
    }
  }
  //comment
  public function tapal_viewpost(Request $request)
  {
    $this->validate($request,[
        'comment_type' => 'required',
        'description' => 'required'
        ]);
    $userid = Auth::user()->id; 
    $seatid_new = $request->session()->get('session_seat');
    $seatnameobj=\App\Seat::where('id',$seatid_new)->first();
    $seatname=$seatnameobj->seat_name;
    $comment_type=$request->comment_type;
    $description=$request->description;
    $tapal_id=$request->creation_of_tapalcomment;
    if(strcmp($comment_type, 'Public') == 0) {
      $comment_type=0;
    }
    else if(strcmp($comment_type, 'Private') == 0) {
      $comment_type=1;
    }
    else if(strcmp($comment_type, 'Yellow Notes') == 0) {
      $comment_type=2;
    }
    $id = Auth::user()->id;
    $commentarr =[];
    $commentcount = \App\Comments::where('tapal_id',$tapal_id)->where('seat_id',$seatid_new)->where('comment_type',$comment_type)->where('comment_description',$description)->count();
    if($commentcount==0)
    {
      $insert_id = \App\Comments::create([//model name database field name
        'comment_type' => $comment_type,
        'comment_description' => $description,
        'tapal_id' => $tapal_id,
        'seat_id' => $seatid_new,
        'updated_by'=>$id
        ]);
      $created_at=$insert_id->created_at->format('d-M-Y');
      $seat = "";
      //echo "tapal_id=$tapal_id...<br>";
      $checkforseatmatch=\App\User_Seat::where('user_id',$id)->where('seat_id',$seatid_new)->count();
      $currenttapalseat=\App\Tapal_forward::where('tapal_id',$tapal_id)->where('active_flag',1)->first();
      //dd($currenttapalseat);
      if(isset($currenttapalseat))
      {
        $seat=$currenttapalseat->to_seat;
      }
      $tapalarr =[];
      $seatflag=0;
      if($seatid_new==$seat)
      {
         $seatflag=1;
      }
      $commentstr ='';
      if($insert_id)
      {
          $sendmessage=1;
          $comments_list=\App\Comments::where('tapal_id',$tapal_id)->where('seat_id',$seatid_new)->orderBy('id','desc')->first();
          if(($comment_type==1)&&($checkforseatmatch>0)) 
          {    
            //<img class='img-circle img-sm' src='../public/img/boxed-bg.jpg' alt='User Image'>
            $commentstr .= "<div class='box-comment'><input type='hidden' name='creation_of_tapal' id='creation_of_tapal' value='$id'><div class='comment-text'><span class='username'>$seatname posted Private Comment <span class='text-muted pull-right'>$created_at</span></span><font color='red'>$description</font></div></div>";
          }
          if($comment_type==0) 
          {
            //<img class='img-circle img-sm' src='../public/img/boxed-bg.jpg' alt='User Image'>
            $commentstr .= "<div class='box-comment'><input type='hidden' name='creation_of_tapal' id='creation_of_tapal' value='$id'><div class='comment-text'><span class='username'>$seatname posted Public Comment <span class='text-muted pull-right'>$created_at</span></span><font color='green'>$description</font></div></div>";
          }
          if(($comment_type==2)  && ($comments_list->disgard_flag==0))
          {
            //<img class='img-circle img-sm' src='../public/img/boxed-bg.jpg' alt='User Image'>
            $commentstr .= "<div class='box-comment'><form class=form-horizontal action='".url('postit_comment')."'  method='post' > 
            <input type='hidden' name='_token' value=".csrf_token()."><input type='hidden' name='tapal' id='tapal' value='$id'>
            <input type='hidden' name='comment_id' id='comment_id' value='$comments_list->id'>
            <div class='comment-text'><span class='username'>$seatname posted Yellow Note <span class='text-muted pull-right'>$created_at</span>
            </span><font color='#ad890a'>$description</font></div>";
            if($seatflag==1)
            {
              $commentstr .= "<button type='submit' class='btn btn-default btn-xm'> <span class='glyphicon glyphicon-trash'></span> Trash </button></form></div> "; 
            }
          }
      }
      else
      {
        $sendmessage=0;
      } 
      $commentarr['comment']=$commentstr;
    }
    return $commentarr;
  }
  public function tapalcapture_viewpost(Request $request)
  {
    $this->validate($request,[     
            'comment_type' => 'required',
            'description' => 'required'
       ]);
    $userid = Auth::user()->id;   
    $seatid_new = $request->session()->get('session_seat');
    $seatnameobj=\App\Seat::where('id',$seatid_new)->first();
    $seatname=$seatnameobj->seat_name;
    $comment_type=$request->comment_type;
    $description=$request->description;
    $tapal_id=$request->creation_of_tapalcomment;
    if(strcmp($comment_type, 'Public') == 0) {
      $comment_type=0;
    }
    else if(strcmp($comment_type, 'Private') == 0) {
      $comment_type=1;
    }
    else if(strcmp($comment_type, 'Yellow Notes') == 0) {
      $comment_type=2;
    }
    $id = Auth::user()->id;
    $insert_id = \App\Comments::create([//model name database field name
      'comment_type' => $comment_type,
      'comment_description' => $description,
      'tapal_id' => $tapal_id,
      'seat_id' => $seatid_new,
      'updated_by'=>$id
       ]);
    $created_at=$insert_id->created_at->format('d-M-Y');
    $seat = "";
    //echo "tapal_id=$tapal_id...<br>";
    $checkforseatmatch=\App\User_Seat::where('user_id',$id)->where('seat_id',$seatid_new)->count();
    $currenttapalseat=\App\Tapal_forward::where('tapal_id',$tapal_id)->where('active_flag',1)->first();
    //dd($currenttapalseat);
    if(isset($currenttapalseat))
    {
      $seat=$currenttapalseat->to_seat;
    }
    $tapalarr =[];
    $seatflag=0;
    if($seatid_new==$seat)
    {
       $seatflag=1;
    }
    $commentstr ='';
    if($insert_id)
    {
      $sendmessage=1;
      $comments_list=\App\Comments::where('tapal_id',$tapal_id)->where('seat_id',$seatid_new)->orderBy('id','desc')->first();
      if(($comment_type==1)&&($checkforseatmatch>0)) 
      {    
        //<img class='img-circle img-sm' src='./public/img/user3-128x128.jpg' alt='User Image'>
        $commentstr .= "<div class='box-comment'><input type='hidden' name='creation_of_tapal' id='creation_of_tapal' value='$id'><div class='comment-text'><span class='username'>$seatname<span class='text-muted pull-right'>$created_at</span></span><font color='red'>$description</font></div></div>";
      }
      if($comment_type==0) 
      {
        //<img class='img-circle img-sm' src='./public/img/user3-128x128.jpg' alt='User Image'>
        $commentstr .= "<div class='box-comment'><input type='hidden' name='creation_of_tapal' id='creation_of_tapal' value='$id'><div class='comment-text'><span class='username'>$seatname<span class='text-muted pull-right'>$created_at</span></span><font color='green'>$description</font></div></div>";
      }
      if(($comment_type==2)  && ($comments_list->disgard_flag==0))
      {
        //<img class='img-circle img-sm' src='./public/img/user3-128x128.jpg' alt='User Image'>
        $commentstr .= "<div class='box-comment'><form class=form-horizontal action='".url('postit_comment')."'  method='post' > 
        <input type='hidden' name='_token' value=".csrf_token()."><input type='hidden' name='tapal' id='tapal' value='$id'>
        <input type='hidden' name='comment_id' id='comment_id' value='$comments_list->id'>
        <div class='comment-text'><span class='username'>$seatname<span class='text-muted pull-right'>$created_at</span>
        </span><font color='#ad890a'>$description</font></div>";
        if($seatflag==1)
        {
          $commentstr .= "<button type='submit' class='btn btn-default btn-xm'> <span class='glyphicon glyphicon-trash'></span> Trash </button></form></div> "; 
        }
      }
    }
    else
    {
      $sendmessage=0;
    }
    $commentarr['comment']=$commentstr;
    return redirect()->back();
  }
  public function tapal_viewcommentpost(Request $request)
  {
    $this->validate($request,[         
            'comment_type' => 'required',
            'description1' => 'required'
       ]);
    $userid = Auth::user()->id;
    $seatid_new = $request->session()->get('session_seat');
    $comment_type=$request->comment_type;
    $description=$request->description1;
    //$tapal_id=$request->creation_of_comment;
    $tapal_id=$request->creation_of_tapalcomment;
    $id = Auth::user()->id;
    $insert_id = \App\Comments::create([//model name database field name
      'comment_type' => $comment_type,
      'comment_description' => $description,
      'tapal_id' => $tapal_id,
      'seat_id' => $seatid_new,
      'updated_by'=>$id
       ]);
    if($insert_id)
      notify()->success('Comment Added!');
    else
      smilify('Error', 'Error Occurred Pls recheck!');
    return redirect()->back();
  }
  //tapal_actions
  public function tapal_actionpost(Request $request)
  {
    //dd($request);
    $office_id=$request->session()->get('session_office');
    $this->validate($request,[       
            'action_type' => 'required',
            'actdescription' => 'required'  
       ]);
    $userid = Auth::user()->id;
    $seatid_new = $request->session()->get('session_seat');
    $seatnameobj=\App\Seat::where('id',$seatid_new)->first();
    $seatname=$seatnameobj->seat_name;
    $action_type=$request->action_type;
    $action_description=$request->actdescription;
    //dd($action_description);
    $tapal_id=$request->creation_of_action;
    $actions_list = \App\Action::where('office_id',$office_id)->where('actions',$action_type)->first();
    if(isset($actions_list))
    {
      $actions = $actions_list->id;
    }
    $id = Auth::user()->id;
    $insert_id = \App\Tapal_action::create([//model name database field name
      'action_type' => $actions,
      'action_description' => $action_description,
      'tapal_id' => $tapal_id,
      'seat_id' => $seatid_new,
      'created_by'=>$id
       ]);
    if($action_type=="Close")
    {
        $closeddate = date("Y-m-d");
        $updateobj = \App\Tapal::where('id',$tapal_id)->first();
        $updateobj->status =1;
        $updateobj->closed_by = $id;
        $updateobj->closed_date = $closeddate;
        $updateobj->save();
    }
    $created_at=$insert_id->created_at->format('d-M-Y');
    $actionstr ='';
    if($insert_id)
    {
      $sendmessage=1;
      if($actions) 
        {    
          //<img class='img-circle img-sm' src='./public/img/user3-128x128.jpg' alt='User Image'>
          $actionstr .= "<div class='box-comment'><div class='comment-text'><span class='username'>$seatname put action on $action_type <span class='text-muted pull-right'>$created_at</span></span>$action_description</div></div>";
        }
    }
    else
    {
        $sendmessage=0;
    }
    $actionarr['action']=$actionstr;
    //return $sendmessage;
    return $actionarr;
  }
  public function tapalcapture_actionpost(Request $request)
  {
    $this->validate($request,[    
            'action_type' => 'required',
            'actdescription' => 'required'  
       ]);
    $userid = Auth::user()->id;
    $seatid_new = $request->session()->get('session_seat');
    $seatnameobj=\App\Seat::where('id',$seatid_new)->first();
    $seatname=$seatnameobj->seat_name;
    $actions=$request->action_type;
    // dd($actions);
    $action_description=$request->actdescription;
    $tapal_id=$request->creation_of_action;
    //$tapalid=$request->creation_of_tapalaction;
    //$tapal_id=$tapalid;
    if(strcmp($actions, 'Clarification required') == 0) {
      $actions=9;
    }
    else if(strcmp($actions, 'Non Pertaining') == 0) {
      $actions=10;
    }
    else if(strcmp($actions, 'Close') == 0) {
      $actions=11;
    }
    else if(strcmp($actions, 'Testing') == 0) {
      $actions=12;
    }
    $id = Auth::user()->id;
    $insert_id = \App\Tapal_action::create([//model name database field name
      'action_type' => $actions,
      'action_description' => $action_description,
      'tapal_id' => $tapal_id,
      'seat_id' => $seatid_new,
      'created_by'=>$id
       ]);
    $created_at=$insert_id->created_at->format('d-M-Y');
    if($insert_id)
      notify()->success('Action Added!');
    else
      smilify('Error', 'Error Occurred Pls recheck!');
    return redirect()->back();
  }
  public function tapal_action(Request $request)
  {
     $this->validate($request,[      
            'actions' => 'required',
            'actdescription1' => 'required' 
       ]);
      $userid = Auth::user()->id;
      $seatid_new = $request->session()->get('session_seat');
      $actions=$request->actions;
      $action_description=$request->actdescription1;
      //$tapal_id=$request->creation_of_action;
      $tapal_id=$request->creation_of_tapalaction;
      //$tapal_id=$tapalid;
      $id = Auth::user()->id;
      $insert_id = \App\Tapal_action::create([//model name database field name
        'action_type' => $actions,
        'action_description' => $action_description,
        'tapal_id' => $tapal_id,
        'seat_id' => $seatid_new,
        'created_by'=>$id
         ]);
      if($action_type=="Close")
      {
          $updateobj = \App\Tapal::where('id',$tapal_id)->first();
          $updateobj->status =1;
          $updateobj->save();
      }      
      if($insert_id)
        notify()->success('Action Added!');
      else
        smilify('Error', 'Error Occurred Pls recheck!');
      return redirect()->back();
  }
  ///////////////////////////////////
  /////attachment insertion in tapal view
  public function tapal_attachmentpost(Request $request)
  {
    $id = Auth::user()->id;   
    //return $request;  
  
        $seatid_new = $request->session()->get('session_seat');
    
    $uploadcount=$request->uploadcount1;
    $tapal_id=$request->creation_of_attachment;
    $filename="upload";
    $filedescrem="filedesc";
    $filedesc=$request->$filedescrem;
    $document_id="";
    $attachmentstr="";
    if ($request->hasFile($filename)) 
    {
        $fileobj=$request->file($filename)->getClientOriginalName();
        $destpath="uploads";
        $custom_file_name = time().'-'.$id.'-'.$fileobj;  
        $path = $request->file($filename)->storeAs($destpath,$custom_file_name);

        $document_id = \App\Documents::create([//model name database field name
        'tapal_id' => $tapal_id,
        'document_path' => $path,
        'document_name' => $filedesc,
        'updated_by'=>$id
         ]);
    }
    if($document_id)
    {

      $sendmessage=1;
      if($path) 
        {    

           $filepath=storage_path('app/'.$path);
         $size=round(filesize($filepath)/1024,1);

          $attachmentstr = "<li><div class='mailbox-attachment-info'><a href='#' class='mailbox-attachment-name'><i class='fa fa-paperclip'></i> $filedesc</a><span class='mailbox-attachment-size'>$size KB<a href='../../storage/app/$path' class='btn btn-default btn-xs pull-right'><i class='fa fa-cloud-download'></i></a></span></div></li>";
        }
    }
    else
      $sendmessage=0;
  
     $attacharr['attachment']=$attachmentstr;
    //return $sendmessage;
    return $attacharr;
  }
  public function tapalcapture_attachmentpost(Request $request)
  {
    $id = Auth::user()->id;   
    //return $request;  
    $seatid_new = $request->session()->get('session_seat');
    $uploadcount=$request->uploadcount1;
    $tapal_id=$request->creation_of_attachment;
    $filename="upload";
    $filedescrem="filedesc";
    $filedesc=$request->$filedescrem;
    $document_id="";
    $attachmentstr="";
    if ($request->hasFile($filename)) 
    {
        $fileobj=$request->file($filename)->getClientOriginalName();
        $destpath="uploads";
        $custom_file_name = time().'-'.$id.'-'.$fileobj;  
        $path = $request->file($filename)->storeAs($destpath,$custom_file_name);

        $document_id = \App\Documents::create([//model name database field name
        'tapal_id' => $tapal_id,
        'document_path' => $path,
        'document_name' => $filedesc,
        'updated_by'=>$id
         ]);
    }
    if($document_id)
    {

      $sendmessage=1;
      if($path) 
        {    

           $filepath=storage_path('app/'.$path);
         $size=round(filesize($filepath)/1024,1);

          $attachmentstr = "<li><div class='mailbox-attachment-info'><a href='#' class='mailbox-attachment-name'><i class='fa fa-paperclip'></i> $filedesc</a><span class='mailbox-attachment-size'>$size KB<a href='../../storage/app/$path' class='btn btn-default btn-xs pull-right'><i class='fa fa-cloud-download'></i></a></span></div></li>";
        }
    }
    else
      $sendmessage=0;
    $attacharr['attachment']=$attachmentstr;
    return redirect()->back();
  }

  //////////////////////////
  public function tapal_attachmentpostdata(Request $request)
  {
      $userid = Auth::user()->id;     
      $seatid_new = $request->session()->get('session_seat');
      $uploadcount=$request->uploadcount;
      $tapal_id=$request->creation_of_tapalattachment;
      $filename="upload1";
      $filedescrem="filedesc1";
      $filedesc=$request->$filedescrem;
      if ($request->hasFile($filename)) 
      {
          $fileobj=$request->file($filename)->getClientOriginalName();
          $destpath="uploads";
          $custom_file_name = time().'-'.$userid.'-'.$fileobj;  
          $path = $request->file($filename)->storeAs($destpath,$custom_file_name);
          
          $document_id = \App\Documents::create([//model name database field name
          'tapal_id' => $tapal_id,
          'document_path' => $path,
          'document_name' => $filedesc,
          'updated_by'=>$userid
           ]);
      }
      if($document_id)
        notify()->success('Attachment Added!');
      else
        smilify('Error', 'Error Occurred Pls recheck!');    
      return redirect()->back();
  }
  /////////////////
  public function postit_comment(Request $request)
  {
      $tapalid=$request->tapal;
      $commentid=$request->comment_id;
      $postcommentstatus = \App\Comments::where('id',$commentid)->where('comment_type',2)->where('disgard_flag',0)->update(['disgard_flag' => 1]);
      return redirect()->route('inbox');
  }
  public function creation_of_tapalpost(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $this->validate($request,[
          'title' => 'required',
          'description' => 'required',
          'subject_group' => 'required',
          'subject' => 'required',
          //'receivedfrom' => 'required',
          //'receiveddate' => 'required',
          'mode_of_receipt' => 'required',
          'priority' => 'required',            
        ]);
    $id = Auth::user()->id;
    $yr=date("Y");
    $tapalsearch='%'.$yr;
    $tapalobj=\App\Tapal::select('tapal_no')->where("tapal_no",'like',$tapalsearch)->orderBy('id','desc')->first();
    if($tapalobj)
    {
        $lasttapalno=$tapalobj->tapal_no;
        $tapalarr=explode("/",$lasttapalno);
        $lasttapalint=$tapalarr[1];
        $tapalno=$lasttapalint+1;
    }
    else
        $tapalno=1;
    $tapalprint="TPL/".$tapalno."/".$yr;
    $title=$request->title;
    $description=$request->description;
    $intrnextn=$request->type;
    $subject_group=$request->subject_group;
    $subject=$request->subject;
    $receivedfrom=$request->receivedfrom;
    $receiveddate=$request->receiveddate;
    $mode_of_receipt=$request->mode_of_receipt;
    $priority=$request->priority;
    $confidential=$request->confidential;
    $valuable=$request->valuables;
    $detail=$request->details;
    $keywords=$request->keywords;
    //dd($priority);
    //////check max number of files exceeds or not///////////////////////////
    $slugname=$request->session()->get('slugname');
    $frequency=$request->session()->get('frequency');
    $stripe_status=$request->session()->get('stripe_status');
    //dd($stripe_status);
    if($stripe_status=="active")
    {
      if($frequency=="year")
      {
          $payment_interval_val = "annual";
      }
      if($frequency=="month")
      {
          $payment_interval_val = "monthly";
      }
      if($slugname)
      {
        $prd_det = App\PaymentLink::where('slugname','=', $slugname)->where('frequency',$payment_interval_val)->first();  
        if(isset($prd_det))
        {
            $max_num_tapals = $prd_det->no_of_tapals;
        }
      }
      $tapal_count = App\Tapal::where('office_id',$office_id)->count();
      $next_tapal_count = $tapal_count+1;
      ////////////////////////////////////////////////////////////////////////////
      if($next_tapal_count<=$max_num_tapals)
      {
        $id = Auth::user()->id;
        $insert_id = \App\Tapal::create([//model name database field name
              'tapal_no' => $tapalprint,
              'title' => $title,
              'tapal_description' => $description,
              'internal_external' => $intrnextn,
              'subject_group_id' => $subject_group,
              'subject_id' => $subject,
              'received_from' => $receivedfrom,
              'received_date' => $receiveddate,
              'mode_of_receipt' => $mode_of_receipt,
              'priority' => $priority,
              'confidential' => $confidential,
              'has_valuables' => $valuable,
              'details' => $detail,
              'keywords' => $keywords,
              'created_by' =>$id,
              'updated_by'=>$id,
              'status'=>0,
              'office_id' => $office_id,
            ]);
        if($insert_id)
        {
          $id = Auth::user()->id;
          $creation_of_tapals =\App\Tapal::where('id',$id)->first();
          //Tapal Forward entry
          //get seat_id of current user
          $seatid=$request->session()->get('session_seat');
          $tapal_forward_id = \App\Tapal_forward::create([//model name database field name
            'tapal_id' => $insert_id->id,
            'from_seat' => 0,
            'to_seat' => $seatid,
            'updated_by' =>$id,
            'active_flag' => 1,
            'read_flag' => 1
             ]);
          $uploadcount=$request->uploadcount;
          for($i=1;$i<=$uploadcount;$i++)
          {

            $filename="upload".$i;
            $filedescrem="filedesc".$i;
            $filedesc=$request->$filedescrem;
            if ($request->hasFile($filename)) 
            {
              $fileobj=$request->file($filename)->getClientOriginalName();
              $destpath="uploads";
              $custom_file_name = time().'-'.$id.'-'.$fileobj;
              $path = $request->file($filename)->storeAs($destpath,$custom_file_name);
              $document_id = \App\Documents::create([//model name database field name
                'tapal_id' => $insert_id->id,
                'document_path' => $path,
                'document_name' => $filedesc,
                'updated_by'=>$id
                 ]);
            }
          }
          notify()->success('Tapal Added!');
          return redirect('inbox');
        }
        else 
          smilify('Error', 'Error Occurred Pls recheck!'); 
      }
      else
      {
          smilify('Error', 'Maximum Number of Tapals Exceeds for this Organization.'); 
      }
    }
    else
    {
        smilify('Error', 'Your Subscription is not active. Please contact Administrator'); 
    }
    //return redirect()->back();
  }

  public function creation_of_tapalpostdata(Request $request)
  {   
    $office_id=$request->session()->get('session_office');
    $id = Auth::user()->id;
    $creation_of_tapals =\App\Tapal::where('office_id',$office_id)->with('subject','subject_groupobj','documents','priorityobj')->where('created_by',$id)->get();
    $data  = [];
    $i=0;
    foreach ($creation_of_tapals as $creation_of_tapal)
    {   
        $id=$creation_of_tapal->id;
        $tapalnum=$creation_of_tapal->tapal_no;//db name
        $tapaltitle=$creation_of_tapal->title;
        $desc=$creation_of_tapal->tapal_description;
        $subject_group=$creation_of_tapal->subject_groupobj->subject_group;
        $subject=$creation_of_tapal->subject->subject; 
        $mode_of_receipts=$creation_of_tapal->mode_of_receipt;
        $priorities=$creation_of_tapal->priorityobj->priority;
        // dd($priorities);
        $conf=$creation_of_tapal->confidential;
        $val=$creation_of_tapal->has_valuables;
        $det=$creation_of_tapal->details;
        $keyword=$creation_of_tapal->keywords;
        $updated_at=$creation_of_tapal->updated_at->format('d-M-Y');
        $attachments="";
        foreach($creation_of_tapal->documents as $document)
        {
          $attachments.=$document->document_path." ";

        }
        $obj = new \stdClass;
        $obj->incid = $i + 1;
        $obj->id = $id;
        $obj->tapal_no = $tapalnum;
        $obj->title = $tapaltitle;
        $obj->tapal_description = $desc;
        $obj->subject_group_id = $subject_group;
        $obj->subject_id = $subject;
        $obj->mode_of_receipt = $mode_of_receipts;
        $obj->priority = $priorities;
        $obj->confidential = $conf;
        $obj->has_valuables = $val;
        $obj->details = $det;
        $obj->keywords = $keyword;
        $obj->attachments = $attachments;
        $obj->updated_at = $updated_at;
        $data[$i] = $obj;
        $i++;
    }
    $creation_of_tapalpostdata = collect($data);  
    return Datatables::of($creation_of_tapalpostdata)
                      ->addColumn('action', function ($creation_of_tapaldata) {
                          return '<a href="' . url('showcreation_of_tapaldata') . '/' . $creation_of_tapaldata->id . '" class="btn btn-xs btn-primary"><i class="fa fa-edit"></i> Show</a>';
                      })
                      ->editColumn('id', 'ID: {{$incid}}')
                      ->make(true);
  }
  public function tapal_forwardpost(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $tapalid=$request->creation_of_tapal_id;
    //$user=$request->user_seat->user_id;
    $name = Auth::user()->name;
    $office=$request->officename;
    $department=$request->deptname;
    $section=$request->secname;
    $toseat=$request->seatname;
    $check=$request->key;
    $id = Auth::user()->id;
    $seatid=$request->session()->get('session_seat');
    // $tapal_forward=\App\Tapal_forward::where('tapal_id',$tapalid)->where('to_seat', $seatid)->where('active_flag',1)->get()
    if($section)
      $seats = \App\Seat::where('section_id', $section)->get();
    else if($department)
      $seats = \App\Seat::where('department_id', $department)->get();
    else
      $seats = \App\Seat::where('office_id', $office_id)->get();
    $seatcount=0;
    $check_flag=0;
    foreach($seats as $seat)
    {
      $toseat=$seat->id;
      $seatobj=$request->$toseat;
      if($seatobj==1)
      {
          $check_flag = 1;
          $selectedseat=$toseat;
          $seatcount++;
      }
    }
    if($check_flag==0)
    {
      smilify('Error', 'Please select atleast one seat to forward !!!');
      return redirect()->back();
    }
    if($check_flag==1)
    {
      /////update active flag to 0 ///////////////
      $tapal_forward = \App\Tapal_forward::where('to_seat', $seatid)->where('tapal_id', $tapalid)->where('active_flag',1)->update(['active_flag' => 0]);
      /////update read flag to 0 ///////////////
      //$tapal_forward1 = \App\Tapal_forward::where('to_seat', $seatid)->where('tapal_id', $tapalid)->where('read_flag',1)->update(['read_flag' => 0]);
      //seatcount has the total selected seats
      if($seatcount==1)
      {
        $insert_id = \App\Tapal_forward::create([//model name database field name
        'tapal_id' => $request->creation_of_tapal_id,
        'to_seat' => $selectedseat,
        'from_seat' => $seatid,
        'active_flag' => 1,
        'read_flag' => 0,
        'updated_by'=>$id
        ]);
      }
      elseif($seatcount>1)
      {
          //multiple seat forward..duplicate file must be created
          $i=0;
          foreach($seats as $seat)
          {
            $toseat=$seat->id;
            $seatobj=$request->$toseat;
            $title=$request->title;                  
            if($seatobj==1)
            {
                $selectedseat=$toseat;
                //duplicate this file
                $tapaldetails = \App\Tapal::where('id',$tapalid)->first();
                $i++;
                $newtapalno=$tapaldetails->tapal_no."(".$i.")";
                $duptapal = \App\Tapal::create([//model name database field name
                    'tapal_no' => $newtapalno,
                    'initiated_tapal_id' => $tapalid,
                    'title' => $tapaldetails->title,
                    'tapal_description' => $tapaldetails->tapal_description,
                    'internal_external' => $tapaldetails->internal_external,
                    'subject_group_id' => $tapaldetails->subject_group_id,
                    'subject_id' => $tapaldetails->subject_id,
                    'received_from' => $tapaldetails->received_from,
                    'received_date' => $tapaldetails->received_date,
                    'mode_of_receipt' => $tapaldetails->mode_of_receipt,
                    'priority' => $tapaldetails->priority,
                    'confidential' => $tapaldetails->confidential,
                    'has_valuables' => $tapaldetails->has_valuables,
                    'details' => $tapaldetails->details,
                    'keywords' => $tapaldetails->keywords,
                    'created_by' =>$id,
                    'updated_by'=>$id,
                    'status'=>0
                  ]);
                //get comments of orginal tapal
                $comments=\App\Comments::where('tapal_id',$tapalid)->get();
                foreach($comments as $comment)
                {
                  $orginalcommentseatid=$comment->seat_id;
                  $orginalcomment_type=$comment->comment_type;
                  $orginalcommentdescription=$comment->comment_description;
                  $orginalcommentcreated_at=$comment->created_at;
                  $orginalcommentupdated_at=$comment->updated_at;
                  $orginalcommentupdated_by=$comment->updated_by;
                  $commentfrwd = \App\Comments::create([
                      'tapal_id' => $duptapal->id,
                      'seat_id' =>  $orginalcommentseatid,
                      'comment_type' => $orginalcomment_type,
                      'comment_description' => $orginalcommentdescription,
                      'created_at'  => $orginalcommentcreated_at,
                      'updated_at'  => $orginalcommentupdated_at,
                      'updated_by'=>$orginalcommentupdated_by
                    ]);
                }
                //get actions of orginal tapal
                $actions=\App\Tapal_action::where('tapal_id',$tapalid)->get();
                foreach($actions as $action)
                {
                    $orginalactionseatid=$action->seat_id;
                    $orginalactiontype=$action->action_type;
                    $orginalactiondescription=$action->action_description;
                    $orginalactioncreated_at=$action->created_at;
                    $orginalactionupdated_at=$action->updated_at;
                    $orginalactionupdated_by=$action->created_by;
                    $actionfrwd = \App\Tapal_action::create([
                          'tapal_id' => $duptapal->id,
                          'seat_id' =>  $orginalactionseatid,
                          'action_type' => $orginalactiontype,
                          'action_description' => $orginalactiondescription,
                          'created_at'  => $orginalactioncreated_at,
                          'updated_at'  => $orginalactionupdated_at,
                          'created_by'=>$orginalactionupdated_by
                      ]);
                }                       
                //get attachments of orginal tapal
                $attachments=\App\Documents::where('tapal_id',$tapalid)->get();
                foreach($attachments as $attachment)
                {
                    $orginalattachmentseatid=$attachment->seat_id;
                    $orginalattachmentdocumentpath=$attachment->document_path;
                    $orginalattachmentdocumentname=$attachment->document_name;
                    $orginalattachmentcreated_at=$attachment->created_at;
                    $orginalattachmentupdated_at=$attachment->updated_at;
                    $orginalattachmentupdated_by=$attachment->updated_by;
                    $attachmentfrwd = \App\Documents::create([
                        'tapal_id' => $duptapal->id,
                        'seat_id' =>  $orginalattachmentseatid,
                        'document_path' => $orginalattachmentdocumentpath,
                        'document_name' => $orginalattachmentdocumentname,
                        'created_at'  => $orginalattachmentcreated_at,
                        'updated_at'  => $orginalattachmentupdated_at,
                        'updated_by'=>$orginalattachmentupdated_by
                      ]);
                }
                //forward duplicated file 
                $firstforwardinsert_id = \App\Tapal_forward::create([//model name database field name
                      'tapal_id' => $duptapal->id,
                      'to_seat' => $seatid,
                      'from_seat' => 0,
                      'active_flag' => 0,
                      'read_flag' => 1,
                      'updated_by'=>$id
                  ]);
                $insert_id = \App\Tapal_forward::create([//model name database field name
                      'tapal_id' => $duptapal->id,
                      'to_seat' => $toseat,
                      'from_seat' => $seatid,
                      'active_flag' => 1,
                      'read_flag' => 0,
                      'updated_by'=>$id
                  ]);
                $tapalforwardusername= "";
                $userSchemaDet = \App\Models\User::where('id',$toseat)->first();
                if(isset($userSchemaDet))
                {
                    $user_name = $userSchemaDet->name;
                }
                $tapalarr = \App\Tapal::where('id', $duptapal->id)->first();
                if(isset($tapalarr))
                {
                    $tapal_no = $tapalarr->tapal_no;
                }
                $tapalforwardbyarr = \App\Models\User::where('id',$seatid)->first();
                if(isset($tapalforwardbyarr))
                {
                    $tapalforwardusername = $tapalforwardbyarr->name;
                }
                $body = $tapal_no. "has been forward to you by ".$tapalforwardusername;
                $offerData = [
                              'name' => 'Hello '.$user_name,
                              'body' => $body,
                          ];
                Notification::send($userSchemaDet, new TapalNotification($offerData));
            }  /////end of if(seatobj)
          } //endforeach
          //change the status of initiated file to 2
          $status = \App\Tapal::where('id', $tapalid)->update(['status' => 2]);
      }
    }
    if($insert_id)
    {
      notify()->success('Forwarded Successfully!!');
      return redirect('inbox');
    }
    else
    {
      smilify('Error', 'Error Occurred Pls recheck!');
      return redirect()->back();
    }   
  }

  public function newcomment(Request $request)
  {
    $this->validate($request,[
            'comment_type' => 'required',
            'commentdesc' => 'required'   
      ]);
    $userid = Auth::user()->id;
    $seatid_new = $request->session()->get('session_seat');
    $comment_type=$request->comment_type;
    $description=$request->commentdesc;
    //$tapal_id=$request->creation_of_comment;
    $tapal_id=$request->creation_of_tapal_id;       
    $id = Auth::user()->id;
    $insert_id = \App\Comments::create([//model name database field name
          'comment_type' => $comment_type,
          'comment_description' => $description,
          'tapal_id' => $tapal_id,
          'seat_id' => $seatid_new,    
          'updated_by'=>$id
      ]);
      if($insert_id)
        notify()->success('Comment Added!');
      else
        smilify('Error', 'Error Occurred Pls recheck!');
      return redirect()->back();
  }

  public function newaction(Request $request)
  {
    $this->validate($request,[      
            'action_type' => 'required',
            'actiondescription' => 'required'    
       ]);
    $seatid_new = $request->session()->get('session_seat');
    $action_type=$request->action_type;
    $description=$request->actiondescription;
    //$tapal_id=$request->creation_of_comment;
    $tapal_id=$request->creation_of_tapal_id;
    //$tapal_id=$tapalid;
    //$hidden=$request->commentval;
    //dd($tapalid);
    $actions_list = \App\Action::where('office_id',$office_id)->where('actions',$action_type)->first();
    if(isset($actions_list))
    {
      $actions = $actions_list->id;
    }
    $id = Auth::user()->id;
    $insert_id = \App\Tapal_action::create([//model name database field name
          'action_type' => $actions,
          'action_description' => $description,
          'tapal_id' => $tapal_id,
          'seat_id' => $seatid_new,
          'created_by'=>$id
        ]);
    if($action_type=="Close")
    {
        $updateobj = \App\Tapal::where('id',$tapal_id)->first();
        $updateobj->status =1;
        $updateobj->save();
    }
    if($insert_id)
       notify()->success('Action Added!');
    else
        smilify('Error', 'Error Occurred Pls recheck!');

    return redirect()->back();
  }

  public function tapalnewforwardpost(Request $request)
  {
    $this->validate($request,[     
            'officename' => 'required'               
      ]);
    $tapalid=$request->creation_of_tapal_id;
    //$user=$request->user_seat->user_id;
    $name = Auth::user()->name;
    $office=$request->officename;
    $department=$request->deptname;
    $section=$request->secname;
    $toseat=$request->seatname;
    $check=$request->key;
    $id = Auth::user()->id;
    $seatid=$request->session()->get('session_seat');
    // $tapal_forward=\App\Tapal_forward::where('tapal_id',$tapalid)->where('to_seat', $seatid)->where('active_flag',1)->get()
    if($section)
      $seats = \App\Seat::where('section_id', $section)->get();
     else if($department)
      $seats = \App\Seat::where('department_id', $department)->get();
    else
      $seats = \App\Seat::where('office_id', $office)->get();
    $seatcount=0;
    $check_flag=0;
    foreach($seats as $seat)
    {
      $toseat=$seat->id;
      $seatobj=$request->$toseat;
      if($seatobj==1)
      {
          $check_flag = 1;
          $selectedseat=$toseat;
           $seatcount++;
       }
    }
    if($check_flag==0)
    {
        smilify('Error', 'Please select atleast one seat to forward !!!');
        return redirect()->back();
    }
    if($check_flag==1)
    {
      /////update active flag to 0 ///////////////
      $tapal_forward = \App\Tapal_forward::where('to_seat', $seatid)->where('tapal_id', $tapalid)->where('active_flag',1)->update(['active_flag' => 0]);
        /////update read flag to 0 ///////////////
      $tapal_forward1 = \App\Tapal_forward::where('to_seat', $seatid)->where('tapal_id', $tapalid)->where('read_flag',1)->update(['read_flag' => 0]);
      //seatcount has the total selected seats
      if($seatcount==1)
      {
        $insert_id = \App\Tapal_forward::create([//model name database field name
        'tapal_id' => $request->creation_of_tapal_id,
        'to_seat' => $selectedseat,
        'from_seat' => $seatid,
        'active_flag' => 1,
        'read_flag' => 0,
        'updated_by'=>$id
        ]);
      }
      elseif($seatcount>1)
      {
          //multiple seat forward..duplicate file must be created
          $i=0;
          foreach($seats as $seat)
          {
            $toseat=$seat->id;
            $seatobj=$request->$toseat;
            $title=$request->title;                  
            if($seatobj==1)
            {
                $selectedseat=$toseat;
                //duplicate this file
                $tapaldetails = \App\Tapal::where('id',$tapalid)->first();
                $i++;
                $newtapalno=$tapaldetails->tapal_no."(".$i.")";
                $duptapal = \App\Tapal::create([//model name database field name
                        'tapal_no' => $newtapalno,
                        'initiated_tapal_id' => $tapalid,
                        'title' => $tapaldetails->title,
                        'tapal_description' => $tapaldetails->tapal_description,
                        'internal_external' => $tapaldetails->internal_external,
                        'subject_group_id' => $tapaldetails->subject_group_id,
                        'subject_id' => $tapaldetails->subject_id,
                        'received_from' => $tapaldetails->received_from,
                        'received_date' => $tapaldetails->received_date,
                        'mode_of_receipt' => $tapaldetails->mode_of_receipt,
                        'priority' => $tapaldetails->priority,
                        'confidential' => $tapaldetails->confidential,
                        'has_valuables' => $tapaldetails->has_valuables,
                        'details' => $tapaldetails->details,
                        'keywords' => $tapaldetails->keywords,
                        'created_by' =>$id,
                        'updated_by'=>$id,
                        'status'=>0
                    ]);
                //get comments of orginal tapal
                $comments=\App\Comments::where('tapal_id',$tapalid)->get();
                foreach($comments as $comment)
                {
                  $orginalcommentseatid=$comment->seat_id;
                  $orginalcomment_type=$comment->comment_type;
                  $orginalcommentdescription=$comment->comment_description;
                  $orginalcommentcreated_at=$comment->created_at;
                  $orginalcommentupdated_at=$comment->updated_at;
                  $orginalcommentupdated_by=$comment->updated_by;
                  $commentfrwd = \App\Comments::create([
                  'tapal_id' => $duptapal->id,
                  'seat_id' =>  $orginalcommentseatid,
                  'comment_type' => $orginalcomment_type,
                  'comment_description' => $orginalcommentdescription,
                  'created_at'  => $orginalcommentcreated_at,
                  'updated_at'  => $orginalcommentupdated_at,
                  'updated_by'=>$orginalcommentupdated_by
                  ]);
                }

                //get actions of orginal tapal
                $actions=\App\Tapal_action::where('tapal_id',$tapalid)->get();
                foreach($actions as $action)
                {
                    $orginalactionseatid=$action->seat_id;
                    $orginalactiontype=$action->action_type;
                    $orginalactiondescription=$action->action_description;
                    $orginalactioncreated_at=$action->created_at;
                    $orginalactionupdated_at=$action->updated_at;
                    $orginalactionupdated_by=$action->created_by;
                    $actionfrwd = \App\Tapal_action::create([
                    'tapal_id' => $duptapal->id,
                    'seat_id' =>  $orginalactionseatid,
                    'action_type' => $orginalactiontype,
                    'action_description' => $orginalactiondescription,
                    'created_at'  => $orginalactioncreated_at,
                    'updated_at'  => $orginalactionupdated_at,
                    'created_by'=>$orginalactionupdated_by
                    ]);
                }                       
                //get attachments of orginal tapal
                $attachments=\App\Documents::where('tapal_id',$tapalid)->get();
                foreach($attachments as $attachment)
                {

                    $orginalattachmentseatid=$attachment->seat_id;
                    $orginalattachmentdocumentpath=$attachment->document_path;
                    $orginalattachmentdocumentname=$attachment->document_name;
                    $orginalattachmentcreated_at=$attachment->created_at;
                    $orginalattachmentupdated_at=$attachment->updated_at;
                    $orginalattachmentupdated_by=$attachment->updated_by;
                    $attachmentfrwd = \App\Documents::create([
                    'tapal_id' => $duptapal->id,
                    'seat_id' =>  $orginalattachmentseatid,
                    'document_path' => $orginalattachmentdocumentpath,
                    'document_name' => $orginalattachmentdocumentname,
                    'created_at'  => $orginalattachmentcreated_at,
                    'updated_at'  => $orginalattachmentupdated_at,
                    'updated_by'=>$orginalattachmentupdated_by
                    ]);
                }
                //forward duplicated file 
                $firstforwardinsert_id = \App\Tapal_forward::create([//model name database field name
                  'tapal_id' => $duptapal->id,
                  'to_seat' => $seatid,
                  'from_seat' => 0,
                  'active_flag' => 0,
                  'read_flag' => 1,
                  'updated_by'=>$id
                  ]);
                 
                $insert_id = \App\Tapal_forward::create([//model name database field name
                    'tapal_id' => $duptapal->id,
                    'to_seat' => $toseat,
                    'from_seat' => $seatid,
                    'active_flag' => 1,
                    'read_flag' => 0,
                    'updated_by'=>$id
                  ]);
            }  /////end of if(seatobj)
          } //endforeach
          //change the status of initiated file to 2
          $status = \App\Tapal::where('id', $tapalid)->update(['status' => 2]);
      }
    }
    if($insert_id)
    {
        notify()->success('Forwarded Successfully!');
        return redirect('inbox');
    }
    else
    {
        smilify('Error', 'Error Occurred Pls recheck!');
        return redirect()->back();
    }
  }
  public function showcreation_of_tapaldata($id,Request $request)//show button
  {
    $office_id=$request->session()->get('session_office');
    $creation_of_tapal=\App\Tapal::where('id',$id)->first();
    $subject_group =\App\Subject_Group::where('office_id',$office_id)->get();
    $priority =\App\Priority::where('office_id',$office_id)->get();
    $actions=\App\Action::where('office_id',$office_id)->get();
    $subject =\App\Subjectgroup_subject::where('office_id',$office_id)->where('subject_group_id',$creation_of_tapal->subject_group_id)->with('subject')->get();
    $userid = Auth::user()->id;
    $comments =\App\Comments::where('tapal_id',$id)->with('seat','tapal')->orderBy('created_at','DESC')->get();
    $attachments =\App\Documents::where('tapal_id',$id)->with('tapal')->orderBy('created_at','DESC')->get();
    $attachmentcount =\App\Documents::where('tapal_id',$id)->with('tapal')->count();
    $tapalactions =\App\Tapal_action::where('tapal_id',$id)->with('seat','tapal','action')->orderBy('created_at','DESC')->get();
    //dd($tapalactions);
    $seatid=$request->session()->get('session_seat');
    $tapal_arr = \App\Tapal_forward::where('to_seat', $seatid)->where('active_flag',1)->get();
    $office=\App\Office::where('id',$office_id)->get();
    $department=\App\Department::where('office_id',$office_id)->get();
    $section =\App\Section::where('office_id',$office_id)->get();
    $currentuserstatus = \App\Tapal_forward::where('to_seat', $seatid)->where('tapal_id', $id)->where('active_flag',1)->count();
    return view('showcreation_of_tapaldata', compact('subject_group','subject','creation_of_tapal','userid','seatid','currentuserstatus','priority','comments','actions','tapalactions','attachments','attachmentcount','tapal_arr','office','department','section'));
  }
  public function updatecreation_of_tapaldata(Request $request)//update button
  {
    //validation of fields
    $this->validate($request,[
          //form field(blade name)
          //'tapalno' => 'required',//name of blade name
          'title' => 'required',
          'description' => 'required',
          'subject_group' => 'required',
          'subject' => 'required',
          //'receivedfrom' => 'required',
          //'receiveddate' => 'required',
          //'mode_of_receipt' => 'required',
          'priority' => 'required',
          //'confidential' => 'required',
          //'valuable' => 'required',
          //'keywords' => 'required',
          //'upload' => 'required'
       ]);
    //variable name
    $tapalnum=$request->tapalno;
    $titl=$request->title;
    $desc=$request->description;
    $subject_grp=$request->subject_group;
    $sub=$request->subject;
    $interexter=$request->type;
    $receivdfrom=$request->receivedfrom;
    $receivddate=$request->receiveddate;
    $mode_ofreceipt=$request->mode_of_receipt;
    $prio=$request->priority;
    $confd=$request->confidential;
    $valuab=$request->valuables;
    $deta=$request->details;
    $keywrd=$request->keywords;
    //$upload1=$request->uploaddiv;
    // dd($upload1);
    $userid = Auth::user()->id;        
    $updateobj = \App\Tapal::where('id',$request->creation_of_tapal_id)->first();
    // db name        //variable name
    // $updateobj->tapal_no = $tapalnum;
    $updateobj->title = $titl;
    $updateobj->tapal_description = $desc;
    $updateobj->subject_group_id = $subject_grp;
    $updateobj->subject_id = $sub;
    $updateobj->internal_external = $interexter;
    $updateobj->received_from = $receivdfrom;
    $updateobj->received_date = $receivddate;
    $updateobj->mode_of_receipt = $mode_ofreceipt;
    $updateobj->priority = $prio;
    $updateobj->confidential = $confd;
    $updateobj->has_valuables = $valuab;
    $updateobj->details = $deta;
    $updateobj->keywords = $keywrd;
    //$updateobj->attachments = $uploads;
    $updateobj->updated_by = $userid;
    $updateobj->save();
    $uploadcount=$request->uploadcount;
    $id = Auth::user()->id;
    for($i=1;$i<=$uploadcount;$i++)
    {

      $filename="upload".$i;
      $filedescrem="filedesc".$i;
      $filedesc=$request->$filedescrem;
      if ($request->hasFile($filename)) 
      {
        $fileobj=$request->file($filename)->getClientOriginalName();
        $destpath="uploads";
        $custom_file_name = time().'-'.$id.'-'.$fileobj;
        $path = $request->file($filename)->storeAs($destpath,$custom_file_name);
        $document_id = \App\Documents::create([//model name database field name
              'tapal_id' => $request->creation_of_tapal_id,
              'document_path' => $path,
              'document_name' => $filedesc,
              'updated_by'=>$id
           ]);
      }
    }
    return redirect('showcreation_of_tapaldata/'.$request->creation_of_tapal_id);  
  }
  //pull back/////////////
  public function move_to_inbox(Request $request)
  {
    $id=$request->creation_of_tapal;
    $userid = Auth::user()->id;
    $seat = \App\Tapal_forward::where('tapal_id',$id)->get();
    foreach ($seat as $togetseat) 
    {
      $toseat=$togetseat->to_seat;
      $fromseat=$togetseat->from_seat;
      $fwd_id = $togetseat->id;
      $read_flag = $togetseat->read_flag;
      if($fromseat!=0)
      {
        //echo "inside if...<br>";
        $tapaldelete=\App\Tapal_forward::where('id',$fwd_id)->where('tapal_id',$id)->where('from_seat',$fromseat)->where('to_seat',$toseat)->where('read_flag',0)->delete();
        //dd($tapaldelete);
      }
      
    }
    //echo "toseat=$toseat....fromseat=$fromseat...read_flag=$read_flag....fwd_id=$fwd_id....<br>";
    //$readupdate = \App\Tapal_forward::where('tapal_id',$id)->where('to_seat',$fromseat)->where('read_flag',0)->update(['read_flag' => 1]);
    $updateflag = \App\Tapal_forward::where('tapal_id',$id)->where('to_seat',$fromseat)->where('active_flag',0)->update(['active_flag' => 1]);
    return redirect()->route('inbox');
  }
  ///////////////////
  //capture file/////////
  public function capturetapal(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $id = Auth::user()->id;
    //$creation_of_tapal=\App\Tapal::where('id',$id)->get();
    $allseats=\App\Seat::where('office_id',$office_id)->get();
    $seatid=$request->session()->get('session_seat');
    $charray=$this->getchildseats1($seatid);
    return view('capturetapal', compact('charray','allseats'));
  }
  public function getchildseats1($parent)
  {
    $childs=\App\Seat::where('reporting_seat',$parent)->get();
    foreach ($childs as $child) 
    {
      array_push($this->childarray,$child->id);
      $this->getchildseats1($child->id);
    }
    return $this->childarray;
  }
  public function gettapallist($id,Request $request)
  { 
    $office_id=$request->session()->get('session_office');
    $seatid=$request->session()->get('session_seat');
    //dd($seatid);
    $data  = [];
    $i=0;
    $tapaldetails_conf=\App\Tapal_forward::where('to_seat',$id)->where('active_flag',1)->with('tapal')->whereHas('tapal', function($q) use($office_id) { $q->where('office_id',$office_id)->where('confidential', 1)->where('status',0);  })->get();
    //dd($tapaldetails_conf);
    foreach ($tapaldetails_conf as $tapal)
    {   
      $tapalid=$tapal->tapal_id;
      $tapalckecking = \App\Tapal_forward::where('tapal_id',$tapalid)->where('from_seat',$seatid)->count();
      //dd($tapalckecking);
      if($tapalckecking==0)
        continue;
      $tapalnum=$tapal->tapal->tapal_no;//db name
      $tapaltitle=$tapal->tapal->title;
      $subjectegrp=\App\Tapal::where('id',$tapalid)->with('subject_groupobj')->first();
      //   dd( $subjectegrp);
      $subject_group=$subjectegrp->subject_groupobj->subject_group;
      $date=$tapal->created_at->format('d-M-Y');
      $updated_at=$tapal->updated_at->format('d-M-Y');
      $obj = new \stdClass;
      $obj->incid = $i + 1;
      $obj->id = $tapalid;
      $obj->tapal_no = $tapalnum;
      $obj->title = $tapaltitle;
      $obj->subject_group = $subject_group;
      $obj->created_at = $date;          
      $obj->updated_at = $updated_at;
      $data[$i] = $obj;
      $i++;
    }
    $tapaldetails=\App\Tapal_forward::where('to_seat',$id)->where('active_flag',1)->with('tapal')->whereHas('tapal', function($q) { $q->where('confidential', NULL)->where('status',0); })->get();
    //dd($tapaldetails);
    foreach ($tapaldetails as $tapal)
    {   
      $tapalid=$tapal->tapal_id;
      $tapalnum=$tapal->tapal->tapal_no;//db name
      $tapaltitle=$tapal->tapal->title;
      $subjectegrp=\App\Tapal::where('id',$tapalid)->with('subject_groupobj')->first();
      //   dd( $subjectegrp);
      $subject_group=$subjectegrp->subject_groupobj->subject_group;
      $date=$tapal->created_at->format('d-M-Y');
      $updated_at=$tapal->updated_at->format('d-M-Y');
      $obj = new \stdClass;
      $obj->incid = $i + 1;
      $obj->id = $tapalid;
      $obj->tapal_no = $tapalnum;
      $obj->title = $tapaltitle;
      $obj->subject_group = $subject_group;
      $obj->created_at = $date;          
      $obj->updated_at = $updated_at;
      $data[$i] = $obj;
      $i++;
    }
    $tapaldata = collect($data);
    return Datatables::of($tapaldata)
            ->addColumn('action', function ($tapallist) {
                return '<a href="' . url('tapal_view') . '/' . $tapallist->id . '" class="btn btn-xs btn-primary"><i class="fa fa-edit"></i> Show</a>';
            })
            ->editColumn('id', 'ID: {{$incid}}')
            ->make(true);
  }
  public function capture1(Request $request)
  {
    $id=$request->creation_of_tapal;
    // dd($id);
    $userid = Auth::user()->id;
    $seatid=$request->session()->get('session_seat');
    $tapalseat = \App\Tapal_forward::where('tapal_id',$id)->where('active_flag',1)->first();
    $tapaltoseat=$tapalseat->to_seat;
    $update_arr = \App\Tapal_forward::where('tapal_id',$id)->where('to_seat',$tapaltoseat)->where('active_flag',1)->orderBy('id','desc')->first();
    //dd($update_arr);
    if(isset($update_arr))
    {
      $update_arr->active_flag= 0;
      $update_arr->save();
    }
    $insert_id = \App\Tapal_forward::create([//model name database field name
                'tapal_id' => $id,
                'to_seat' => $seatid,
                'from_seat' => $tapaltoseat,
                'active_flag' => 1,
                'read_flag' => 0,
                'capture_flag' => 1,
                'updated_by'=>$userid
          ]);
    return redirect()->route('inbox');
  }
  ////////////////////
}