

<?php 
    $pID = $_REQUEST['pID'];

    $stts = $db->prepare('SELECT *FROM tbl_projects p
    INNER JOIN tbl_clients c ON c.ct_id=p.clnt 
    WHERE projid="'.$pID.'"
    ORDER BY projid DESC');
    $stts->execute();
    while($rr = $stts->fetch()){
       $projid = $rr['projid'];
       $projname = $rr['projname'];
       $ctNames = $rr['ct_names'];
       $agreeMont = $rr['agreeMont'];
       $wrkp = $rr['wps'];
       if($rr['wt']==1){
        $wt="Applicable";
        $withTax=15;
       }else{
        $wt="Not Applicable";
        $withTax =0;
       } 

    #### FILES UPLOADS ####
    if(isset($_REQUEST['saveDocs'])){
        $todate = date('Y-m-d H:i:s');

        $userRec = $_REQUEST['userRec'];
        $recAppoint = $_REQUEST['recAppoint'];
        $Deptrec = $_REQUEST['Deptrec'];
        $proj = $_REQUEST['proj'];

        $stt = 1;
        ######## FILES UPLOAD #############
        $countfiles = count($_FILES['file']['name']);
    
        $totalFileUploaded = 0;
        for($i=0;$i<$countfiles;$i++){
        $stms_last = $db->prepare("SELECT doc_id FROM tbl_docs  ORDER BY doc_id DESC LIMIT 1");
            try {
                $stms_last->execute(array());
                $row_count_last = $stms_last->rowCount();
                if ($row_count_last > 0) {
                    $rows = $stms_last->fetch(PDO::FETCH_ASSOC);
                        $doc_id = $rows['doc_id']+1;
                }else{
                    $doc_id = 1;
                }
            }
            catch (PDOException $ex) {
            echo $ex->getMessage();
            } 
    
            
            $filename = $doc_id."_".$_FILES['file']['name'][$i];
    
            ## Location
            $location = $path_upload.$filename;
            $extension = pathinfo($location,PATHINFO_EXTENSION);
            $extension = strtolower($extension);
    
            ## File upload allowed extensions
            $valid_extensions = array("jpg","jpeg","png","pdf","doc","docx","xls","xlsx","ppt","pptx","zip","tar"."gz");
    
            $response = 0;
            ## Check file extension
            if(in_array(strtolower($extension), $valid_extensions)) {
                ## Upload file
                if(move_uploaded_file($_FILES['file']['tmp_name'][$i],$location)){
    
                    //    echo "file name : ".$filename."<br/>";
                $stmt2 = $db->prepare("INSERT INTO tbl_docs(rec_dpt,prjID,usID,docAppoint,docName,uploaded_on,stts_doc) VALUES(:rec_dpt,:prjID,:usID,:docAppoint,:docName,:uploaded_on,:stts_doc)");
                $stmt2->execute(array(':rec_dpt'=>$Deptrec,':prjID' => $proj, ':usID' => $userRec, ':docAppoint' => $recAppoint, ':docName' => $filename, ':uploaded_on' => $todate,':stts_doc'=>$stt));
                // end to insert tbl_doc
    
                        $totalFileUploaded++;
                }
            }
    
        }

        echo'<script type="text/javascript">
        jQuery(function validation(){
        swal("File(s) saved", "Successfully", "success", {
        button: "Continue",
        });
        });
        </script>';
    
    }
    
    ###### INVOICE #####
    $invce = $db->query('SELECT SUM(invceMont) AS totInv FROM tbl_invoices WHERE projInv="'.$pID.'" AND stsinvce=1 AND invtpe=1');
    $invce->execute();
    $ffinv = $invce->fetch();
    $totInv = $ffinv['totInv'];

    ###### PO #####
    $invce2 = $db->query('SELECT SUM(invceMont) AS totInv FROM tbl_invoices WHERE projInv="'.$pID.'" AND stsinvce=1 AND invtpe=2');
    $invce2->execute();
    $ffinv2 = $invce2->fetch();
    $totInv2 = $ffinv2['totInv'];

    $totPercent = $totInv*100/$agreeMont;
    $perFin = number_format($totPercent, 0, '.', '' );

    ###### PAYMENT #####
    $pymt = $db->query('SELECT SUM(payMont) AS totPymt FROM tbl_payments WHERE projPay="'.$pID.'" AND pmtSts=1 AND paytpe=1');
    $pymt->execute();
    $ffpmt = $pymt->fetch();
    $totPmnt = $ffpmt['totPymt'];

    ###### PAYABLES #####
    $pymt2 = $db->query('SELECT SUM(payMont) AS totPymt FROM tbl_payments WHERE projPay="'.$pID.'" AND pmtSts=1 AND paytpe=2');
    $pymt2->execute();
    $ffpmt2 = $pymt2->fetch();
    $totPmnt2 = $ffpmt2['totPymt'];

    ##### WITH TAX #####
    $totWtax = $agreeMont*$withTax/100;
    $PaidWtax = $totPmnt*$withTax/100;

    ####### UPDATE PROJ #######
    if(isset($_REQUEST['updProj'])){
        $clnt = $_REQUEST['clnt'];
        $agreeno = $_REQUEST['agreeno'];
        $prjname = $_REQUEST['prjname'];
        $agree_mont = str_replace(',', '', $_REQUEST['agree_mont']);
        $signdate = $_REQUEST['signdate'];
        $start_date = $_REQUEST['start_date'];
        $withtax = $_REQUEST['withtax'];
        $durat = $_REQUEST['durat']; 

        $projid = $_REQUEST['projid'];

        $sql = "UPDATE tbl_projects SET aggreno=?, projname=?, wt=?, clnt=?, agreeMont=?, signdate=?, startDue=?, durat=? WHERE projid=?";
        $stmt= $db->prepare($sql);
        $stmt->execute([$agreeno, $prjname, $withtax, $clnt, $agree_mont, $signdate, $start_date, $durat, $projid]);
        if($stmt){
            echo'<script type="text/javascript">
            jQuery(function validation(){
            swal("Successfully", "Project updated well", "success", {
            button: "Continue",
            });
            });
            </script>';
        }
        
       echo'<meta http-equiv="refresh"'.'content="2;URL=">'; 
    }
?>

<div class="card mb-g border shadow-0">
    <div class="card-header bg-white p-0 header">
        <div class="p-3 d-flex flex-row">
            <div class="d-block ml-2">
                <span class="h6 font-weight-bold text-uppercase d-block m-0">
                   Project Box
                </span>

                <div class="d-flex mr-4">
                    <li class="position-absolute pos-top pos-right d-none d-sm-block"  style="padding: 10px;">
                     <a href="gate?b=pj" class="flex-shrink-0 ml-auto" style="font-weight: bold;">Go back <i class="fa fa-mail-reply ml-2"></i> </a>
                    </li>
                </div>

                <div class="clearfix"></div>  
            </div>
        </div>
    </div>

    <div class="card-body ">

    <div class="d-flex align-items-center pl-2 pr-3 py-3 pl-sm-3 pr-sm-4 py-sm-4 px-lg-5 py-lg-3 flex-shrink-0">
        <!-- button for mobile -->
        <a href="javascript:void(0);" class="pl-3 pr-3 py-2 d-flex d-lg-none align-items-center justify-content-center mr-2 btn" 
        data-action="toggle" data-class="slide-on-mobile-left-show" data-target="#js-inbox-menu">
            <i class="fa fa-ellipsis-v h1 mb-0 "></i>
        </a>
        <!-- end button for mobile -->
        <h3 class="subheader-title mb-0 ml-2 ml-lg-5">
        <b><i>PROJECT: <?php echo $projname;?></i></b>
        </h3>
        
        <div class="d-flex position-relative ml-auto">
            <a href="javascript:void(0);" class="btn btn-default btn-xs ml-1 fs-lg" data-toggle="modal" data-target="#default-example-modal-sm-center">
                <i class="fa fa-paperclip" aria-hidden="true"></i> My Docs
            </a>
        </div>
    </div>
    <!-- end inbox title -->

    <!-- message -->
    <div id="msg-03" class="d-flex flex-column border-faded border-top-0 border-left-0 border-right-0 py-3 px-3 px-sm-4 px-lg-0 mr-0 mr-lg-5 flex-shrink-0">
        <div class="d-flex align-items-center flex-row">
            <div class="ml-0 mr-3 mx-lg-3 width-2">   
            <?php 
            if($role_id==2 || $role_id==3){ 
            ?>      
            <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#pjUpdate_<?php echo $projid;?>" style="border-radius: 4px;">
                <i class="fa fa-pencil"></i>
            </button>     
            <?php }?>
            </div>
            <div class="fw-500 flex-1 d-flex flex-column cursor-pointer" data-toggle="collapse" data-target="#msg-03 > .js-collapse">
                <div class="fs-lg">
                    <?php echo $rr['codeproj'];?>
                    <span class="fs-nano fw-400 ml-2"><?php echo $rr['aggreno'];?></span>
                </div>
                <div class="fs-nano">
                    <b>Client:</b>  <?php echo $ctNames;?>
                </div>
            </div>

            <div class="collapsed-reveal">
                <a href="javascript:void(0);" class="btn btn-icon ml-1 fs-lg rounded-circle">
                    <i class="fa fa-reply"></i>
                </a>
            </div>
        </div>
        
        <div id="js-msg-1" class="js-collapse">
            <div class="pl-lg-5 ml-lg-5 pt-3 pb-4 ">
                
            <div class="row">
                <div class="col-sm-4 d-flex">
                    <div class="table-responsive">
                        <table class="table table-clean table-sm align-self-end">
                            <tbody>
                                <tr>
                                    <td>
                                    <b>Signed Date:</b>
                                    </td>
                                    <td>
                                        <?php echo date('d/m/Y', strtotime($rr['signdate']));?>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <b>Starting Date:</b>
                                    </td>
                                    <td>
                                        <?php echo date('d/m/Y', strtotime($rr['startDue']));?>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <b>Duration:</b>
                                    </td>
                                    <td>
                                        <?php echo $rr['durat']." Months";?>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <b>WithHolding Tax:</b>
                                    </td>
                                    <td>
                                        <?php echo $wt;?>
                                    </td>
                                </tr>
                                <tr>
                                    <td><b>Physical Progress</b></td>
                                    <td> 
                                        <div class="demo js-progress-animated">
                                            <div class="progress progress-lg">
                                                <div class="progress-bar progress-bar-striped bg-primary-500" role="progressbar" style="color: #000;font-weight: bold;width: <?php echo $wrkp;?>%" aria-valuenow="<?php echo $wrkp;?>" aria-valuemin="0" aria-valuemax="100"><?php echo $wrkp;?>%</div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>

                                <tr>
                                    <td><b>Financial Progress</b></td>
                                    <td> 
                                    <div class="demo js-progress-animated">
                                        <div class="progress progress-lg">
                                            <div class="progress-bar progress-bar-striped bg-primary-500" role="progressbar" style="color: #000;font-weight: bold;width: <?php echo $perFin;?>%" aria-valuenow="<?php echo $perFin;?>" aria-valuemin="0" aria-valuemax="100"><?php echo $perFin;?>%</div>
                                        </div>
                                    </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="col-sm-4 ml-sm-auto">
                    <div class="table-responsive">
                        <table class="table table-sm table-clean text-right">
                            <tbody>
                                <tr>
                                    <td>
                                        <b>Progress History:</b>
                                    </td>
                                </tr>
                               <?php 
                               $wpQue=$db->prepare('SELECT *FROM tbl_work_progress WHERE prj_progress="'. $projid.'" ORDER BY workp_id DESC');
                               $wpQue->execute();
                               while($fff=$wpQue->fetch()){
                               ?>
                                <tr>
                                    <td>
                                        <b><?php echo date('d/m/Y',strtotime($fff['dueprogress']));?></b>
                                    </td>

                                    <td>
                                        <b><?php echo $fff['wrkp_num']." %";?></b>
                                    </td>
                                </tr>
                                <?php }?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-sm-12">
                    <div class="table-responsive">

                        <table class="table mt-5">

                            <thead class="bg-primary-500">
                                <tr>                                            
                                    <th class="border-top-0 table-scale-border-bottom fw-700">Financial Status</th>
                                    <th class="border-top-0 table-scale-border-bottom fw-700">Amount</th>
                                </tr>
                            </thead>

                            <tbody>  
                                                              
                                <tr class="beam-dir">
                                    <td class="text-left">Agreement Amount</td>
                                    <td class="text-left b"><?php echo number_format($agreeMont);?></td>
                                </tr>
                                
                                <tr class="beam-dir">
                                    <td class="text-left">Total WithHolding Tax</td>
                                    <td class="text-left b"><?php echo number_format($totWtax);?></td>
                                </tr>

                                <tr class="beam-dir">
                                    <td class="text-left">Invoice Amount(s)</td>
                                    <td class="text-left b"><?php echo number_format($totInv);?></td>
                                </tr>

                                <tr class="beam-dir">
                                    <td class="text-left">Received Amount(s)</td>
                                    <td class="text-left b"><?php echo number_format($totPmnt);?></td>
                                </tr>

                                <tr class="beam-dir">
                                    <td class="text-left">Expense(s)</td>
                                    <td class="text-left b"><?php echo number_format($totPmnt2);?></td>
                                </tr>
                                
                                <tr class="beam-dir">
                                    <td class="text-left">Paid Tax</td>
                                    <td class="text-left b"><?php echo number_format($PaidWtax);?></td>
                                </tr>

                                <tr class="beam-dir">
                                    <td class="fw-700">Remaining Amount</td>
                                    <td class="fw-700"><?php echo number_format($agreeMont-$totPmnt);?></td>
                                </tr>

                            </tbody>
                        </table>

                    </div>
                </div>
            </div>
           
            </div>

            <div class="row">
            <?php 
                $i=0;
                if($role_id==2 || $role_id==3 || $role_id==9 || $role_id==15){
                $select = $db->prepare("SELECT * FROM `tbl_docs` WHERE prjID = '".$pID."' ORDER BY doc_id DESC"); 
                }else{                       
                $select = $db->prepare("SELECT * FROM `tbl_docs` WHERE prjID='".$pID."' AND rec_dpt='".$role_id."' ORDER BY doc_id DESC");
                }                       
                $select->execute(); 
                while($row = $select->fetch()){
                    $doc_id = $row['doc_id'];
                    $uploaded_on = $row['uploaded_on'];
                    $docName = $row['docName'];
                    $rec_dpt = $row['rec_dpt'];
                    $usID = $row['usID'];
                    $stts_doc = $row['stts_doc'];
                    $i++;
                    
                    //Hide Extension
                    $file = new SplFileInfo($docName);
                    $ext  = $file->getExtension();
                    //Get File Name
                    $fileName = basename($docName);
                    $fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $fileName);

                    //DOC ICON
                    if($ext == "pdf"){
                        $imgIcon = "pdf.png";
                    }if($ext == 'xls' || $ext == 'xlsx'){
                        $imgIcon = "excel.png";  
                    }if($ext == 'doc' || $ext == 'docx'){
                        $imgIcon = "docx.png";
                    }if($ext == 'ppt' || $ext == 'pptx'){
                        $imgIcon = "pptx.png";
                    }

                    
                    ####### DEPARTMENT #####
                    $dept = $db->prepare('SELECT *FROM tbl_role WHERE role_id = "'.$rec_dpt.'"');
                    $dept->execute();
                    $fDept = $dept->fetch();
                    $role_name = $fDept['role_name'];
                    
                    ###### USER #####
                    
                    $getUser = $db->prepare('SELECT *FROM tbl_user_accounts WHERE user_id = "'.$usID.'"');
                    $getUser->execute();
                    $fUs = $getUser->fetch();
                    $ffirst = $fUs['first_name'];
                    $fLst = $fUs['family_name'];
            ?>
                <div class="col-md-offset-2 col-md-2">
                        <div class="panel panel-default bootcards-file">
                            <div class="list-group">
                                <div class="list-group-item">
                                    <a href="../docs/<?php echo $docName;?>">
                                    <img src="../img/icon/<?php echo $imgIcon;?>" width="100">
                                    </a>
                                    
                                    <p class="list-group-item-text"><b>
                                        <a href="../docs/<?php echo $docName;?>" style="color: #777;">
                                            <?php echo $fileNameNoExtension;?>
                                        </a>
                                        </b></p>
                                </div>
                            </div>

                    </div>
                </div>

                <?php  
                    }
                ?>
            </div>
        </div>
    </div>

<!-- end message -->
</div>

</div>
<!-- End row -->
       

<?php
  include 'modalattach.php';
  include 'updproj.php';
?>

<?php 
  }
?>
      
      
<script>
 $(document).ready(function(){
    //apply on typing and focus
  $('#agree_mont').on('blur',function(){
       $(this).manageCommas();
    });
  $('#agree_mont').on('focus',function(){
        $(this).santizeCommas();
    });
  });

  String.prototype.addComma = function() {
    return this.replace(/(.)(?=(.{3})+$)/g,"$1,").replace(',.', '.');
  }
  //Jquery global extension method
  $.fn.manageCommas = function () {
      return this.each(function () {
          $(this).val($(this).val().replace(/(,|)/g,'').addComma());
      });
  }

  $.fn.santizeCommas = function() {
    return $(this).val($(this).val().replace(/(,| )/g,''));
  }   
</script>
