<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

if (isset($_POST) && !empty($_GET['delete'])) {
    $dataP['deleted'] = 1;
    ProductSetup::UpdateProductSetup($_GET['delete'],$dataP);
    header("Location: " . PROJECT_ADMIN_URL . "packaging_cost.php?view");
    exit();
}

// Initialize variables
$id = $name = $weight = $pcs_per_ctn = $pollybag_pcs_per_kg = $pollybag_rate_per_kg = "";
$pollybag_rate_per_pc = $carton_rate = $carton_pack_cost = $total_cost = "";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>

</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Packaging Cost</h3>
            </div>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="?add">Add <i
                            class="mdi-content-add-box" style="font-size:12px;"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
            if (isset($_GET['add'])) {
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                 $data['name'] = $name;
        $data['weight'] = $weight;
        $data['pcs_per_ctn'] = $pcs_per_ctn;
        $data['pollybag_pcs_per_kg'] = $pollybag_pcs_per_kg;
        $data['pollybag_rate_per_kg'] = $pollybag_rate_per_kg;

        // Calculate auto fields
        $data['pollybag_rate_per_pc'] = ($pollybag_pcs_per_kg > 0) ? ($pollybag_rate_per_kg / $pollybag_pcs_per_kg) : 0;
        $data['carton_rate'] = $carton_rate;
        $data['carton_pack_cost'] = ($pcs_per_ctn > 0) ? ($carton_rate / $pcs_per_ctn) : 0;
        $data['total_cost'] = $data['pollybag_rate_per_pc'] + $data['carton_pack_cost'];

        $errors = array();

        if (strlen($name) == 0 || strlen($name) > 255)
            $errors[] = "Please enter valid name";
        if (strlen($weight) == 0)
            $errors[] = "Please enter weight";
        if (!is_numeric($pcs_per_ctn) || $pcs_per_ctn <= 0)
            $errors[] = "Please enter valid pieces per carton";
        if (!is_numeric($pollybag_pcs_per_kg) || $pollybag_pcs_per_kg <= 0)
            $errors[] = "Please enter valid pollybag pieces per kg";
        if (!is_numeric($pollybag_rate_per_kg) || $pollybag_rate_per_kg <= 0)
            $errors[] = "Please enter valid pollybag rate per kg";
        if (!is_numeric($carton_rate) || $carton_rate < 0)
            $errors[] = "Please enter valid carton rate";

        $usercheck = PackagingCostSetup::CheckPackagingCost($name, 0);
        if ($usercheck)
            $errors[] = "Packaging cost with this name already exists";
            if (count($errors) == 0) {
                $q = PackagingCostSetup::AddPackagingCost($data);

            
            if ($q) {
                $output = '';
                //header("Location: ?view&sucess"); ?>
                <script>window.location.href = '?view&sucess'</script>
            <?php
            echo "<div id='card-alert' class='card green lighten-5'>
                      <div class='card-content green-text'>
                        <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                      </div>
                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
            } else {
                $output = '';
                echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
            }
            } else {
                //Prepare errors for output
                foreach ($errors as $val) {
                    $output .= "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>$val</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                }
            }
            }
            ?>
                <form action="" method="post" id="product_setup_form" novalidate="novalidate">
    <div class="row">
        <div class="col s12 form-group">
            <?php echo $output; ?>
            <div class="col s8">
                <div class="row margin">
                    <span>(*) Mark Fields are mandatory</span><br/><br/>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" id="name" maxlength="250" name="name"
                               value='<?php echo $name; ?>'/>
                        <label for="name" class="control-label">Name *</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" id="weight" maxlength="20" name="weight"
                               value='<?php echo $weight; ?>'/>
                        <label for="weight" class="control-label">Weight *</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="number" id="pcs_per_ctn" name="pcs_per_ctn"
                               value='<?php echo $pcs_per_ctn; ?>'/>
                        <label for="pcs_per_ctn" class="control-label">Pieces per Carton *</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="number" id="pollybag_pcs_per_kg" name="pollybag_pcs_per_kg"
                               value='<?php echo $pollybag_pcs_per_kg; ?>'/>
                        <label for="pollybag_pcs_per_kg" class="control-label">Pollybag Pieces per Kg *</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="number" step="0.01" id="pollybag_rate_per_kg"
                               name="pollybag_rate_per_kg" value='<?php echo $pollybag_rate_per_kg; ?>'/>
                        <label for="pollybag_rate_per_kg" class="control-label">Pollybag Rate per Kg *</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="number" readonly id="pollybag_rate_per_pc"
                               name="pollybag_rate_per_pc" value='<?php echo $pollybag_rate_per_pc; ?>'/>
                        <label for="pollybag_rate_per_pc" class="control-label">Pollybag Rate per Piece (Auto)</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="number" step="0.01" id="carton_rate" name="carton_rate"
                               value='<?php echo $carton_rate; ?>'/>
                        <label for="carton_rate" class="control-label">Carton Rate *</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="number" readonly id="carton_pack_cost"
                               name="carton_pack_cost" value='<?php echo $carton_pack_cost; ?>'/>
                        <label for="carton_pack_cost" class="control-label">Carton Pack Cost (Auto)</label>
                    </div>
                </div>

                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="number" readonly id="total_cost"
                               name="total_cost" value='<?php echo $total_cost; ?>'/>
                        <label for="total_cost" class="control-label">Total Cost (Auto)</label>
                    </div>
                </div>

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

    <div class="row margin">
        <div id="status" class="input-field col s12">
            <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">Submit</button>
            <button type="button" class="btn waves-effect waves-light"
                    onclick="location.href='packaging_cost.php?view'">Cancel
            </button>
        </div>
    </div>
</form>

                <?php
            } // add close

            if (isset($_GET['view'])) {

                ?>
                <?php if (isset($_GET['sucess'])) { ?>
                    <div id='card-alert' class='card green lighten-5'>
                        <div class='card-content green-text'>
                            <p>Successfully updated!</p>
                        </div>
                        <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <?php if (isset($_GET['error'])) { ?>
                    <div id='card-alert' class='card orange lighten-5'>
                        <div class='card-content orange-text'>
                            <p>WARNING : <strong>Attention! </strong>Error occurred!</p>
                        </div>
                        <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <div class="table-datatables">
                    <table id="data-table-simple" class="responsive-table display">
                        <thead>
                        <tr>
                            <th>Action</th>
                            <th>S.No</th>
                            <th>Name</th>
                            <th>Weight</th>
                            <th>Pcs/Ctn</th>
                          	<th>Polybag Pieces/KG</th>
                            <th>Pollybag Rate/Kg</th>
                            <th>Pollybag Rate/Pc</th>
                            <th>Carton Rate</th>
                            <th>Carton Pack Cost</th>
                            <th>Total Cost</th>
                            <th>Date</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>S.No</th>
                            <th>Name</th>
                            <th>Weight</th>
                            <th>Pcs/Ctn</th>
                          	<th>Polybag Pieces/KG</th>
                            <th>Pollybag Rate/Kg</th>
                            <th>Pollybag Rate/Pc</th>
                            <th>Carton Rate</th>
                            <th>Carton Pack Cost</th>
                            <th>Total Cost</th>
                            <th>Date</th>
                        </tr>
                        </tfoot>
                        <tbody>
<?php
$filterP = " ORDER BY id ASC ";
$qry = PackagingCostSetup::GetPackagingCostList($filterP);
if ($qry) {
    $countingSr = 1;
    foreach ($qry as $qery) { ?>
        <tr>
            <td>
                <?php if ($_SESSION['sess_role'] == 'VEC' || $_SESSION['sess_role'] == 'VE') { ?>
                     <a href='?edit&id=<?php echo $qery->id; ?>&v' title="View">
                                    <span style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                          class="mini-stat-icon pink"><i class="mdi-action-description"></i></span>
                                            </a>
                                            <a href="?edit&id=<?php echo $qery->id; ?>" title="Edit">
                                    <span style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                          class="mini-stat-icon orange"><i class="mdi-image-edit"></i></span>
                                            </a>
                 <!--   <a style="cursor:pointer;" title="Delete">
                        <span class="btn-warning-confirm<?= $qery->id ?> mini-stat-icon deep-orange darken-2">
                            <i class="fa fa-arrows-alt">Delete</i>
                        </span>
                    </a> -->
                    <script>
                        $('.btn-warning-confirm<?= $qery->id ?>').click(function () {
                            swal({
                                title: "Are you sure?",
                                text: "Are you sure you want to delete?",
                                type: "warning",
                                showCancelButton: true,
                                confirmButtonColor: '#DD6B55',
                                confirmButtonText: 'Yes',
                                closeOnConfirm: false
                            }, function () {
                                swal("Deleted!", "Packaging cost entry deleted.", "success");
                                window.location.href = 'packaging_cost.php?view&delete=<?php echo $qery->id; ?>';
                            });
                        });
                    </script>
                <?php } else { ?>
                    <a href="?edit&id=<?php echo $qery->id; ?>&v" title="View">
                        <span class="mini-stat-icon pink"><i class="mdi-action-description"></i></span>
                    </a>
                <?php } ?>
            </td>
            <td><?php echo $countingSr; ?></td>
            <td><?php echo ucwords($qery->name); ?></td>
            <td><?php echo $qery->weight; ?></td>
            <td><?php echo $qery->pcs_per_ctn; ?></td>
          	<td><?php echo number_format($qery->pollybag_pcs_per_kg	, 2); ?></td>
            <td><?php echo number_format($qery->pollybag_rate_per_kg, 2); ?></td>
            <td><?php echo number_format($qery->pollybag_rate_per_pc, 4); ?></td>
            <td><?php echo number_format($qery->carton_rate, 2); ?></td>
            <td><?php echo number_format($qery->carton_pack_cost, 4); ?></td>
            <td><?php echo number_format($qery->total_cost, 4); ?></td>
            <td><?php echo date('d-m-Y', strtotime($qery->updated_date)); ?></td>

        </tr>
    <?php
        $countingSr++;
    }
}
?>
</tbody>

                    </table>
                </div>
                <?php
            } // close view


            if (isset($_GET['edit']) && !empty($_POST)) {
                extract($_REQUEST);
                 $id = $_GET['id'];

    $data['name'] = $name;
    $data['weight'] = $weight;
    $data['pcs_per_ctn'] = $pcs_per_ctn;
    $data['pollybag_pcs_per_kg'] = $pollybag_pcs_per_kg;
    $data['pollybag_rate_per_kg'] = $pollybag_rate_per_kg;

    // Auto calculations
    $data['pollybag_rate_per_pc'] = ($pollybag_pcs_per_kg > 0) ? ($pollybag_rate_per_kg / $pollybag_pcs_per_kg) : 0;
    $data['carton_rate'] = $carton_rate;
    $data['carton_pack_cost'] = ($pcs_per_ctn > 0) ? ($carton_rate / $pcs_per_ctn) : 0;
    $data['total_cost'] = $data['pollybag_rate_per_pc'] + $data['carton_pack_cost'];

    $errors = array();

    if ((strlen($name) == 0) || (strlen($name) > 255))
        $errors[] = "Please enter valid name";
    if (strlen($weight) == 0)
        $errors[] = "Please enter weight";
    if (!is_numeric($pcs_per_ctn) || $pcs_per_ctn <= 0)
        $errors[] = "Please enter valid pieces per carton";
    if (!is_numeric($pollybag_pcs_per_kg) || $pollybag_pcs_per_kg <= 0)
        $errors[] = "Please enter valid pollybag pieces per kg";
    if (!is_numeric($pollybag_rate_per_kg) || $pollybag_rate_per_kg <= 0)
        $errors[] = "Please enter valid pollybag rate per kg";
    if (!is_numeric($carton_rate) || $carton_rate < 0)
        $errors[] = "Please enter valid carton rate";

    $usercheck = PackagingCostSetup::CheckPackagingCost($name, $id);
    if ($usercheck)
        $errors[] = "Packaging cost with this name already exists";

    if (count($errors) == 0) {
        $q = PackagingCostSetup::UpdatePackagingCost($id, $data);
        if ($q) {
                        $output = '';
                        //header("Location: ?view&sucess"); ?>
                        <script>window.location.href = '?view&sucess'</script>
                        <?php
                        echo "<div id='card-alert' class='card green lighten-5'>
                      <div class='card-content green-text'>
                        <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                      </div>
                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    } else {
                        $output = '';
                        echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    }
                } else {
                    //Prepare errors for output
                    foreach ($errors as $val) {
                        $output .= "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>$val</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    }
                }
            }
            if (isset($_GET['edit'])) {
                $id = $_GET['id'];
                 if (empty($_POST)) {
        $qry = PackagingCostSetup::GetPackagingCostById($id);
        $name = $qry->name;
        $weight = $qry->weight;
        $pcs_per_ctn = $qry->pcs_per_ctn;
        $pollybag_pcs_per_kg = $qry->pollybag_pcs_per_kg;
        $pollybag_rate_per_kg = $qry->pollybag_rate_per_kg;
        $pollybag_rate_per_pc = $qry->pollybag_rate_per_pc;
        $carton_rate = $qry->carton_rate;
        $carton_pack_cost = $qry->carton_pack_cost;
        $total_cost = $qry->total_cost;
    }

    if ($_REQUEST['id'] && isset($_REQUEST['v'])) {
        ?>
        <style>
            h4 {
                float: left;
                margin: 0;
                width: 30%;
            }

            p {
                float: left;
            }

            .activity-icon {
                margin: 0;
            }
        </style>
                    <div class="row">
            <div class="col s12 form-group">
                <div class="col s8">
                    <div class="row">
                        <div class="col s6"><strong>Name:</strong></div>
                        <div class="col s6"><?php echo $name; ?></div>
                    </div>
                    <div class="row">
                        <div class="col s6"><strong>Weight:</strong></div>
                        <div class="col s6"><?php echo $weight; ?></div>
                    </div>
                    <div class="row">
                        <div class="col s6"><strong>Pollybag Rate / Pc:</strong></div>
                        <div class="col s6"><?php echo number_format($pollybag_rate_per_pc, 4); ?></div>
                    </div>
                    <div class="row">
                        <div class="col s6"><strong>Carton Pack Cost:</strong></div>
                        <div class="col s6"><?php echo number_format($carton_pack_cost, 4); ?></div>
                    </div>
                    <div class="row">
                        <div class="col s6"><strong>Total Cost:</strong></div>
                        <div class="col s6"><?php echo number_format($total_cost, 4); ?></div>
                    </div>
                </div>
            </div>
        </div>
                <?php } else {
                    ?>
                    <div class="row">
                        <!--  The form that will be parsed by jQuery before submit  -->
                        <form action="?edit&id=<?php echo $id ?>" method="post" id="product_setup_form"
                              novalidate="novalidate">
                            <div class="col s12 form-group">
        <div class="col s8">
            <div class="row">
                <?php echo $output; ?>
            </div>
            <div class="row">
                <span>(*) Mark Fields are mandatory</span><br/><br/>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="text" id="name" maxlength="250"
                           name="name" value="<?php echo $name; ?>"/>
                    <label for="name" class="control-label">Name *</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="text" id="weight" maxlength="20"
                           name="weight" value="<?php echo $weight; ?>"/>
                    <label for="weight" class="control-label">Weight *</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="number" id="pcs_per_ctn"
                           name="pcs_per_ctn" value="<?php echo $pcs_per_ctn; ?>"/>
                    <label for="pcs_per_ctn" class="control-label">Pieces per Carton *</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="number" id="pollybag_pcs_per_kg"
                           name="pollybag_pcs_per_kg" value="<?php echo $pollybag_pcs_per_kg; ?>"/>
                    <label for="pollybag_pcs_per_kg" class="control-label">Pollybag Pieces per Kg *</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="number" step="0.01" id="pollybag_rate_per_kg"
                           name="pollybag_rate_per_kg" value="<?php echo $pollybag_rate_per_kg; ?>"/>
                    <label for="pollybag_rate_per_kg" class="control-label">Pollybag Rate per Kg *</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="number" readonly id="pollybag_rate_per_pc"
                           name="pollybag_rate_per_pc" value="<?php echo $pollybag_rate_per_pc; ?>"/>
                    <label for="pollybag_rate_per_pc" class="control-label">Pollybag Rate per Piece (Auto)</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="number" step="0.01" id="carton_rate"
                           name="carton_rate" value="<?php echo $carton_rate; ?>"/>
                    <label for="carton_rate" class="control-label">Carton Rate *</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="number" readonly id="carton_pack_cost"
                           name="carton_pack_cost" value="<?php echo $carton_pack_cost; ?>"/>
                    <label for="carton_pack_cost" class="control-label">Carton Pack Cost (Auto)</label>
                </div>
            </div>

            <div class="row margin">
                <div class="input-field col s12">
                    <input class="form-control" type="number" readonly id="total_cost"
                           name="total_cost" value="<?php echo $total_cost; ?>"/>
                    <label for="total_cost" class="control-label">Total Cost (Auto)</label>
                </div>
            </div>

            <div class="row margin">
                <div id="status" class="input-field col s12">
                    <?php if ($_SESSION['sess_role'] == 'VE' || $_SESSION['sess_role'] == 'VEC') { ?>
                        <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">
                            Submit
                        </button>
                    <?php } ?>
                    <button type="button" class="btn waves-effect waves-light"
                            onclick="location.href='packaging_cost.php?view'">
                        Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>
                    </div>
                <?php } ?>
                </div>
                <?php
            }
            ?>

        </div>
    </div>
</div>
</div>
<?php include('includes/inc_footer.php'); ?>
<?php include('includes/inc_js.php'); ?>
<script type="application/javascript">
    $(document).ready(function () {
        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
    });

function calculatePackagingCosts() {
        var pcsPerKg = parseFloat(document.getElementById('pollybag_pcs_per_kg').value) || 0;
        var ratePerKg = parseFloat(document.getElementById('pollybag_rate_per_kg').value) || 0;
        var pcsPerCtn = parseFloat(document.getElementById('pcs_per_ctn').value) || 0;
        var cartonRate = parseFloat(document.getElementById('carton_rate').value) || 0;

        var ratePerPc = (pcsPerKg > 0) ? (ratePerKg / pcsPerKg) : 0;
        var cartonPackCost = (pcsPerCtn > 0) ? (cartonRate / pcsPerCtn) : 0;
        var total = ratePerPc + cartonPackCost;

        document.getElementById('pollybag_rate_per_pc').value = ratePerPc.toFixed(4);
        document.getElementById('carton_pack_cost').value = cartonPackCost.toFixed(4);
        document.getElementById('total_cost').value = total.toFixed(4);
    }

    ['pollybag_pcs_per_kg', 'pollybag_rate_per_kg', 'pcs_per_ctn', 'carton_rate'].forEach(function (id) {
        var el = document.getElementById(id);
        if (el) el.addEventListener('input', calculatePackagingCosts);
    });

  $(document).ready(function () {
    $('#data-table-simple').DataTable({
        "destroy": true,
        "order": [[1, "asc"]] // 2nd column (S.No) in ascending order
    });
});

</script>
</body>
</html>