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

class ClosedController extends Controller
{
  protected $childarray=[];
  public function __construct()
  {
      $this->middleware('auth');
  }
  public function closed_tapal(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $id = Auth::user()->id;  
    $seatid=$request->session()->get('session_seat');
    $tapalinboxcount = \App\Tapal_forward::whereHas('tapal', function ($query) { $query->where('status','=','0')->with('user'); })->where('to_seat', $seatid)->where('active_flag',1)->with('tapal')->orderBy('created_at','desc')->count();
    $fileinboxcount = \App\File_forward::where('to_seat', $seatid)->where('active_flag',1)->with('file')->whereHas('file', function ($query) { $query->where('status','=','0'); })->orderBy('created_at','DESC')->count();
    $tapaloutboxcount = \App\Tapal_forward::where('from_seat', $seatid)->with('tapal')->orderBy('created_at','DESC')->count();
    $fileoutboxcount = \App\File_forward::where('from_seat', $seatid)->with('file')->orderBy('created_at','DESC')->count();
    $priority =\App\Priority::where('office_id',$office_id)->get();
    $tapal_arr = \App\Tapal_forward::where('to_seat', $seatid)->where('active_flag',1)->get();
    foreach ($tapal_arr as $tapal_val) 
    {
        $tapalid=$tapal_val->id;
    }
    $actions = \App\Action::where('office_id',$office_id)->get();
    $comments = \App\Comments::all();
    ///////////////TAPALROUTE DETAILS:
    $troutarr=[];
    $tapals=\App\Tapal_forward::where('to_seat',$seatid)->where('active_flag',1)->get();
    //dd($tapals);
    foreach($tapals as $tapal)
    { 
      $tapalidforward = $tapal->tapal_id;
      $tapalsubid=$tapal->tapal->subject_id;
      //dd($tapalsub->subject);
      $trout=\App\Troute::where('subject_id',$tapalsubid)->get();
      $i=0;
      foreach($trout as $trouts)
      { 
        $troutid=$trouts->id;
        $troutename=$trouts->routename; 
        $troutarr[$i]['id']=$troutid;
        $troutarr[$i]['name']=$troutename;
        $i++;
      } 
    }     

    return view('closed_tapal', compact('office_id','seatid','tapalinboxcount','fileinboxcount','tapaloutboxcount','fileoutboxcount','tapal_arr','actions','priority','comments','troutarr'));
  }
  public function closedinboxjson(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    //dd($office_id);
    $id = Auth::user()->id;
    $seatid=$request->session()->get('session_seat');
    $id = Auth::user()->id;
    $inboxs = \App\Tapal_forward::where('to_seat', $seatid)->with('tapal')->whereHas('tapal', function ($query) use($office_id) { $query->where('status','=','1')->where('office_id',$office_id)->with('user','closedby'); })->orderBy('created_at','desc')->get();
    //dd($inboxs);
    $data  = [];
    $i=0;
    foreach ($inboxs as $inbox)
    {
      $id=$inbox->id;
      $tapalno=$inbox->tapal->tapal_no;
      $tapalid=$inbox->tapal->id;
      $priority=$inbox->tapal->priority;
      $createdby=$inbox->tapal->user->name;
      $prioritylabelobj=\App\Priority::where('id',$priority)->first();
      $priority=$prioritylabelobj->priority;
      $date=$inbox->tapal->created_at->format('d-M-Y h-m-s');;
      $title=$inbox->tapal->title;
      $confidential=$inbox->tapal->confidential;
      $valuables=$inbox->tapal->has_valuables;
      $forwardedby=$inbox->from_seat;
      if(!$forwardedby)
        $forwardedby="Self Generated";
      else
      {
        $forwardseatobj=\App\Seat::where('id',$forwardedby)->first();
        $forwardedby=$forwardseatobj->seat_code."::".$forwardseatobj->seat_name;
      }
      $closedbyuser ="";
      $closed_by  ="";
      $closed_date ="";
      if($inbox->tapal->closed_by)
      {
        $closed_by = $inbox->tapal->closed_by;
        if($closed_by)
        {
            $closedbyuser = $inbox->tapal->closedby->name;
        }
        $closed_date = $inbox->tapal->closed_date;
        $closed_date = date("d-M-Y", strtotime($closed_date));
      }
      //echo "closedbyuser=$closedbyuser..<br>";
      $forwardedon=$inbox->created_at->format('d-M-Y');
      $fdate=new \DateTime($forwardedon);
      $cdate=new \DateTime();
      $diff='';
      $diff=date_diff($fdate,$cdate);
      $noofdays= $diff->format("%a days");
      $tapal_forward_toseat=$inbox->to_seat;
      /////count of comments -- tapal/////////////////////
      $match_comments = [['tapal_id','=',$tapalid],['comment_type','=',0]];
      $tapalcommentcount=\App\Comments::where($match_comments)->count();
      /////count of actions -- tapal/////////////////////
      $match_actions = [['tapal_id','=',$tapalid]];
      $tapalactioncount=\App\Tapal_action::where($match_actions)->count();
      /////count of attachments -- tapal/////////////////////
      $match_attachments = [['tapal_id','=',$tapalid]];
      $tapalattachmentcount=\App\Documents::where($match_attachments)->count();
      $subjectgroup=$inbox->tapal->subject_groupobj->subject_group;
      $obj = new \stdClass;
      $obj->incid = $i + 1;
      $obj->id = $id;
      $obj->tapalid = $tapalid;
      $obj->tapal_no = $tapalno;
      $obj->title = $title;
      $obj->created_at = $date;
      $obj->createdby = $createdby;
      $obj->from_seat = $forwardedby;
      $obj->forwardedon = $forwardedon."(".$noofdays.")" ;
      $obj->subject_group = $subjectgroup;
      $obj->tapalcommentcount = $tapalcommentcount;
      $obj->tapalactioncount = $tapalactioncount;
      $obj->tapalattachmentcount = $tapalattachmentcount;
      $obj->priority = $priority;
      $obj->confidential = $confidential;
      $obj->valuables = $valuables;
      $obj->closedbyuser = $closedbyuser;
      $obj->closed_date = $closed_date;
      $data[$i] = $obj;
      $i++;
    }
    $inboxjson = collect($data);
    return Datatables::of($inboxjson)
              ->make(true);
  } 

  public function closedmodaltapalview($id,Request $request)
  {
    $tapaldetailsarr =[];
    $office_id=$request->session()->get('session_office');
    $tapal_id= $id;
    $creation_of_tapal=\App\Tapal::where('id',$id)->where('office_id',$office_id)->with('user')->first();
    $tapal_no=$creation_of_tapal->tapal_no;
    $description=$creation_of_tapal->tapal_description;
    $confidential=$creation_of_tapal->confidential;
    $status=$creation_of_tapal->status;
    $tapalcreateduser=$creation_of_tapal->user->name;
    
    //dd($tapal_no);
    $tapaluserseat=\App\User_Seat::where('user_id',$creation_of_tapal->created_by)->with('seat')->first();
    $tapalseat=$tapaluserseat->seat->seat_name;
    $tapaldetailsarr =[];
    $i=0;
    $tapaldetailsarr['id']=$tapal_id;
    $tapaldetailsarr['tapal_no']=' Tapal No:'." ".$tapal_no."   " .$tapalseat." : " .$tapalcreateduser;
    if($confidential==1)
    {
      $conf=', Confidential';
      $tapaldetailsarr['tapal_no']=' Tapal No:'." ".$tapal_no."   " .$tapalseat." : " .$tapalcreateduser .$conf;
    }
    $tapaldetailsarr['tapal_description']=$description;
    if($creation_of_tapal->internal_external == 1)
    {
      $internal_external='Internal Tapal';
    }
    else
    {
      $internal_external='External Tapal';
    }
    $tapaldetailsarr['internal_external']=$internal_external;
    $tapaldetailsarr['title']=$creation_of_tapal->title;
    $tapaldetailsarr['status']=$status;
    $closedbyuser ="";
    $closed_by  ="";
    $closed_date ="";
    if($creation_of_tapal->closed_by)
    {
      $closed_by = $creation_of_tapal->closed_by;
      if($closed_by)
      {
          $closedbyuser = $creation_of_tapal->closedby->name;
      }
      $closed_date = $creation_of_tapal->closed_date;
      $closed_date = date("d-M-Y", strtotime($closed_date));
    }
    $tapaldetailsarr['closedbyuser']=$closedbyuser;
    $tapaldetailsarr['closed_date']=$closed_date;
    $tapalfrwrd=\App\Tapal_forward::where('tapal_id',$tapal_id)->where('active_flag',1)->with('tapal')->first();
    $to_seat = $tapalfrwrd->to_seat;
    $createdby=$tapalfrwrd->tapal->user->name;
    $createdat=$tapalfrwrd->tapal->created_at->format('d-M-Y h-m-s');
    $forwardedon=$tapalfrwrd->created_at->format('d-M-Y h-m-s');
    $forwardedby=$tapalfrwrd->from_seat;
    if(!$forwardedby)
      $forwardedby="Self Generated";
    else
    {
      $forwardseatobj=\App\Seat::where('id',$forwardedby)->first();
      $forwardedby=$forwardseatobj->seat_code."::".$forwardseatobj->seat_name;
    }
    $tapalfrwrdupd=\App\Tapal_forward::where('tapal_id',$tapal_id)->where('active_flag',1)->where('to_seat',$to_seat)->first();
    if(isset($tapalfrwrdupd))
    {
      $tapalfrwrdupd->read_flag = 1;
      $tapalfrwrdupd->save();
    }
    $tapaldetailsarr['from_seat']=$forwardedby;
    $tapaldetailsarr['created_at']=$forwardedon;
    $tapaldetailsarr['name']=$createdby;
    $tapaldetailsarr['created_at']=$createdat;
    $subject =\App\Subject::where('id',$creation_of_tapal->subject_id)->first();
    $sub=$subject->subject;
    $tapaldetailsarr['subject']=$sub;
    if($creation_of_tapal->mode_of_receipt==0)
      $mode='NA';
    else if($creation_of_tapal->mode_of_receipt==1)
      $mode='Fax';
    else if($creation_of_tapal->mode_of_receipt==2)
      $mode='Email';
    else if($creation_of_tapal->mode_of_receipt==3)
      $mode='By hand';
    else if($creation_of_tapal->mode_of_receipt==4)
      $mode='Post';    
    $tapaldetailsarr['mode_of_receipt']=$mode;
    $prio=App\Priority::where('id',$creation_of_tapal->priority)->first();
    $priority=$prio->priority;
    $tapaldetailsarr['priority']=$priority;
    $attachmentcount =\App\Documents::where('tapal_id',$tapal_id)->count();
    $i=0;
    $tapal_attchment =\App\Documents::where('tapal_id', $tapal_id)->get();
    $tapaldocstr='';
    foreach ($tapal_attchment as $tattachment) 
    {
      $tapal_documentname=$tattachment->document_name;
      $path=$tattachment->document_path;
      $tapal_attach_createdat=$tattachment->created_at->format('d-M-Y h:i:s');
      $size='';
      $filepath=storage_path('app/'.$path);
      if(file_exists($filepath))
      {
        $size=round(filesize($filepath)/1024,1);
      }
      if($tapal_documentname)
      {
        $tapaldocstr.= "<li><div class='mailbox-attachment-info'><a href='#' class='mailbox-attachment-name'><i class='fa fa-paperclip'></i> $tapal_documentname</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>";

        $i++;
      }
    }
    $tapaldetailsarr['document_path']=$tapaldocstr;
    $userid = Auth::user()->id;
    $comments_arr = \App\Comments::where('tapal_id', $tapal_id)->with('tapal','seat')->orderBy('created_at','DESC')->get();
    $commentstr ='';
    $comments_count = \App\Comments::where('tapal_id', $tapal_id)->with('tapal','seat')->count();
    if($comments_count==0)
    {
      $commentstr .= "<div class='box-comment'><div class='comment-text'><span class='username' id='nocomment'>&nbsp;<span class='text-muted pull-right'></span></span>No Comments added yet !!!</div></div>";
    }
    foreach ($comments_arr as $comments_list)
    {
      $created_at=$comments_list->created_at->format('d-M-Y ');
      $tapalid=$comments_list->tapal_id;
      $comment_type=$comments_list->comment_type;
      $comment_description=$comments_list->comment_description;
      $seatname=$comments_list->seat->seat_name;
      $commentseatid=$comments_list->seat_id;
      //dd($tapalid);
      $checkforseatmatch=\App\User_Seat::where('user_id',$userid)->where('seat_id',$commentseatid)->count();
      $currentseat=\App\User_Seat::where('user_id',$userid)->with('seat')->get();
      foreach ($currentseat as $userseat)
      {
        $currentuserseat=$userseat->seat_id;
        $currenttapalseat=\App\Tapal_forward::where('tapal_id',$tapalid)->where('active_flag',1)->first();
        $seat=$currenttapalseat->to_seat;
        $seatflag=0;
        if($currentuserseat==$seat)
        {
          $seatflag=1;
        }
      }
      if(($comment_type==1)&&($checkforseatmatch>0)) 
      {    
        $commentstr .= "<div class='box-comment'><input type='hidden' name='creation_of_tapal' id='creation_of_tapal' value='$id'><img class='img-circle img-sm' src='../public/img/boxed-bg.jpg' alt='User Image'><div class='comment-text'><span class='username'>$seatname posted <font color='red'>Private</font> Comment <span class='text-muted pull-right'>$created_at</span></span><font color='red'>$comment_description</font></div></div>";
      }
      if($comment_type==0) 
      {
        $commentstr .= "<div class='box-comment'><input type='hidden' name='creation_of_tapal' id='creation_of_tapal' value='$id'><img class='img-circle img-sm' src='../public/img/boxed-bg.jpg' alt='User Image'><div class='comment-text'><span class='username'>$seatname posted <font color='green'>Public</font> Comment <span class='text-muted pull-right'>$created_at</span></span><font color='green'>$comment_description</font></div></div>";
      }
      if(($comment_type==2)  && ($comments_list->disgard_flag==0))
      {
        $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'>
        <img class='img-circle img-sm' src='../public/img/boxed-bg.jpg' alt='User Image'>
        <div class='comment-text'><span class='username'>$seatname posted <font color='#ad890a'>Yellow Note</font> <span class='text-muted pull-right'>$created_at</span>
        </span><font color='#ad890a'>$comment_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> "; 
        }
      }  
    }
    $tapaldetailsarr['comment_description']=$commentstr;
    $actions_arr = \App\Tapal_action::where('tapal_id', $id)->with('tapal','seat','action')->orderBy('created_at','DESC')->get();
    $actionstr ='';
    $action_count = \App\Tapal_action::where('tapal_id', $id)->with('tapal','seat','action')->count();
    if($action_count==0)
    {
      $actionstr .= "<div class='box-comment'><div class='comment-text'><span class='username'>&nbsp;<span class='text-muted pull-right'></span></span>No Actions added yet !!!</div></div>";
    }
    foreach ($actions_arr as $actions_list)
    {
      $created_at=$actions_list->created_at->format('d-M-Y');
      $tapalid=$actions_list->id;
      $action_type=$actions_list->action->actions;
      $action_description=$actions_list->action_description;
      $seatname=$actions_list->seat->seat_name;
      //$actionseatid=$actions_list->seat_id;
      if($action_description) 
      {    
        //<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>";
      }
    }  
    $tapaldetailsarr['action_description']=$actionstr;
    $tapalattachedtofile_arr = \App\File_reference::where('tapal_id', $tapal_id)->with('file')->first();
    $tapaldetailsarr['file_id']=$tapalattachedtofile_arr;
    $seatid=$request->session()->get('session_seat');
    $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;
      }
    }
    $tapaldetailsarr['active_flag']=$act_flg_status;
    $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;
    }
    $tapaldetailsarr['read_flag']=$readflag;
    $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;
    }
    $tapaldetailsarr['user_comment_flag']=$user_comment_flag;
    $charray=$this->getchildseatsclosed($seatid);
    $tapalseat = \App\Tapal_forward::where('tapal_id',$tapal_id)->where('active_flag',1)->first();
    $tapaltoseat=$tapalseat->to_seat;
    $enablecapture="";
    if(in_array($tapaltoseat, $charray))
    {
      $enablecapture=1;
    }
    else
    {
      $enablecapture=0;
    }
    $tapaldetailsarr['enablecapture']=$enablecapture;
    //////////////
    $tapalconfflag=0;
    $newflag="";
    //echo "$tapaltoseat....$seatid_new";
    if($tapaltoseat!=$seatid)
    {
      //check if loggedin user is in fileforward fromseat for this fileid
      $tapalckecking = \App\Tapal_forward::where('tapal_id',$tapal_id)->where('from_seat',$seatid)->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'));
    //if the loggedin user doesnt comes in the history of tapal
    $tapalcondition = \App\Tapal_forward::where('tapal_id',$tapal_id)->where('to_seat',$seatid)->count();
    //dd($tapalcondition);
    // return 5;
    if($tapalcondition==0)
    {
      $tapalconfflag=1;
    }
    $charray=$this->getchildseatsclosed($seatid);
    if(in_array($tapaltoseat, $charray)||($tapalconfflag==0))
    {
      $newflag=1;
    }
    else
    {
      $newflag=0;
    }
    if($tapaltoseat==$seatid)
    {
      $newflag=1;
    }
    if($newflag==0)
      return view('tapaldenied', compact('newflag','tapaltoseat','seatid'));
    $priorityfile=App\Priority::all();
    //dd($tapaldetailsarr);
    return $tapaldetailsarr;
  }

  public function reopentapal(Request $request)
  {
    $userid = Auth::user()->id;
    $seatid_new = $request->session()->get('session_seat');
    $id=$request->creation_of_tapal;
    $tapalseat = \App\Tapal_forward::where('tapal_id',$id)->where('active_flag',1)->first();
    $tapaltoseat=$tapalseat->to_seat;
    $update_arr = \App\Tapal::where('id',$id)->orderBy('id','desc')->first();
    //dd($update_arr);
    if(isset($update_arr))
    {
      $update_arr->status= 0;
      $update_arr->save();
    }
    return redirect()->route('inbox');
  }

  //////////////////////////file//////////////////////////////////////////////

  public function closed_file(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $id = Auth::user()->id;  
    $seatid=$request->session()->get('session_seat');
    $tapalinboxcount = \App\Tapal_forward::whereHas('tapal', function ($query) { $query->where('status','=','0')->with('user'); })->where('to_seat', $seatid)->where('active_flag',1)->with('tapal')->orderBy('created_at','desc')->count();
    $fileinboxcount = \App\File_forward::where('to_seat', $seatid)->where('active_flag',1)->with('file')->whereHas('file', function ($query) { $query->where('status','=','0'); })->orderBy('created_at','DESC')->count();
    $tapaloutboxcount = \App\Tapal_forward::where('from_seat', $seatid)->with('tapal')->orderBy('created_at','DESC')->count();
    $fileoutboxcount = \App\File_forward::where('from_seat', $seatid)->with('file')->orderBy('created_at','DESC')->count();
    $priority =\App\Priority::where('office_id',$office_id)->get();
    $tapal_arr = \App\Tapal_forward::where('to_seat', $seatid)->where('active_flag',1)->get();
    foreach ($tapal_arr as $tapal_val) 
    {
        $tapalid=$tapal_val->id;
    }
    $actions = \App\Action::where('office_id',$office_id)->get();
    $comments = \App\Comments::all();
    ///////////////TAPALROUTE DETAILS:
    $troutarr=[];
    $tapals=\App\File_forward::where('to_seat',$seatid)->where('active_flag',1)->get();
    //dd($tapals);
    foreach($tapals as $tapal)
    { 
      $tapalidforward = $tapal->tapal_id;
      $filegroupid=$tapal->file->file_group_id;
      //dd($tapalsub->subject);
      $trout=\App\Troute::where('file_group_id',$filegroupid)->get();
      $i=0;
      foreach($trout as $trouts)
      { 
        $troutid=$trouts->id;
        $troutename=$trouts->routename; 
        $troutarr[$i]['id']=$troutid;
        $troutarr[$i]['name']=$troutename;
        $i++;
      } 
    }     

    return view('closed_file', compact('office_id','seatid','tapalinboxcount','fileinboxcount','tapaloutboxcount','fileoutboxcount','tapal_arr','actions','priority','comments','troutarr'));
  }

  public function closedfileinboxjson(Request $request)
  {
    $office_id=$request->session()->get('session_office');
    $id = Auth::user()->id;
    $seatid=$request->session()->get('session_seat');
    $inboxs = \App\File_forward::where('to_seat', $seatid)->with('file')->whereHas('file', function ($query) use($office_id) {  $query->where('office_id',$office_id)->where('status',1)->with('user','closedby'); })->orderBy('created_at','desc')->get();
    //dd($inboxs);
    $data  = [];
    $i=0;
    foreach ($inboxs as $inbox)
    {
      $id=$inbox->id;
      $fileno=$inbox->file->file_no;
      $fileid=$inbox->file->id;
      $priority=$inbox->file->priority;
      $createdby=$inbox->file->user->name;
      $confidential=$inbox->file->confidential;
      $prioritylabelobj=\App\Priority::where('id',$priority)->first();        
      $priority=$prioritylabelobj->priority;
      $date=$inbox->file->created_at->format('d-M-Y h-m-s');
      $title=$inbox->file->title;
      $refencenumber=$inbox->file->reference_number;
      $forwardedby=$inbox->from_seat;
      if(!$forwardedby)
        $forwardedby="Self Generated";
      else
      {
        $forwardseatobj=\App\Seat::where('id',$forwardedby)->first();
        $forwardedby=$forwardseatobj->seat_code."::".$forwardseatobj->seat_name;
      }
      $file_forward_toseat=$inbox->to_seat;
      $closedbyuser ="";
      $closed_by  ="";
      $closed_date ="";
      if($inbox->file->closed_by)
      {
        $closed_by = $inbox->file->closed_by;
        if($closed_by)
        {
            $closedbyuser = $inbox->file->closedby->name;
        }
        $closed_date = $inbox->file->closed_date;
        $closed_date = date("d-M-Y", strtotime($closed_date));
      }
      /////count of comments -- tapal/////////////////////
      $match_comments = [['file_id','=',$fileid],['comment_type','=',0]];
      $filecommentcount=\App\Comments::where($match_comments)->count();
      //////attached tapal comments in a file////////////
      $tapallinkcomment=0;
      $tapallinks = \App\File_reference::where('file_id', $fileid)->get();
      foreach ($tapallinks as $tapallink) 
      {
        $tapal_id_ref=$tapallink->tapal_id;
        $match_comments_tapal = [['tapal_id',$tapal_id_ref],['comment_type','=',0]];
        $tapal_comment =\App\Comments::where($match_comments_tapal)->count();
        $tapallinkcomment += $tapal_comment;
      }
      $total_comment_count = $tapallinkcomment + $filecommentcount;
      /////count of actions -- tapal/////////////////////
      $match_actions = [['file_id','=',$fileid]];
      $fileactioncount=\App\File_action::where($match_actions)->count();
      //////attached tapal actions in a file////////////
      $tapallinkactions=0;
      $tapallinks_actions = \App\File_reference::where('file_id', $fileid)->get();
      foreach ($tapallinks_actions as $tap_action_list) 
      {
        $tapal_id_ref_act=$tap_action_list->tapal_id;
        $tapal_action =\App\Tapal_action::where('tapal_id',$tapal_id_ref_act)->count();
        $tapallinkactions += $tapal_action;
      }
      $total_fileaction_count = ($tapallinkactions*1) + ($fileactioncount*1);
      /////count of attachments -- tapal/////////////////////
      $match_attachments = [['file_id','=',$fileid]];
      $fileattachmentcount=\App\Documents::where($match_attachments)->count();
      //////attached tapal actions in a file////////////
      $tapallinkattachments=0;
      $tapallinks_attachments = \App\File_reference::where('file_id', $fileid)->get();
      foreach ($tapallinks_attachments as $tap_attach_list) 
      {
         $tapal_id_ref_attach=$tap_attach_list->tapal_id;
         $tapal_attachment_count =\App\Documents::where('tapal_id',$tapal_id_ref_attach)->count();
         $tapallinkattachments += $tapal_attachment_count;
      }
      $total_fileattachment_count = ($tapallinkattachments*1) + ($fileattachmentcount*1);
      //////////////////////////////////////////
      $forwardedon=$inbox->created_at->format('d-M-Y');
      $fdate=new \DateTime($forwardedon);
      $cdate=new \DateTime();
      $diff='';
      $diff=date_diff($fdate,$cdate);
      $noofdays= $diff->format("%a days");
      $filegroup=$inbox->file->file_groupobj->file_group;
      $obj = new \stdClass;
      $obj->incid = $i + 1;
      $obj->id = $id;
      $obj->fileid = $fileid;
      $obj->file_no = $fileno;
      $obj->title = $title;
      $obj->created_at = $date;
      $obj->createdby = $createdby;
      $obj->confidential = $confidential;
      $obj->reference_number = $refencenumber;
      $obj->from_seat = $forwardedby;
      $obj->forwardedon = $forwardedon."(".$noofdays.")" ;
      $obj->file_group = $filegroup;
      $obj->priority = $priority;
      $obj->filecommentcount = $total_comment_count;
      $obj->fileactioncount = $total_fileaction_count;
      $obj->fileattachmentcount = $total_fileattachment_count;
      $obj->closedbyuser = $closedbyuser;
      $obj->closed_date = $closed_date;
      $data[$i] = $obj;
      $i++;
    }
    $fileinboxjson = collect($data);
    return Datatables::of($fileinboxjson)->make(true);
  } 

  public function closedmodalfileview($id,Request $request)
  {
      $office_id=$request->session()->get('session_office');
      $file_id= $id;
      $creation_of_file=\App\File::where('office_id',$office_id)->where('status',1)->where('id',$id)->with('user')->first();
      $file_no=$creation_of_file->file_no;
      $description=$creation_of_file->file_description;
      $confidential=$creation_of_file->confidential;
      $filecreateduser=$creation_of_file->user->name;
      $currentseatid=$request->session()->get('session_seat');
      $fileuserseat=\App\User_Seat::where('user_id',$creation_of_file->created_by)->with('seat')->first();
      $fileseat=$fileuserseat->seat->seat_name;

      $filedetailsarr =[];
      $i=0;
      $closedbyuser ="";
      $closed_by  ="";
      $closed_date ="";
      if($creation_of_file->closed_by)
      {
        $closed_by = $creation_of_file->closed_by;
        if($closed_by)
        {
            $closedbyuser = $creation_of_file->closedby->name;
        }
        $closed_date = $creation_of_file->closed_date;
        $closed_date = date("d-M-Y", strtotime($closed_date));
      }
      $filedetailsarr['closedbyuser']=$closedbyuser;
      $filedetailsarr['closed_date']=$closed_date;
      $filedetailsarr['id']=$file_id;
       $filedetailsarr['file_no']=' File No:'." ".$file_no."   " .$fileseat." : " .$filecreateduser;
       if($confidential==1)
       {
          $conf=', Confidential';
          $filedetailsarr['file_no']=' File No:'." ".$file_no."   " .$fileseat." : " .$filecreateduser .$conf;
       }
       $filedetailsarr['file_description']=$description;
       
       $filedetailsarr['title']=$creation_of_file->title;
      //dd($filedetailsarr);
       $filefrwrd=\App\File_forward::where('file_id',$file_id)->where('active_flag',1)->with('file')->first();
       $to_seat = $filefrwrd->to_seat;
       $createdby=$filefrwrd->file->user->name;
       $createdat=$filefrwrd->file->created_at->format('d-M-Y h-m-s');
       $forwardedon=$filefrwrd->created_at->format('d-M-Y h-m-s');
       $forwardedby=$filefrwrd->from_seat;
         if(!$forwardedby)
          $forwardedby="Self Generated";
        else
        {
          $forwardseatobj=\App\Seat::where('id',$forwardedby)->first();
          $forwardedby=$forwardseatobj->seat_code."::".$forwardseatobj->seat_name;
        
        }
        $filefrwrdupd=\App\File_forward::where('file_id',$file_id)->where('active_flag',1)->where('to_seat',$currentseatid)->first();
        if(isset($filefrwrdupd))
        {
            $filefrwrdupd->read_flag = 1;
            $filefrwrdupd->save();
        }
        $filedetailsarr['from_seat']=$forwardedby;
        $filedetailsarr['created_at']=$forwardedon;
        $filedetailsarr['name']=$createdby;
        $filedetailsarr['created_at']=$createdat;

        $filegroup =\App\File_Group::where('id',$creation_of_file->file_group_id)->first();
        $filegrp=$filegroup->file_group;
        $filedetailsarr['file_group']=$filegrp;

        

        $prio=App\Priority::where('id',$creation_of_file->priority)->first();
        $priority=$prio->priority;
        $filedetailsarr['priority']=$priority;

        $seatid=$request->session()->get('session_seat');
              $act_flg_status = 0;
              $match=[['to_seat',$seatid],['file_id',$id]];
              //print_r($match);
              $current_fileuser=\App\File_forward::where($match)->get();
              foreach($current_fileuser as $tapvallist)
              {
                $active_flag = $tapvallist->active_flag;
                if($active_flag == 1)
                {
                  $act_flg_status = 1;
                }

              }

              $filedetailsarr['active_flag']=$act_flg_status;

              $readflag="-1";
              $fromseat = \App\File_forward::where('from_seat', $seatid)->where('file_id',$id)->get();
              foreach ($fromseat as $togetseat) 
              {
                $toseat=$togetseat->to_seat;
                //dd($toseat);
                $readflag=$togetseat->read_flag;
                
                //dd($flagread);
              }
              $filedetailsarr['read_flag']=$readflag;

              $userid = Auth::user()->id;
              $user_comment_flag='';
              $file_comment_last = \App\Comments::where('file_id',$file_id)->orderBy('created_at','DESC')->first();
              if(isset($file_comment_last)!='')
              {
                  $userid_last_filecomment = $file_comment_last->updated_by;
                  if($userid_last_filecomment == $userid)
                  {
                      $user_comment_flag = 1;
                  }
              }
              else
              {
                  $user_comment_flag=0;
              }
              //$note="Forward button will be enabled,if alteast one note is entered by the current seat.";

              $filedetailsarr['user_comment_flag']=$user_comment_flag;
            

      $attachmentcount =\App\Documents::where('file_id',$file_id)->count();

      
      $i=0;
      $file_attchment =\App\Documents::where('file_id', $file_id)->get();
      $filedocstr='';
      foreach ($file_attchment as $tattachment) 
      {
         $file_documentname=$tattachment->document_name;
         $path=$tattachment->document_path;
         $file_attach_createdat=$tattachment->created_at->format('d-M-Y h:i:s');

         $filepath=storage_path('app/'.$path);
         $size='';
         if(file_exists($filepath)){
          $size=round(filesize($filepath)/1024,1);
         }
         
         if($file_documentname)
         {
            
            $filedocstr.= "<li><div class='mailbox-attachment-info'><a href='#' class='mailbox-attachment-name'><i class='fa fa-paperclip'></i> $file_documentname</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>";

            $i++;
         }
      }
      
      //tapal attachments
        $tapalattachmentscount=0;

        $tapalattachments_arr = \App\File_reference::where('file_id', $file_id)->with('tapal')->get();
        foreach ($tapalattachments_arr as $tapalattachment_arr)
        {

            $tapalid=$tapalattachment_arr->tapal_id;
            $tapalnumber = \App\Tapal::where('id', $tapalid)->first();
            $tapalno=$tapalnumber->tapal_no;

            $tapalattachmentscount = \App\Documents::where('tapal_id', $tapalid)->count();
            if($tapalattachmentscount > 0)
            {
              $tapalattachments[$tapalid] = \App\Documents::where('tapal_id', $tapalid)->with('tapal','user')->orderBy('created_at','DESC')->get();
              foreach ($tapalattachments[$tapalid] as $tplattachment) 
              {
                 $file_documentname=$tplattachment->document_name;
                 $path=$tplattachment->document_path;
                 $file_attach_createdat=$tplattachment->created_at->format('d-M-Y h:i:s');

                 $filepath=storage_path('app/'.$path);
                 if(file_exists($filepath)){
                  $size=round(filesize($filepath)/1024,1);
                 }
                 
                 if($file_documentname)
                 {
                    
                    $filedocstr.= "<li><div class='mailbox-attachment-info'><a href='#' class='mailbox-attachment-name'><i class='fa fa-paperclip'></i> $file_documentname&nbsp;&nbsp;$tapalno</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>";          
                 }
              }
            }
            
        }

          $filedetailsarr['document_path']=$filedocstr;


      $userid = Auth::user()->id;

      $comments_arr = \App\Comments::where('file_id', $file_id)->with('file','seat')->orderBy('created_at','DESC')->get();
  
       $commentstr ='';
       $comments_count = \App\Comments::where('file_id', $file_id)->with('file','seat')->count();
       if($comments_count==0)
       {
            $commentstr .= "<div class='box-comment'><div class='comment-text'><span class='username' id='nocomment'>&nbsp;<span class='text-muted pull-right'></span></span>No Comments added yet !!!</div></div>";
       }

      
      foreach ($comments_arr as $comments_list)
      {
          $created_at=$comments_list->created_at->format('d-M-Y');
          $fileid=$comments_list->file_id;
          $comment_type=$comments_list->comment_type;
          $comment_description=$comments_list->comment_description;
          $seatname=$comments_list->seat->seat_name;
          $commentseatid=$comments_list->seat_id;
          //dd($tapalid);
          $checkforseatmatch=\App\User_Seat::where('user_id',$userid)->where('seat_id',$commentseatid)->count();
          $currentseat=\App\User_Seat::where('user_id',$userid)->with('seat')->get();
        foreach ($currentseat as $userseat)
          {
            $currentuserseat=$userseat->seat_id;
            //dd($currentuserseat);
            $currentfileseat=\App\File_forward::where('file_id',$fileid)->where('active_flag',1)->first();
            //foreach ($currenttapalseat as $tapalseat)
            //{
            $seat=$currentfileseat->to_seat;
            // dd($seat);
            //}
            $seatflag=0;
            if($currentuserseat==$seat)
              {
                 $seatflag=1;
              }

          }


          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_file' id='creation_of_file' value='$fileid'><div class='comment-text'><span class='username'>$seatname posted Private Comment<span class='text-muted pull-right'>$created_at</span></span><font color='red'>$comment_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_file' id='creation_of_file' value='$fileid'><div class='comment-text'><span class='username'>$seatname posted Public Comment<span class='text-muted pull-right'>$created_at</span></span><font color='green'>$comment_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='file' id='file' value='$fileid'><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'>$comment_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> "; 
              }

            }
            
           
        }

        

        //dd($tapaldetailsarr);

        //tapal comments 
              $commentscount=0;
     
              $tapalcomments_arr = \App\File_reference::where('file_id', $file_id)->with('tapal')->get();
              foreach ($tapalcomments_arr as $tapalcomment_list)
               {

                  $tapalid=$tapalcomment_list->tapal_id;
                  $tapalno=$tapalcomment_list->tapal->tapal_no;

                  $commentscount += \App\Comments::where('tapal_id', $tapalid)->count();
                  if($commentscount > 0)
                   {
                      $comments[$tapalid] = \App\Comments::where('tapal_id', $tapalid)->with('tapal','seat')->orderBy('created_at','DESC')->get();
                      foreach ($comments[$tapalid] as $tapalcomment) 
                      {
                         $seatname=$tapalcomment->seat->seat_name;
                         $comment_description=$tapalcomment->comment_description;
                         $created_at=$tapalcomment->created_at->format('d-M-Y');
                         if(($tapalcomment->comment_type == 1) && ($tapalcomment->seat_id == $fileseat))
                         {
                            //<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_file' id='creation_of_file' value='$file_id'><div class='comment-text'><span class='username'>$seatname&nbsp;&nbsp;$tapalno<span class='text-muted pull-right'>$created_at</span></span><font color='red'>$comment_description</font></div></div>";
                         }

                         if($tapalcomment->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_file' id='creation_of_file' value='$file_id'><div class='comment-text'><span class='username'>$seatname&nbsp;&nbsp;$tapalno<span class='text-muted pull-right'>$created_at</span></span><font color='green'>$comment_description</font></div></div>";
                         }

                         if(($tapalcomment->comment_type == 2) && ($tapalcomment->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('filepostit_comment')."'  method='post' > <input type='hidden' name='_token' value=".csrf_token()."><input type='hidden' name='file' id='file' value='$file_id'><input type='hidden' name='comment_id' id='comment_id' value='$comments_list->id'><div class='comment-text'><span class='username'>$seatname&nbsp;&nbsp;$tapalno<span class='text-muted pull-right'>$created_at</span></span><font color='#ad890a'>$comment_description</font></div>";

                            if($act_flg_status==1)
                                {
                                  $commentstr .= "<button type='submit' class='btn btn-default btn-xm'> <span class='glyphicon glyphicon-trash'></span> Trash </button></form></div> "; 
                                }
                         }
                      }
                   }
               }

            $filedetailsarr['comment_description']=$commentstr;

            $actions_arr = \App\File_action::where('file_id', $id)->with('file','seat','action')->orderBy('created_at','DESC')->get();
 

            $actionstr ='';

              $action_count = \App\File_action::where('file_id', $id)->with('file','seat','action')->count();
             if($action_count==0)
             {
                  $actionstr .= "<div class='box-comment'><div class='comment-text'><span class='username'>&nbsp;<span class='text-muted pull-right'></span></span>No Actions added yet !!!</div></div>";
             }

            foreach ($actions_arr as $actions_list)
            {
                $created_at=$actions_list->created_at->format('d-M-Y');
                $fileid=$actions_list->id;
                $action_type=$actions_list->action->actions;
                $action_description=$actions_list->action_description;
                $seatname=$actions_list->seat->seat_name;
                //$actionseatid=$actions_list->seat_id;
                
               
                if($action_type) 
                {    
                  //<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>";
                  }


                 
              }  


              
              //tapal actions
              $tapalactionscount=0;
              // $checkforseatmatch=\App\User_Seat::where('user_id',$userid)->where('seat_id',$commentseatid)->count();
              $tapalactions_arr = \App\File_reference::where('file_id', $id)->with('tapal')->get();
              //dd($tapalactions_arr);
              foreach ($tapalactions_arr as $tapalactions_arrobj)
              {

                  $tapalid=$tapalactions_arrobj->tapal_id;
                  $tapalno=$tapalactions_arrobj->tapal->tapal_no;
                  $tapalactionscount += \App\Tapal_action::where('tapal_id', $tapalid)->count();
                  if($tapalactionscount > 0)
                  {
                      $tapalactions[$tapalid] = \App\Tapal_action::where('tapal_id', $tapalid)->with('tapal','seat','action')->orderBy('created_at','DESC')->get();
                      foreach ($tapalactions[$tapalid] as $tapalaction)
                      {
                         
                         $seatname=$tapalaction->seat->seat_name;
                         //$comment_description=$tapalaction->comment_description;
                         $action_description=$tapalaction->action_description;
                         $action_type=$tapalaction->action->actions;
                         $created_at=$tapalaction->created_at->format('d-M-Y');

                         if($action_type) 
                          {    
                            // /<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&nbsp;&nbsp;$tapalno<span class='text-muted pull-right'>$created_at</span></span>$action_description</div></div>";
                          }
                      }
                  }
              }
              
              $filedetailsarr['action_description']=$actionstr;





              $priorityfile=App\Priority::all();

              // tapal attached to this file///////////////
              

             

              
              //list of tapal attached to this file////////////////
              $linkstr ='';
              $tapallinkscount = '';
              $tapallinkscount = \App\File_reference::where('file_id', $id)->with('tapal','user')->count();
              if($tapallinkscount=='')
              {
                 $linkstr .= "<div class='box-comment'><div class='comment-text'><span class='username'>&nbsp;<span class='text-muted pull-right'></span></span>No Tapals attached yet !!!</div></div>";
              }
              $tapallinks = \App\File_reference::where('file_id', $id)->with('tapal','user')->get();
              foreach ($tapallinks as $tapallink) 
              {
                     $tapallinkuser=$tapallink->user->id;
                     $tapalno=$tapallink->tapal->tapal_no;
                     $createdat=$tapallink->created_at->format('d-m-Y H:i:s');
                     //$seat=$tapallink->tapal->seat->seat_name;
                     $tapallinkseat =\App\User_Seat::where('user_id',$tapallinkuser)->with('seat')->first();
                     $seat=$tapallinkseat->seat->seat_name;
                     $linkstr .= "<div class='box-comment'><div class='comment-text'><span class='username'>$tapalno&nbsp;attached to this file on&nbsp;$createdat&nbsp;by $seat</span></div></div>";
              }

              $filedetailsarr['link']=$linkstr;

              $tempstr='';
              $approveduser='';
              $ftemplate =\App\Fileview_template::where('file_id',$id)->where('cancel_flag',0)->with('template','user')->get();
              foreach ($ftemplate as $titledisp)
                {
                    $tempstr .="<tr ><td width='75%' >";

                    $fileviewtemplateid=$titledisp->id;
                    $title=$titledisp->template->title;
                    $name=$titledisp->user->name;
                    $created_at=$titledisp->created_at->format("d-m-Y H:i:s");

                    $tempstr .="<b>$title</b> last modified by $name on $created_at";


                    $fileviewtemplateapprovedby=$titledisp->approved_by;
                    if($fileviewtemplateapprovedby!=0)
                    {
                        $approveuser=\App\Models\User::where('id',$fileviewtemplateapprovedby)->first();
                        $approveduser=$approveuser->name;
                    }
                    $fileviewtemplatearr[$fileviewtemplateid]=$approveduser;
                    if($titledisp->approval_flag==1)
                    {
                      $tempstr .="approved by $approveduser";
                    }
                    $tempstr .="<br></td><td >";

                    if($titledisp->approval_flag==0)
                    {
                       $tempstr .="<button data-toggle='modal' data-target='#TemplateModal' class='btn btn-success pull-right btn-sm' type='button' onclick=getModaltemp('$fileviewtemplateid');>Edit this Document</button>";
                    }


                    if($titledisp->approval_flag==1)
                    {
                      $tempstr .="<button data-toggle='modal' data-target='#ApproveModal' class='btn btn-warning pull-right btn-sm' type='button' onclick=getApprovetemp('$fileviewtemplateid');>View this Document</button>";
                    }
                    
                    $tempstr .="</td></tr>";
                    
                } 

                $filedetailsarr['temp']=$tempstr;

                //dd($filedetailsarr);
               return $filedetailsarr;

  }

  public function reopenfile(Request $request)
  {
    $userid = Auth::user()->id;
    $seatid_new = $request->session()->get('session_seat');
    $id=$request->creation_of_file;
    $tapalseat = \App\File_forward::where('file_id',$id)->where('active_flag',1)->first();
    $tapaltoseat=$tapalseat->to_seat;
    $update_arr = \App\File::where('id',$id)->orderBy('id','desc')->first();
    //dd($update_arr);
    if(isset($update_arr))
    {
      $update_arr->status= 0;
      $update_arr->save();
    }
    return redirect()->route('fileinbox');
  }

  public function getchildseatsclosed($parent)
  {
    $childs=\App\Seat::where('reporting_seat',$parent)->get();
    foreach ($childs as $child) 
    {
      array_push($this->childarray,$child->id);
      $this->getchildseatsclosed($child->id);
    }
    return $this->childarray;
  }

}