<?php 
$req=$_REQUEST['req'];
$conreq=$_REQUEST['conreq'];
$asgnid=$_REQUEST['asgnid'];
$appoint=$_REQUEST['appoint'];

###### GET REQUEST ######
$stmtReq = $db->prepare('SELECT *FROM tbl_info_register i
INNER JOIN tbl_con_infos cn ON cn.reg_info_id=i.regst_id 
INNER JOIN tbl_clients c ON c.ct_id=i.clnt_id 
INNER JOIN tbl_reqs_type r ON r.reqtype_id=i.reqtype
WHERE cn.con_info_id="'.$conreq.'"');
$stmtReq->execute();
while($ffReq = $stmtReq->fetch()){
   $sub_matt=$ffReq['sub_matt'];

}
###### END GET REQ ######

#####GET ASSIGNED APPOINTMENT ####
$asgnQue=$db->prepare('SELECT *FROM tbl_assign_reqs a
INNER JOIN tbl_title t ON t.title_id=a.asgn_appoint 
WHERE assreq_id ="'.$asgnid.'"');
$asgnQue->execute();

$rr=$asgnQue->fetch();
$titlename=$rr['title_name'];
#####---END ASSIGNED APPOINTMENT ####

##### SUBMIT BOQ #####
if(isset($_REQUEST['confySubmit'])){
    $reqboq = $_REQUEST['reqboq'];
    $conb = $_REQUEST['conb'];
    $appoin = $_REQUEST['appoin'];
    $dept = $_REQUEST['dept'];
    $usrec = $_REQUEST['usrec'];
    $dt = date('Y-m-d');

    $upd = $db->prepare("UPDATE `tbl_boq_title` SET `sts_btle`=4,date_boq_cplte='".$dt."' WHERE req_tle='".$reqboq."' AND conbtle='".$conb."' 
    AND appointle='".$appoin."' AND sts_btle=8");
    $upd->execute();

    ######## UPDATE DATE NOTE ####
    $updNotes = $db->prepare("UPDATE `tbl_con_infos` SET info_sts=3 WHERE `con_info_id`='".$conb."'");
    $updNotes->execute();
    ######## END UPDATE DATE NOTE ####

    ######## UPDATE INFO ####
    $updinfo = $db->prepare("UPDATE `tbl_info_register` SET stts_reg=3 WHERE `regst_id`='".$reqboq."'");
    $updinfo->execute();
    ######## END INFO ####

    echo'<script type="text/javascript">
    jQuery(function validation(){
    swal("Successfully!", "BOQ Submitted.", "success", {
    button: "Continue",
    });
    });
</script>';

echo'<meta http-equiv="refresh"'.'content="2;URL=?home">'; 

}

##### NEW TITLE #####
if(isset($_REQUEST['btnBoqDIV'])){

    $req_div = $_REQUEST['req_div'];
    $conbdiv = $_REQUEST['conbdiv'];
    $appointdiv = $_REQUEST['appointdiv'];
    $dept_div = $_REQUEST['dept_div'];
    $usrec_div = $_REQUEST['usrec_div'];
    $boqtitle_id = $_REQUEST['boqtitle_id'];
    $compnt_id = $_REQUEST['compnt_id'];
    $boqdiv = $_REQUEST['boqdiv'];
    
    $duedtrm = date('Y-m-d H:i:s');
    $statement = $db->prepare("INSERT INTO tbl_boq_div(divtle_id, req_div, boqdiv_name, dv_cmpnt,conbdiv, trmDiv, appoidiv, dept_div,usrec_div,sts_bdiv)
    VALUES(?,?,?,?,?,?,?,?,?,?)");
    $statement->execute(array($boqtitle_id,$req_div,$boqdiv,$compnt_id,$conbdiv,$duedtrm,$appointdiv,$dept_div,$usrec_div,1));
    
    echo'<script type="text/javascript">
        jQuery(function validation(){
        swal("Successfully!", "New BOQ Components saved.", "success", {
        button: "Continue",
        });
        });
    </script>';
    
    }
?>

<div class="subheader">
    <h1 class="subheader-title" style="font-weight: bold;">
        <i class='subheader-icon fa fa-bars text-primary'></i><?php echo $title." by ".$titlename;?> 
    </h1>
</div>

<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">
                   Sub: <?php echo $sub_matt;?>
                </span>
                <div class="clearfix"></div>                  
            </div>
        </div>
    </div>

    <div class="card-body ">
    <br>
    
    <form method="post" action="save_gen_boq" id="save_gen_boq" enctype="multipart/form-data" autocomplete="off">
        
        <div class="form-group row">  
          <div class="col-sm-2"></div>

            <label class="col-md-1 col-form-label form-control-label">BOQ Title<span class="required" style="color:red">*</span></label>

            <div class="col-sm-2">
                <select class="select2 form-control w-100" name="boqttle" id="boqttle" data-placeholder="-select title-" required>
                    <option></option>
                        <?php
                            $sth1 = $db->query('SELECT * FROM tbl_boq_title WHERE req_tle="'.$req.'" AND sts_btle=8 ORDER BY btle_id DESC');
                            try
                            {
                                while ($rr1 = $sth1->fetch(PDO::FETCH_ASSOC)) {
                                ?>
                                    <option value="<?php echo $rr1['btle_id']; ?>"><?php echo $rr1['boqtitle_name']; ?></option>
                                <?php
                                }
                                }
                                catch (PDOException $ex) {
                                //Something went wrong rollback!
                                echo $ex->getMessage();
                            }
                        ?>	
                </select>
            </div>

            <div class="col-sm-1"></div>

            <label class="col-md-1 col-form-label form-control-label">BOQ Component<span class="required" style="color:red">*</span></label>
            <div class="col-sm-2">
                <select class="select2 form-control w-100" name="boqcomp" id="boqcomp" data-placeholder="-select component-"  onchange="mydiv(this.value)" required>
                    <option></option>
                        <?php
                            $sth1 = $db->query('SELECT * FROM tbl_boq_compnt WHERE req_cpnt="'.$req.'" AND sts_bcpnt=8 ORDER BY bcpnt_id DESC');
                            try
                            {
                                while ($rr1 = $sth1->fetch(PDO::FETCH_ASSOC)) {
                                ?>
                                    <option value="<?php echo $rr1['bcpnt_id']; ?>"><?php echo $rr1['boqcpnt_name']; ?></option>
                                <?php
                                }
                                }
                                catch (PDOException $ex) {
                                //Something went wrong rollback!
                                echo $ex->getMessage();
                            }
                        ?>	
                </select>
            </div>

        </div>

        <div class="form-group row">  

        <div class="col-sm-2"></div>
            <label class="col-md-1 col-form-label form-control-label">BOQ Division<span class="required" style="color:red">*</span></label>
            <div class="col-sm-2">
                <select class="select2 form-control w-100" name="boqdiv" id="boqdiv" data-placeholder="-select division-" required>
                    <option></option>                        
                </select>
            </div>
                      
            <div class="col-sm-1">
                <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addNewDiv" style="border-radius: 4px;">
                <i class="fa fa-pencil"></i></button>
            </div>

            <label class="col-md-1 col-form-label form-control-label">Elements<span class="required" style="color:red">*</span></label>
            <div class="col-sm-2">
                <select class="select2 form-control w-100" name="elem" id="elem" data-placeholder="-select element-"  onchange="myctg(this.value)"  required>
                    <option></option>
                        <?php
                            $sth = $db->query('SELECT * FROM tbl_elements WHERE stselem=1 ORDER BY elemid DESC');
                            try
                            {
                                while ($rr2 = $sth->fetch(PDO::FETCH_ASSOC)) {
                                ?>
                                    <option value="<?php echo $rr2['elemid']; ?>"><?php echo $rr2['elemName']; ?></option>
                                <?php
                                }
                                }
                                catch (PDOException $ex) {
                                //Something went wrong rollback!
                                echo $ex->getMessage();
                            }
                        ?>	
                </select>
            </div>        
        </div>

      <hr style="height:2px;border:none;color:#777;background-color:#777;">
        <br>

        <div class="form-group row">  
            <div class="col-md-1"></div>

            <label class="col-md-1 col-form-label form-control-label">CATEGORY<span class="required" style="color:red">*</span></label>            
            <div class="col-sm-2">
                <select class="select2 form-control w-100" name="ctgid" id="ctgid" style="width: 90%;" data-placeholder="- choose category -" onchange="myitem(this.value)" required>
                    <option></option>                   
                </select>
            </div>

            <label class="col-md-1 col-form-label form-control-label">Item name<span class="required" style="color:red">*</span></label>
            <div class="col-sm-2">
                <select class="select2 form-control w-100" name="item_id" id="item_id" style="width: 90%;" data-placeholder="- select item -" required>
                    <option></option>                
                </select>
            </div>
            
            <label class="col-md-1 col-form-label form-control-label">Qty<span class="required" style="color:red">*</span></label>
            <div class="col-sm-2">
                <input type="text" name="qty" placeholder="0.0" required style="width: 50%;">
            </div>

            <input type="hidden" name="boqreqst_id" value="<?php echo $req;?>" required>
            <input type="hidden" name="con_idboq" value="<?php echo $conreq;?>" required>

            <div class="col-sm-1">
                <button type="submit" class="btn btn-primary btn-sm" id="addbtn" style="border-radius: 4px;height: 25px;"><i class="fa fa-plus"></i></button>
            </div>

        </div>    
    </form>
    
    <br><br>
    <form action="trash_generate_boq" id="trash_generate_boq" method="post" enctype="multipart/form-data" autocomplete="off">

        <table class="table w-100" border="2" style="font-size: 11px;">
            <thead class="header bg-primary">
                <tr>
                    <th style="font-weight: bold;width: 5px;"></th>            
                    <th style="font-weight: bold;">DESCRIPTION</th>
                    <th class="text-right" style="font-weight: bold;">UNIT</th>
                    <th class="text-right" style="font-weight: bold;">QTY</th>
                    <th class="text-right" style="font-weight: bold;"> RATE (Rwf)</th>
                    <th class="text-right" style="font-weight: bold;">AMOUNT (RWF)</th>
                </tr>
            </thead>

            <tbody id="data"></tbody>                      
        </table>
    
        <div class="card-footer">
            <div class="d-flex align-items-center">
                <?php 
                if($sth1->rowCount()>0){
                ?>
                <span class="text-sm text-muted font-italic">
                    <a href="#" data-toggle="modal" data-target="#submitBoq" class="btn btn-default btn-sm" style="border-radius: 4px;" title="Submit BOQ">
                        <i class="fa fa-check" aria-hidden="true"></i> Submit BOQ
                    </a>

                    <button type="submit" class="btn btn-danger btn-sm" name="clear" style="border-radius: 4px;" title="Delete data">
                        <i class="fa fa-trash-o" aria-hidden="true"></i> Delete Item
                    </button>
                </span>
                <?php }?>
                <a href="gate?b=awaitboqd" class="flex-shrink-0 ml-auto" style="font-weight: bold;">Go back <i class="fa fa-mail-reply ml-2"></i> </a>
            </div>
        </div>
    </form>

<?php 
    include 'modal_subboq.php';
    include 'boq_div_modal.php';
?>

<script>
  	function myitem(data){
		const ajaxreq =new XMLHttpRequest();
		ajaxreq.open('GET','getVal?ctgid='+data,'TRUE');
		ajaxreq.send();
		ajaxreq.onreadystatechange= function(){

			if (ajaxreq.readyState== 4 && ajaxreq.status == 200) {

				document.getElementById('item_id').
				innerHTML = ajaxreq.responseText;
				// alert(data2);
			}
		}

	}

    function mydiv(data){
		const ajaxreq =new XMLHttpRequest();
		ajaxreq.open('GET','getVal?boqcomp='+data,'TRUE');
		ajaxreq.send();
		ajaxreq.onreadystatechange= function(){

			if (ajaxreq.readyState== 4 && ajaxreq.status == 200) {

				document.getElementById('boqdiv').
				innerHTML = ajaxreq.responseText;
				// alert(data2);
			}
		}

	}

    function myctg(data){
		const ajaxreq =new XMLHttpRequest();
		ajaxreq.open('GET','getVal?elem='+data,'TRUE');
		ajaxreq.send();
		ajaxreq.onreadystatechange= function(){

			if (ajaxreq.readyState== 4 && ajaxreq.status == 200) {

				document.getElementById('ctgid').
				innerHTML = ajaxreq.responseText;
				// alert(data2);
			}
		}

	}
</script>

<script>
//  SAVE ORDER
    $(document).ready(function(){
    displayData();
    $("#save_gen_boq").submit(function(e){
        e.preventDefault();

    var formdata = new FormData(this);
        $.ajax({
            url: "save_gen_boq",
            type: "POST",
            data: formdata,
            mimeTypes:"multipart/form-data",
            contentType: false,
            cache: false,
            processData: false,
            success: function(formData){
            // chkall(false);
            displayData();
            pop_up_request(formData);
            },error: function(){
                alert("okey");
            }
         });
      });
      
    // Notification  
    function pop_up_request(feedback) {
    jQuery(function validation(){
    swal("Well done! ", "Data saved successfully.", "success", {
    button: "ok",
      });
    });
    }
     
    //  TRASH ORDER
    $("#trash_generate_boq").submit(function(e){
        e.preventDefault();

        var formdata = new FormData(this);
        $.ajax({
            url: "trash_generate_boq",
            type: "POST",
            data: formdata,
            mimeTypes:"multipart/form-data",
            contentType: false,
            cache: false,
            processData: false,
            success: function(formData){
            // chkall(false);
            displayData();
            },error: function(){
                alert("okey");
            }
         });
      });
      
    
     //FETCH DATA
	function displayData(){
	$.ajax({
		type: 'POST',
		url: 'viewboq',
		data: {res: <?php echo $req;?>,con: <?php echo $conreq;?>,asgn: <?php echo $asgnid;?>,appoi:<?php echo $appoint;?>},
		success: function(data){
			$('#data').html(data)
		}
	});
	}
   });

</script>