<?php
require_once("../includes/config.php");
$arrstatus = getFullStatus("", $link1);
/////////check approval is applicable or not
$apply_app = getAnyDetails(base64_decode($_REQUEST['pid']), "apply_approval", "tabid", "tab_master", $link1);
$docid = base64_decode($_REQUEST['id']);
//// stock conversion details
$sql_locdet = "SELECT * FROM stock_conversion_master where system_ref_no='".$docid."'";
$res_locdet = mysqli_query($link1, $sql_locdet);
$row_locdet = mysqli_fetch_assoc($res_locdet);
$stock = explode(' ', $row_locdet['conversion_type']);
if ($stock[0] == 'Fresh') {
	$select_field = "ok_qty";
} else if ($stock[0] == 'Damag') {
    $select_field = "damage_qty";
}
////// final submit form ////
@extract($_POST);
if (isset($_POST['appsave']) || isset($_POST['rejsave'])) {
    // print_r($_POST);die;
    mysqli_autocommit($link1, false);
    $flag = true;
    $err_msg = "";
    /////if user hit approve button
    if ($_POST['appsave'] == "Approve") {
        ////// entry in approval activity table and we take status 4 as approved from status master
        $flag = approvalActivity($docid, "STOCK CONVERSION", $row_locdet['entry_date'], $row_locdet['status'], $_SESSION['userid'], "4", $remark, $ip, $link1, $flag);
        /////////////// update status active(1) in stock_conversion_master ////////////////////////////////////////
        $upd_status = "update stock_conversion_master set status='4' where system_ref_no='" . $docid . "'";
        $result = mysqli_query($link1, $upd_status);
        //// check if query is not executed
        if (!$result) {
            $flag = false;
            $err_msg = "Error Code1: " . mysqli_error($link1);
        }
        // insert model qty detail in inventory stock table \\
        $c = count($_POST['conver_qty']);
        for ($i = 0; $i < $c; $i++) {
            $item = $_POST['partcode'][$i];
            $qty = $_POST['conver_qty'][$i];
			$stk_out = "";
			$stk_in = "";
            if ($_POST['check_stock'] == 'ok_qty') {
               $stk_out = "OK";
			   $stk_in = "DAMAGE";
                $req_res2 = mysqli_query($link1, "UPDATE inventory_status set ok_qty = ok_qty-$qty,damage_qty = damage_qty+$qty where partcode='" . $item . "' and location_code='" . $_POST['location'] . "'");
            } else if ($_POST['check_stock'] == 'damage_qty') {
                $stk_out = "DAMAGE";
			    $stk_in = "OK";
                $req_res2 = mysqli_query($link1, "UPDATE inventory_status set ok_qty = ok_qty+$qty,damage_qty = damage_qty-$qty where partcode='" . $item . "' and location_code='" . $_POST['location'] . "'");
            }
            //// check if query is not executed
            if (!$req_res2) {
                $flag = false;
                $err_msg = "Error Code2: " . mysqli_error($link1);
            }
            ////// insert in stock ledger table////               
            $result = stockLedger($docid, $row_locdet['entry_date'], $item, $_POST['location'], "", "OUT", $stk_out, $row_locdet['conversion_type'], "ADD", $qty, "0.00", $_SESSION['userid'], $today, $currtime, $ip, $link1, $flag);
            $result = stockLedger($docid, $row_locdet['entry_date'], $item, $_POST['location'], "", "IN", $stk_in, $row_locdet['conversion_type'], "ADD", $qty, "0.00", $_SESSION['userid'], $today, $currtime, $ip, $link1, $flag);
            $expld = explode("~", $result);
            $flag = $expld[0];
            $err_msg = $expld[1];
        }
        ////// insert in activity table////
        $flag = dailyActivity($_SESSION['userid'], $docid, "STOCK CONVERSION", "APPROVE", $ip, $link1, $flag);
        ///// check both master and data query are successfully executed
        if ($flag) {
            mysqli_commit($link1);
            $msg = "You have taken Approve action for STOCK CONVERSION REQUEST " . $docid;
            $cflag = "success";
            $cmsg = "Success";
        } else {
            mysqli_rollback($link1);
            $msg = "Request could not be processed " . $err_msg . ". Please try again.";
            $cflag = "danger";
            $cmsg = "Failed";
        }
    } else if ($_POST['rejsave'] == "Reject") {
        ////// entry in approval activity table and we take status 5 as reject from status master
        $flag = approvalActivity($docid, "STOCK CONVERSION", $row_locdet['entry_date'], $row_locdet['status'], $_SESSION['userid'], "5", $remark, $ip, $link1, $flag);
        /////////////// update status active(1) in request_production_p ////////////////////////////////////////
        $upd_status = "update stock_conversion_master set status='5' where system_ref_no='" . $docid . "'";
        $result = mysqli_query($link1, $upd_status);
        ////// insert in activity table////
        $flag = dailyActivity($_SESSION['userid'], $docid, "STOCK CONVERSION", "REJECT", $ip, $link1, $flag);
        ////// return message
        if ($flag) {
            mysqli_commit($link1);
            $msg = "You have taken Reject action for STOCK CONVERSION REQUEST " . $docid;
            $cflag = "success";
            $cmsg = "Success";
        } else {
            mysqli_rollback($link1);
            $msg = "Request could not be processed " . $err_msg . ". Please try again.";
            $cflag = "danger";
            $cmsg = "Failed";
        }
    } else {
        ///// nothing to do
        ////// return message
        $msg = "Something went wrong. Please try again.";
        $cflag = "danger";
        $cmsg = "Failed";
    }
    ///// move to parent page
    header("Location:stock_conversion_list.php?msg=" . $msg . "&chkflag=" . $cflag . "&chkmsg=" . $cmsg . "" . $pagenav);
    exit;
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>
            <?= siteTitle ?>
        </title>
        <link rel="shortcut icon" href="../images/titleimg.png" type="image/png">
        <script src="../js/jquery.js"></script>
        <?php
        include("../includes/fontawesome.html");
        include("../includes/main_css.html");
        include("../includes/bootstrap.html");
        include("../includes/datatables.html");
        ?>
        <script>
            $(document).ready(function () {
                var spinner = $('#loader');
                $("#frm1").validate({
                    ccc: function (form) {
                        if (!this.wasSent) {
                            this.wasSent = true;
                            $(':submit', form).val('Please wait...')
                                    .attr('disabled', 'disabled')
                                    .addClass('disabled');
                            spinner.show();
                            form.submit();
                        } else {
                            return false;
                        }
                    }
                });
            });
        </script>
        <script type="text/javascript" src="../js/jquery.validate.js"></script>
        <link href="../css/loader.css" rel="stylesheet"/>
    </head>
    <body>
        <div class="container-fluid">
            <div class="row content">
                <?php
                include("../includes/leftnav_admin.php");
                ?>
                <div class="<?= $screenwidth ?>">
                    <h2 align="center"><i class="fa <?= $fa_icon ?>"></i> Stock Conversion Approvel</h2>
                    <h4 align="center"><?php echo "( " . $row_locdet['system_ref_no'] . " )"; ?></h4>
                    <div class="form-group"  id="page-wrap" style="margin-left:10px;" >
                        <form id="frm1" name="frm1" class="form-horizontal" action="" method="post">
                            <div class="panel-group">
                                <div class="panel panel-success table-responsive">
                                    <div class="panel-heading"><i class="fa fa-newspaper-o fa-lg"></i>&nbsp;&nbsp;Stock Conversion Details</div>
                                    <div class="panel-body">
                                        <table class="table table-bordered" width="100%">
                                            <tbody>
                                                <tr>
                                                    <td width="20%"><label class="control-label">Location</label></td>
                                                    <td width="30%"><?= getAnyDetails($row_locdet['location_code'], "locationname", "location_code", "location_master", $link1) . " (" . $row_locdet['location_code'] . ")"; ?>
                                                        <input type="hidden" name="location" id="location" value="<?= $row_locdet['location_code'] ?>"/></td>
                                                    <td width="20%"><label class="control-label">Conversion Type</label></td>
                                                    <td width="30%"><?= $row_locdet['conversion_type']; ?>
                                                        <input type="hidden" name="check_stock" id="check_stock" value="<?= $select_field ?>"/></td>
                                                </tr>
                                                <tr>
                                                    <td width="20%"><label class="control-label">Status</label></td>
                                                    <td width="30%"><?= $arrstatus[$row_locdet['status']] ?></td>
                                                    <td width="20%"><label class="control-label">Remark</label></td>
                                                    <td width="30%"><?= $row_locdet['remark']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td width="20%"><label class="control-label">Create By</label></td>
                                                    <td width="30%"><?= getAnyDetails($row_locdet['entry_by'], "name", "username", "admin_users", $link1) ?></td>
                                                    <td width="20%"><label class="control-label">Create Date</label></td>
                                                    <td width="30%"><?= dt_format($row_locdet['entry_date']) . " | " . time_format($row_locdet['entry_time']) ?></td>
                                                </tr>
                                                <?php
                                                if ($apply_app == "Y") {
                                                    $row_app = mysqli_fetch_assoc(mysqli_query($link1, "select action_by,action_taken,action_date,action_remark from  approval_activity where ref_no='" . $docid . "'"));
                                                    if ($row_app['action_by'] != '') {
                                                        ?>
                                                        <tr>
                                                            <td width="20%"><label class="control-label">Approval By</label></td>
                                                            <td width="30%"><?= getAnyDetails($row_app['action_by'], "name", "username", "admin_users", $link1) ?></td>
                                                            <td width="20%"><label class="control-label">Approval Date</label></td>
                                                            <td width="30%"><?= dt_format($row_app['action_date']) ?></td>
                                                        </tr>
                                                        <tr>
                                                            <td width="20%"><label class="control-label">Approval Action</label></td>
                                                            <td width="30%"><?= !empty($arrstatus[$row_app['action_taken']]) ?></td>
                                                            <td width="20%"><label class="control-label">Approval Remark</label></td>
                                                            <td width="30%"><?= $row_app['action_remark'] ?></td>
                                                        </tr>
                                                        <?php
                                                    }
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div><!--close panel body-->
                                </div><!--close panel-->
                                <div class="panel panel-success table-responsive">
                                    <div class="panel-heading"><i class="fa fa-cubes fa-lg"></i>&nbsp;&nbsp;Stock Conversion Part Details</div>
                                    <div class="panel-body">
                                        <table class="table table-bordered" width="100%">
                                            <thead>
                                                <tr class="<?= $tableheadcolor ?>">
                                                    <th width="35%">Part Name</th>
                                                    <th width="10%">Available Stock</th>
                                                    <th width="10%">Conversion Qty</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $i = 0;
                                                /// select stock conversion part wise data table info
                                                $res = mysqli_query($link1, "SELECT * FROM stock_conversion_data where system_ref_no='" . $docid . "'");
                                                while ($row = mysqli_fetch_assoc($res)) {

                                                    $query = "SELECT " . $select_field . " from inventory_status where location_code='" . $row_locdet['location_code'] . "' and partcode='" . $row['partcode'] . "'";
                                                    $res1 = mysqli_query($link1, $query);
                                                    $row1 = mysqli_fetch_array($res1);
                                                    ?>
                                                    <tr>
                                                        <td><?= getAnyDetails($row['partcode'], "part_name", "partcode", "partcode_master", $link1) . " (" . $row['partcode'] . ")"; ?>
                                                            <input type="hidden" name="partcode[<?= $i ?>]" id="partcode[<?= $i ?>]" value="<?= $row['partcode'] ?>"/></td>
                                                        <td align="right"><?= $row1[$select_field]; ?>
                                                            <input type="hidden" name="avail_qty[<?= $i ?>]" id="avail_qty[<?= $i ?>]" value="<?= $row1[$select_field] ?>"/></td>
                                                        <td align="right"><?= $row['qty'] ?>
                                                            <input type="hidden" name="conver_qty[<?= $i ?>]" id="conver_qty[<?= $i ?>]" value="<?= $row['qty'] ?>"/>
                                                        </td>
                                                    </tr>
                                                    <?php $i++;
                                                }
                                                ?> 
                                            </tbody>
                                        </table>
                                    </div><!--close panel body-->
                                </div><!--close panel--> 
                                <div class="panel panel-success table-responsive">
                                    <div class="panel-heading"><i class="fa fa-id-card fa-lg"></i>&nbsp;&nbsp;Action</div>
                                    <div class="panel-body">
                                        <table class="table table-bordered" width="100%">
                                            <tbody>
                                                <tr>
                                                    <td align="right"><label class="control-label">Remark</label></td>
                                                    <td><textarea name="remark" id="remark" required class="required form-control addressfield" ></textarea></td>
                                                </tr>
                                                <tr>
                                                    <td align="center" colspan="2">
                                                        <button class='btn<?= $btncolor ?>' id="app" type="submit" name="appsave" value="Approve"><i class="fa fa-check-circle fa-lg"></i>&nbsp;&nbsp;Approve</button>
                                                        <button class='btn btn-danger' id="reject" type="submit" name="rejsave" value="Reject"><i class="fa fa-times-circle fa-lg"></i>&nbsp;&nbsp;Reject</button>
                                                        <button title="Back" type="button" class="btn<?= $btncolor ?>" onClick="window.location.href = 'stock_conversion_list.php?location=<?php
                                                        if (isset($_REQUEST['location'])) {
                                                            echo $_REQUEST['location'];
                                                        }
                                                        ?>&stock_type=<?php
                                                        if (isset($_REQUEST['stock_type'])) {
                                                            echo $_REQUEST['stock_type'];
                                                        }
                                                        ?>&daterange=<?php
                                                        if (isset($_REQUEST['daterange'])) {
                                                            echo $_REQUEST['daterange'];
                                                        }
                                                        ?><?= $pagenav ?>'"><i class="fa fa-reply fa-lg"></i>&nbsp;&nbsp;Back</button>                 </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div><!--close panel body-->
                                </div><!--close panel-->
                            </div><!--close panel group-->
                        </form>
                    </div>
                    <!--End form group--> 
                </div>
                <!--End col-sm-9--> 
            </div>
            <!--End row content--> 
        </div>
        <!--End container fluid-->
        <div id="loader"></div>
        <?php
        include("../includes/footer.php");
        include("../includes/connection_close.php");
        ?>
    </body>
</html>
