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

$current_date = date('Y-m-d');
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php include('../includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker').pickadate({
                //format: 'dd-mm-yyyy',
               format: 'yyyy-mm-dd',
                selectMonths: true,
                selectYears: true, // Creates a dropdown to control year
            });
        });
    </script>
</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>Delivery Challan</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"></i></a>
                        <div class="clearfix"></div>
                    <?php }
                } ?>
                <br />
                <?php
                if (isset($_GET['add']) || isset($_GET['edit'])) {
                    if (isset($_GET['edit'])) {
                        extract($_REQUEST);
                        $getdelivery_challan = Deliverychallan::GetDeliveryChallanSetupById($id);
                        $customer_name = $getdelivery_challan->customer_id;
                        $date = date('d-m-Y', strtotime($getdelivery_challan->created_date));
                        $delivery_challanNumber = $getdelivery_challan->challan_code;
                       // $discount = $getdelivery_challan->discount;
                        $description = $getdelivery_challan->remarks;
                       // $discount_price = $getdelivery_challan->discount_price;
                      //  $tax = $getdelivery_challan->tax;
                      //  $adv_tax = $getdelivery_challan->adv_tax;
                      //  $adv_tax_price = $getdelivery_challan->adv_tax_price;
                      //  $is_tax = $getdelivery_challan->is_tax;
                      //  $tax_price = $getdelivery_challan->tax_price;
                        $poNumber = $getdelivery_challan->po_number;
                      $data['total'] = array_sum($_POST['totcarton']);
                      
                      // After pre-filling values
   					 echo "<script>Materialize.updateTextFields();</script>";
                    } else if (isset($_GET['add'])) {
                        if (PROJECT_TAX == 1) {
                            $tax = PROJECT_TAX_AMOUNT;
                            $is_tax = PROJECT_TAX;
                            $adv_tax = PROJECT_ADV_TAX_AMOUNT;
                        }
                        if (empty($delivery_challan_date)) {
                            $delivery_challan_date = $current_date; // Use current date if delivery_challan date is not set
                            $datedelivery_challan = date('Ymd', strtotime($delivery_challan_date));
                        }
                        if ($_SESSION['clone'] == 1) {
                            $delivery_challanfilter = " WHERE challan_code like '$datedelivery_challan%' ORDER BY id DESC limit 1 ";
                            $delivery_challans = Deliverychallan::GetDeliveryChallanList($delivery_challanfilter);
                            if (!empty($delivery_challans[0]->challan_code)) {
                                $delivery_challanNumber = intval($delivery_challans[0]->challan_code);
                                $delivery_challanNumber = $delivery_challanNumber + 1;
                            } else {
                                $delivery_challanNumber = $datedelivery_challan . '001';
                            }
                        } else {
                            $delivery_challanfilter = " WHERE challan_code like '$datedelivery_challan%' ORDER BY id DESC limit 1 ";
                            $delivery_challans = Deliverychallan::GetDeliveryChallanList($delivery_challanfilter);
                            if (!empty($delivery_challans[0]->challan_code)) {
                                $delivery_challanNumber = intval($delivery_challans[0]->challan_code);
                                $delivery_challanNumber = $delivery_challanNumber + 1;
                            } else {
                                $delivery_challanNumber = $datedelivery_challan . '001';
                            }
                        }
                    }
                    if (isset($_POST) && !empty($_POST)) {
                        extract($_REQUEST);
                        $data['customer_id'] = $customer_name;
                        $data['created_by'] = $sales_person_id;
                        $delivery_challan_date = $_POST['delivery_challan_date'];
                        $data['created_date'] = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($delivery_challan_date)));
                       // $data['challan_code'] = $delivery_challan_number;
                        $data['updated_date'] = 'NOW()';
                        $data['remarks'] = $description;
                        $data['po_number'] = $_POST['po_number'];
                      	$data['validate_date'] = '';
                      	$data['total'] = array_sum($_POST['totcarton']);
                      
                      

                        $errors = array();
                        if ((strlen($customer_name) == 0) || (strlen($customer_name) > 255))
                            array_push($errors, "Please enter customer name");
                        if ((strlen($delivery_challan_date) == 0))
                            array_push($errors, "Please enter delivery_challan date");

                        if (!isset($products) || (count($products) == 0))
                            array_push($errors, "Please select at least one product");

                        if (count($errors) == 0) {
                            if (isset($_GET['add'])) {
                                if ($_SESSION['clone'] == 1) {
                                    $datedelivery_challan = date('Ymd', strtotime($delivery_challan_date));
                                    $delivery_challanfilter = " WHERE challan_code like '$datedelivery_challan%' ORDER BY id DESC limit 1 ";
                                    $delivery_challans = Deliverychallan::GetDeliveryChallanList($delivery_challanfilter);
                                  
                                  
                                    if (!empty($delivery_challans[0]->challan_code)) {
                                        $delivery_challanNumber = intval($delivery_challans[0]->challan_code);
                                        $delivery_challanNumber = $delivery_challanNumber + 1;
                                    } else {
                                        $delivery_challanNumber = $datedelivery_challan . '001';
                                    }
                                } 
                             
                              else {
                                    $datedelivery_challan = date('Ymd', strtotime($delivery_challan_date));
                                    $delivery_challanfilter = " WHERE challan_code like '$datedelivery_challan%' ORDER BY id DESC limit 1 ";
                                    $delivery_challans = Deliverychallan::GetDeliveryChallanList($delivery_challanfilter);
                                  
                                  
                                    if (!empty($delivery_challans[0]->challan_code)) {
                                        $delivery_challanNumber = intval($delivery_challans[0]->challan_code);
                                        $delivery_challanNumber = $delivery_challanNumber + 1;
                                    } else {
                                        $delivery_challanNumber = $datedelivery_challan . '001';
                                    }
                                }
                             
                               
                                $data['challan_code'] = $delivery_challanNumber;
                             	 $data['total'] = array_sum($_POST['totcarton']);
                                $data['status'] = 'Draft';
                                $q = Deliverychallan::AddDeliveryChallan($data);
                              
                                foreach ($products as $prKey => $prRow) {
                                    $productSetup = ProductSetup::GetProductSetupById($prRow);
                                    $dataProduct['challan_id'] = $q;
                                  
                                    $dataProduct['product_id'] = $prRow;
                                             

                                 //   $dataProduct['product_qty'] = $qty[$prKey];
                                    $dataProduct['quantity'] = $totcarton[$prKey];
                                  
                                    $qp = Deliverychallan::AddDeliveryChallanProduct($dataProduct);
                                    

                                }
                            } elseif (isset($_GET['edit'])) {
                                $deliverychallanid = Deliverychallan::GetDeliveryChallanSetupById($_GET['id']);
                              $challan_id = $deliverychallanid->id;
                                 
                                $q = Deliverychallan::UpdateDeliveryChallanSetup($challan_id, $data);
                                Deliverychallan::DeleteDeliveryChallanProducts($challan_id);
                                foreach ($products as $prKey => $prRow) {
                                    $productSetup = ProductSetup::GetProductSetupById($prRow);
                                    $dataProduct['challan_id'] = $challan_id;
                                    $dataProduct['product_id'] = $prRow;
                                    $dataProduct['quantity'] = $totcarton[$prKey];
                                  
                                  
                                  
                                    $qp = Deliverychallan::AddDeliveryChallanProduct($dataProduct);
                                
                                }
                            }

                            if ($qp) {
                                $output = '';
                                ?>
                                <script>window.location.href = 'delivery_challan.php?view&sucess'</script>
                                <?php
                            } 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 {
                            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="delivery_challan_create_form" novalidate="novalidate">
                        <div class="row">
                            <div class="col s12 form-group">
                                <?php echo $output; ?>
                                <div class="row">
                                    <div class="col m6 s12">
                                        <div class="row margin">
                                            <div class="input-field col s12">
                                                <?php
                                                $customersfilter = " WHERE status = 'active' ORDER BY name";
                                                $customers = CustomerSetup::GetCustomerSetupList($customersfilter);
                                                ?>
                                                <select class="form-control" required id="customer_name"
                                                    name="customer_name">
                                                    <option></option>
                                                    <?php
                                                    foreach ($customers as $customersRow) {
                                                        $selected = $customersRow->id == $customer_name ? "selected" : "";
                                                        echo '<option ' . $selected . ' value="' . $customersRow->id . '" data-mart="' . $customersRow->is_mart . '" data-disperc="' . $customersRow->discount_perc . '" data-discountdisable="' . $customersRow->is_discountdisable . '" >' . $customersRow->name . '</option>';
                                                    }
                                                    ?>
                                                </select>
                                                <label for="customer_name" class="control-label">Customer *</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col m6 s12">
                                        <div class="row margin">
                                            <div class="input-field col s12">
                                                <input class="form-control" required type="text" id="datepicker" name="delivery_challan_date" placeholder="<?= date('01-01-Y') ?>"
                                                    value='<?= !empty($date) ? $date : $current_date; ?>' /><br />
                                                <label for="delivery_challan_date" class="form-label ">Delivery Challan Date *</label>
                                            </div>
                                        </div>
                                    </div>
                                  

                                </div>
                                <div class="clearfix"></div>
                                <div class="row">
                                    <div class="col m6 col s12">
                                        <div class="row margin">
                                            <div class="input-field col s12">
                                                <input class="form-control" type="text" id="sales_person" name="sales_person" readonly
                                                    value='<?php echo $_SESSION['sess_username']; ?>' />
                                                <input class="form-control" type="hidden" id="sales_person_id"
                                                    name="sales_person_id"
                                                    value='<?php echo $_SESSION['sess_userid']; ?>' /><br />
                                                <label for="sales_person" class="control-label">Sales Person *</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col m6 col s12">
                                        <div class="row margin">
                                            <div class="input-field col s12">
                                                <input class="form-control" type="text" id="delivery_challan_number" name="delivery_challan_number" readonly
                                                    value='<?php echo $delivery_challanNumber; ?>' /><br />
                                                <label for="delivery_challan_number" class="control-label">delivery_challan No. *</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

								<div class="clearfix"></div>
                                <div class="col m6 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="po_number" name="po_number"
                                                value='<?php echo $poNumber; ?>' /><br />
                                            <label for="po_number" class="control-label">PO No. *</label>
                                        </div>
                                    </div>
                                </div>

                                
                                <div class="row">
                                    <div class="col m6 col s12">
                                        <div class="row margin">
                                            <div class="input-field col s12">
                                                <input class="form-control" type="text" id="description" name="description"
                                                    maxlength="100" value='<?php echo $description; ?>' /><br />
                                                <label for="description" class="control-label">Description</label>
                                            </div>
                                        </div>
                                    </div>
                                   </div>
                                    <div class="clearfix"><br><br></div>
                                    <div class="row">
                                        <table style="margin-top: 60px;" class="bordered responsive-table table dataTable">
                                            <thead>
                                                <th>S.No</th>
                                                <th>Action</th>
                                                <th>Product Name</th>
                                                <th>Carton</th>
                                            </thead>
                                            <tbody id="addNewItem">
                                                <?php
                                                if (isset($_GET['edit'])) {
                                                    $filterdelivery_challanproducts = " WHERE challan_id = '$id'";
                                                   
                                                    $delivery_challanProducts = Deliverychallan::GetdeliverychallanProducts($filterdelivery_challanproducts);
                                                
                                                    $counting = 0;
                                                    foreach ($delivery_challanProducts as $delivery_challanProductsRow) {
                                                  
                                                        $qry = ProductSetup::GetProductSetupById($delivery_challanProductsRow->product_id);
                                                    

                                                        if ($qry) {
                                                            $counting++;
                                                            echo "<tr id='tr" . $qry->id . "'>";
                                                            echo '<td>' . $counting . ' </td>';
                                                            echo '<td style="width: 30px; height: 30px; font-size: 12px; line-height: 15px; margin-top: 11px;" class="mini-stat-icon orange darken-2">';
                                                            echo '<i id="trashing' . $qry->id . '" style="cursor: pointer;font-size: 18px;margin-top: 7px;" class="mdi-action-delete"></i>';
                                                            echo '</td>';
                                                            echo '<td>';
                                                            echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->name . '">';
                                                            echo '<input type="hidden" name="products[]" id="product" value="' . $qry->id . '">';
                                                            echo '</td>';
                                                           echo '<td id="carton">';
   echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" name="totcarton[]" id="totcarton" value="' . $delivery_challanProductsRow->quantity . '"> ';
                                                            echo '</td>';
                                                            ?>
                                                            <?php
                                                        }
                                                    }
                                                }
                                                ?>
                                            </tbody>
                                            <tbody>
                                                <tr>
                                                    <td> </td>
                                                    <td> </td>
                                                    <td></td>
    												<td><strong>Total Cartons: <span id="totalCartons">0</span> </strong></td> <!-- This will display the total cartons -->
     												<td colspan="5"></td>
												</tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <hr>
                                    <div class="clearfix"></div>
                                    <div class="row">
                                        <div class="input-field col m3 col s12">
                                            <?php
                                            $filter = " where status = 'active' ORDER BY product_order";
                                            $qry = ProductSetup::GetProductSetupList($filter, $pageno = "null", $pagesize = "null");
                                            if ($qry) {
                                                echo '<select id="productsItem" style="width: 100%!important;" class="form-control"><option></option>';
                                                foreach ($qry as $qery) {
                                                    echo '<option value=' . $qery->id . '>' . $qery->name . '</option>';
                                                }
                                                echo '</select>';
                                                echo '<label for="productsItem">Products</label>';
                                            }
                                            ?>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="clearfix"></div>
                                        <div class="col m12 col s12">
                                            <div class="btn-group">
                                                <button id="newItem" type="button" class="btn waves-effect waves-light">
                                                    Add New <i class="fa fa-plus"></i>
                                                </button>
                                                <?php if (isset($_GET['add'])) { ?>
                                                    <button id="newAll" type="button" class="btn waves-effect waves-light">
                                                        Add All Products<i class="fa fa-plus"></i>
                                                    </button>
                                                <?php } ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="clearfix"></div>
                            <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='delivery_challan.php?view'">Cancel
                            </button>
                    </form>
                    <?php

                } // close view
                ?>
            </div>
        </div>
    </div>
    </div>
    <?php include('../includes/inc_footer.php'); ?>

    <?php include('../includes/inc_js.php'); ?>
   <script type="application/javascript">
    function numbering() {
        var count = 0;
        $('#addNewItem tr td:first-child').each(function () {
            count++;
            $(this).html(count);
        });
    }

    $(document).ready(function () {
       // Update labels for newly added fields
        Materialize.updateTextFields()
        var selectedvall = $('#customer_name').find(':selected').data('discountdisable');
        if (selectedvall == 1) {
            $('#discount').attr('readonly', true);
        }

        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });

        if ($('#customer_name').find(':selected').attr('data-mart') == 1) {
            $('#distributorHeader').show();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').show();
            });
            $('#show1').show();
            $('#show2').show();
            $('#show3').show();
            $('#show4').show();
            $('#show5').show();
        } else {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
            $('#show5').hide();
        }
        Calculate();
    });

    $('#customer_name').on('change', function () {
        var selectedval = $(this).find(':selected').data('discountdisable');
        if (selectedval == 1) {
            <?php if (isset($_GET['edit'])) { ?>
                $('#discount').val(0);
                Calculate();
            <?php } ?>
            $('#discount').attr('readonly', true);
        } else {
            $('#discount').val($(this).find(':selected').data('disperc'));
            $('#discount').attr('readonly', false);
        }
    });

    $('#customer_name').on('change', function () {
        if ($(this).find(':selected').attr('data-mart') == 1) {
            $('#distributorHeader').show();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').show();
                $(this).rules('add', {
                    required: true,
                    messages: {
                        required: "<span class='label label-warning val_mes'>Please enter distributor price</span>"
                    }
                });
            });
            $('#show1').show();
            $('#show2').show();
            $('#show3').show();
            $('#show4').show();
            $('#show5').show();
        } else {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
            $('#show5').hide();
        }
    });

    $('#newItem').on('click', function () {
        $('#newItem').attr('disabled', true);
        var product = $('#productsItem').val();
        var fewSeconds = 2;
        if (!$('#tr' + product).html() && product != '') {
            $('body #container').block({ message: 'Loading...' });
            $.get('addItemdc.php?id=' + $('#productsItem').val() + '&customer=' + $('#customer_name').find(':selected').attr('data-mart') + '&customerid=' + $('#customer_name').find(':selected').val(), function (data) {
                $("#addNewItem").append(data);
                numbering();
                $('body #container').unblock();
            });
            setTimeout(function () {
                $('body #container').unblock();
            }, fewSeconds * 500);
            $('#newAll').remove();
        }
        $('#newItem').attr('disabled', false);
    });

    $('#newAll').on('click', function () {
        var fewSeconds = 2;
        $('body #container').block({ message: 'Loading...' });
        $.get('addAlldc.php?id=' + $('#customer_name').val() + '&customer=' + $('#customer_name').find(':selected').attr('data-mart'), function (data) {
            $("#addNewItem").append(data);
            numbering();
            $('body #container').unblock();
        });
        $('#newAll').remove();
        setTimeout(function () {
            $('body #container').unblock();
        }, fewSeconds * 500);
    });

    <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
        $('#discount').attr('required', true);
        $(document).on('keyup', "input[name='discount']", function () {
            Calculate();
        });
        $('document').ready(function () {
           // Update labels for newly added fields
        Materialize.updateTextFields()
            $('#discount').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter discount price</span>"
                }
            });
        });
    <?php } ?>

   function Calculate() {
    var totalCartons = 0; // Initialize total cartons

    // Loop through each input in the "Total Cartons" column
    $("input[name='totcarton[]']").each(function () {
        var cartonValue = parseFloat($(this).val());

        // Check if the carton value is a valid number
        if (!isNaN(cartonValue) && cartonValue > 0) {
            totalCartons += cartonValue; // Add to the total cartons
        }
    });

    // Display the total cartons
    $('#totalCartons').text(totalCartons.toFixed(0)); // Display the result
}

// Trigger the calculation whenever the value of carton changes
$(document).on('keyup change', "input[name='totcarton[]']", function () {
   // Update labels for newly added fields
        Materialize.updateTextFields()
    Calculate();
});

// Initial calculation on page load (if necessary)
$(document).ready(function () {
   // Update labels for newly added fields
        Materialize.updateTextFields()
    Calculate();
});

function isDoubleNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

</script>


</body>

</html>
