<?php require_once './admin_header.php';
require_once './PHP_Code/connection.php';
?>


<style>
    th{
        border-top: 1px solid black !important;
        border-bottom: 1px solid black !important;
    }
    label{
        color: darkblue;
        font-size: 15px;
    }
</style>
<div class="app-main__outer">
    <div class="app-main__inner" style="padding-top: 30px;padding-bottom: 0px;padding-left: 0px;padding-right: 30px !important">
        <div class="tab-content">
            <div class="tab-pane tabs-animation fade show active" id="tab-content-0" role="tabpanel">

                <div class="tab-content">
                    <div class="tab-pane tabs-animation fade active show" id="tab-content-0" role="tabpanel">
                        <div class="main-card mb-3 card">
                            <div class="card-body"><h5 class="card-title">ગ્રાહકની માહીતી</h5>
                                <form method="post" id="broker_detail">
                                    <div class="form-row">

                                        <div class="col-md-3">
                                            <label for="mobile_no" class="">મોબાઇલ નંબર</label>
                                            <input name="mobile_no" id="mobile_no" placeholder="મોબાઇલ નંબર" tabindex="1" type="text" class="form-control">
                                            <div id="msg_mobile_no"></div>
                                        </div>

                                        <div class="col-md-4">
                                            <label for="broker_name" class="">ગ્રાહકનું નામ</label>
                                            <input name="broker_name" id="broker_name" placeholder="ગ્રાહકનું નામ" tabindex="2" type="text" class="form-control">
                                            <div id="msg_broker_name"></div>
                                        </div>                                       

                                        <div class="col-md-3">
                                            <label for="Address" class="">સરનામું</label>
                                            <textarea name="address" id="address" placeholder="સરનામું" tabindex="3" class="form-control"></textarea>
                                            <div id="msg_address"></div>
                                        </div>



                                        <div class="col-md-6">
                                            <br>
                                            <div>
                                                <h5  id="total_amount_data">Grant Total</h5>
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <label for="broker_name" class="">Sell Date</label>
                                            <input name="broker_name" id="sell_date" placeholder="Sell Date" tabindex="6" type="date" class="form-control">
                                            <div id="msg_sell_date"></div>
                                        </div>

                                    </div>
                                    <div class="form-row form-group">
                                        <div class="col-md-2">
                                            <br>
                                            <button type="button" class="mt-1 btn btn-primary form-control font-size-lg" tabindex="8" style="width: auto!important" id="btn_save_broker">Save</button>
                                            <div id="msg_insert_data" > </div>
                                        </div>
                                    </div>

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

                <!DOCTYPE html>
                <html lang="gu">
                    <head>
                        <meta charset="UTF-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1">
                        <title>Sell Information</title>
                        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
                    </head>
                    <body>

                        <div class="container-fluid mt-3">
                            <div class="tab-content">
                                <div class="tab-pane fade show active" id="tab-content-0" role="tabpanel">

                                    <div class="card mb-3">
                                        <h5 class="card-title text-center mt-3">વેચાણની માહીતી</h5>

                                        <div class="card-body" id="broket_div">
                                            <div class="row mb-3">
                                                <div class="col-md-4 col-sm-12">
                                                    <div id="msg_milk_take_time_search"></div>
                                                </div>
                                            </div>

                                            <!-- Responsive Table -->
                                            <div class="table-responsive">
                                                <table class="table table-hover text-center">
                                                    <thead class="table-dark">
                                                        <tr>
                                                            <th>#</th>
                                                            <th>ગ્રાહકનું નામ</th>
                                                            <th>મોબાઇલ નંબર</th>
                                                            <th>Total Sell Amount</th>
                                                            <th>Product Details</th>
                                                            <th>Sell Date</th>
                                                            <th>Action</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="table_body">
                                                        <?php
                                                        $query = 'SELECT * FROM tbl_sell_product WHERE flag="1" ORDER BY id DESC';
                                                        mysqli_set_charset($con, 'utf8');
                                                        $result = mysqli_query($con, $query);
                                                        if (mysqli_num_rows($result) > 0) {
                                                            $i = 1;
                                                            while ($row = mysqli_fetch_assoc($result)) {
                                                                $sell_id = $row["id"];
                                                                $query1 = 'SELECT tsl.*, tp.name FROM tbl_sell_list AS tsl 
                                                   LEFT JOIN tbl_product AS tp ON tsl.product_id = tp.id 
                                                   WHERE tsl.flag="1" AND tsl.sell_id=' . $sell_id;
                                                                $result12 = mysqli_query($con, $query1);

                                                                $html_data = "";
                                                                if (mysqli_num_rows($result12) > 0) {
                                                                    $j = 1;
                                                                    while ($row12 = mysqli_fetch_assoc($result12)) {
                                                                        $html_data .= $j . '. ' . $row12["name"] . ' ' . $row12["price"] . '*' . $row12["quantity"] . '=' . $row12["total"] . '<br>';
                                                                        $j++;
                                                                    }
                                                                }
                                                                ?>
                                                                <tr>
                                                                    <td><?php echo $i; ?></td>
                                                                    <td><?php echo $row["cust_name"]; ?></td>
                                                                    <td><?php echo $row["mobile_no"]; ?></td>
                                                                    <td><?php echo $row["sell_total_price"]; ?></td>
                                                                    <td><?php echo $html_data; ?></td>
                                                                    <td><?php echo date("d-m-Y", strtotime($row["sell_date"])); ?></td>
                                                                    <td>
                                                                        <a href="JavaScript:void(0);" class="btn btn-sm btn-success btn_print" id="<?php echo $row["id"]; ?>">
                                                                            <i class="fa fa-print"></i> Print
                                                                        </a>
                                                                        <a href="JavaScript:void(0);" data-bs-toggle="modal" data-bs-target="#exampleModal" class="btn btn-sm btn-danger btn_delete" id="<?php echo $row["id"]; ?>">
                                                                            <i class="fa fa-trash"></i> Delete
                                                                        </a>
                                                                    </td>
                                                                </tr>
                                                                <?php
                                                                $i++;
                                                            }
                                                        } else {
                                                            echo "<tr><td colspan='7'>No results found</td></tr>";
                                                        }
                                                        ?>
                                                    </tbody>
                                                </table>
                                            </div> <!-- End Responsive Table -->
                                        </div>
                                    </div>

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

                        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
                    </body>
                </html>

            </div>
        </div>

    </div>
</div>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        let today = new Date().toISOString().split('T')[0];
        document.getElementById("sell_date").value = today;
    });
</script>

<script type="text/javascript">

    $(document).ready(function () {
        //set initial state.

        var f = {};
        f.text = "SOME DATA";
        f.any_other_field = "text";
        f.items = [];

        $(document.body).on('change', '#product_name', function () {
//        $('#product_name').click(function () {
            var product_id = $(this).attr('name');
            if (!$(this).is(':checked')) {
//                return confirm("Are you sure?");
                $("#quantity" + product_id).css({display: "none"});
                $("#price" + product_id).css({display: "none"});
                $("#total_price" + product_id).css({display: "none"});
//                alert(f.items.length);

                window.location.href = "http://localhost/Rk_Enterprise/product_sell_entry.php";
                //window.location.href = "https://vegboxdairy.thehometown.in/product_sell_entry.php";

            } else {
//                alert("Uncheck");
                $("#quantity" + product_id).css({display: "inline"});
                $("#price" + product_id).css({display: "inline"});
                $("#total_price" + product_id).css({display: "inline"});
                $("#quantity" + product_id).val("");
                $("#price" + product_id).css({display: "inline"});
                $("#total_price" + product_id).html("");
            }
        });




        var cnt_item = 1;
        var total_quantitry = 0;
        $(document.body).on('blur', '.quantity', function () {
            debugger;
//            alert('hello '+$("#course_category").val());
            var product_id = $(this).attr('name');
            if ($("#quantity" + product_id).val() == "")
            {
                alert("* Quantity is Empty");
                $("#total_price" + product_id).val("");
            } else if ($("#quantity" + product_id).val() == "0")
            {
                alert("* Quantity is Empty");
                $("#total_price" + product_id).val("");
            } else
            {
                var quantity = $("#quantity" + product_id).val();
                var price = $("#price" + product_id).attr('name');
                var name = $("#product_name" + product_id).attr('name');
                var total_price = quantity * price;
                $("#total_price" + product_id).html("Total Price Rs. " + total_price);
//                alert("quantity " + quantity);

                var tmp = {};
                tmp.id = product_id;
                tmp.quantity = quantity;
                tmp.price = price;
                tmp.total_price = total_price;
                f.items.push(tmp);
//                alert(f.items.length);

                let grant_total = 0;

                f.items.forEach(item => {
                    let ttotal = parseFloat(item.total_price); // Use parseFloat to handle potential string values
                    grant_total += ttotal;
                });

                console.log(grant_total); // Correct output (sum of total_price values)




//                var data = "<tr> <td>" + cnt_item + ".</td> <td>" + name + "</td><td>" + quantity + "</td><td>" + price + "</td><td>" + total_price + "</td><</tr>";
//                cnt_item = cnt_item + 1;
                $("#total_amount_data").html("Grant Total - " + grant_total);

//                total_quantitry = total_quantitry + parseFloat(quantity);
//                $("#ship_quantity").html(total_quantitry + " KG");
//                $("#ship_total").html("Total Shipping Charge - Rs." + total_quantitry * 20);
//                $("#ship_total").attr('name', total_quantitry * 20);
            }
        });


//        alert('hello');
        $(document.body).on('blur', '#broker_name', function () {
//            alert('hello '+$("#course_category").val());
            if ($("#broker_name").val() == "")
            {
                $("#msg_broker_name").fadeIn(500);
                $("#msg_broker_name").html("* Customer Name is Empty").css({'color': 'red'});
                $("#msg_broker_name").focusin();
            } else
            {
                $("#msg_broker_name").fadeOut(1000);
            }
        });

        $(document.body).on('blur', '#sell_date', function () {
//            alert('hello '+$("#course_category").val());
            if ($("#sell_date").val() == "")
            {
                $("#msg_sell_date").fadeIn(500);
                $("#msg_sell_date").html("* Sell Date is Empty").css({'color': 'red'});
                $("#msg_sell_date").focusin();
            } else
            {
                $("#msg_sell_date").fadeOut(1000);
            }
        });


        $(document.body).on('blur', '#milk_time', function () {
//            alert('hello '+$("#course_category").val());
            if ($("#milk_time").val() == "")
            {
                $("#msg_milk_time").fadeIn(500);
                $("#msg_milk_time").html("* દુધ લેવાનો સમય is Empty").css({'color': 'red'});
                $("#msg_milk_time").focusin();
            } else
            {
                var milk_time = $("#milk_time").children(":selected").attr("name");
//                alert('milk_time '+milk_time);
                $("#msg_milk_time").fadeOut(1000);
            }
        });


        $(document.body).on('change', '#milk_take_time_search', function () {
//            alert('hello '+$("#course_category").val());
            if ($("#milk_take_time_search").val() == "")
            {
                $("#msg_milk_take_time_search").fadeIn(500);
                $("#msg_milk_take_time_search").html("* દુધ લેવાનો સમય is Empty").css({'color': 'red'});
                $("#msg_milk_take_time_search").focusin();
            } else
            {
                var milk_take_time_search = $("#milk_take_time_search").children(":selected").attr("name");
//                alert('milk_take_time_search ' + milk_take_time_search);
                $("#msg_milk_take_time_search").fadeOut(1000);

                var data = {};
                data.milk_take_time_search = milk_take_time_search;
                $.ajax({
                    type: 'POST',
                    data: data,
                    url: './PHP_Code/select_mik_customer.php',
                    success: function (data) {
//                        alert('data '+data);
                        debugger;
                        $('#table_body').html('');
                        $('#table_body').html(data);
                    }, error: function (xhr, err) {
                        alert('Error ' + err.message);
                    }
                });
            }
        });


        $(document.body).on('blur', '#address', function () {
//            alert('hello '+$("#course_category").val());
            if ($("#address").val() == "")
            {
                $("#msg_address").fadeIn(500);
                $("#msg_address").html("* Address is Empty").css({'color': 'red'});
                $("#msg_address").focusin();
            } else
            {
                $("#msg_address").fadeOut(1000);
            }
        });
        $(document.body).on('keypress', '#mobile_no', function (e) {
            //if the letter is not digit then display error and don't type anything
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                //display error message
                $("#msg_mobile_no").html("Digits Only").show().fadeOut("slow");
                return false;
            }
        });

        $(document.body).on('blur', '#mobile_no', function () {
            if ($("#mobile_no").val() == "")
            {
                $("#msg_mobile_no").fadeIn(500);
                $("#msg_mobile_no").html("* Mobile No is Empty").css({'color': 'red'});
            } else
            {
                var mobile = $("#mobile_no").val();
                if (mobile.length != 10) {
                    $("#msg_mobile_no").fadeIn(500);
                    $("#msg_mobile_no").html("* required 10 digits, match requested format!").css({'color': 'red'});
                } else {

                    $("#msg_mobile_no").fadeOut(1000);
                }
            }
        });

        $(document.body).on('blur', '#buffalo_litre', function () {
//            alert('hello '+$("#course_category").val());
            if ($("#buffalo_litre").val() == "")
            {
                $("#msg_buffalo_litre").fadeIn(500);
                $("#msg_buffalo_litre").html("* Buffalo Milk Litre is Empty").css({'color': 'red'});
                $("#msg_buffalo_litre").focusin();
            } else
            {
                $("#msg_buffalo_litre").fadeOut(1000);
            }
        });

        $(document.body).on('blur', '#cow_litre', function () {
//            alert('hello '+$("#course_category").val());
            if ($("#cow_litre").val() == "")
            {
                $("#msg_cow_litre").fadeIn(500);
                $("#msg_cow_litre").html("* Cow Milk Litre is Empty").css({'color': 'red'});
                $("#msg_cow_litre").focusin();
            } else
            {
                $("#msg_cow_litre").fadeOut(1000);
            }
        });

        function clear()
        {
            $("#broker_name").val('');
            $("#mobile_no").val('');
        }

        $('#btn_save_broker').click(function () {
            var broker_name = $("#broker_name").val();
            var mobileno = $("#mobile_no").val();
//            var address = $("#address").val();
//            var customer_type = $("#customer_type").children(":selected").attr("name");
            var sell_date = $("#sell_date").val();
//            var ship_total = $("#ship_total").attr('name');
            var ship_total = $("#ship_total").val();
//            alert('ship_total ' + ship_total);
//            alert('sell_date ' + sell_date);
//            var f = {};
//            f.text = "SOME DATA";
//            f.any_other_field = "text";
//            f.items = [];
//
//            var tmp = {};
//            tmp.id = "1";
//            tmp.name = "Viru";
//            f.items.push(tmp);
//
//            var tmp1 = {};
//            tmp1.id = "12";
//            tmp1.name = "Rocky";
//            f.items.push(tmp1);

            var send = {'cust_name': broker_name, 'mobileno': mobileno, 'f': f, 'ship_total': ship_total, 'sell_date': sell_date};

            if (broker_name == '')
            {
                $("#msg_broker_name").html(" * Customer Name is Empty").css({'color': 'red'});
            } else if (mobileno == '')
            {
                $("#msg_mobile_no").html(" * Mobile No is Empty").css({'color': 'red'});
            } else if (sell_date == '')
            {
                $("#msg_sell_date").html("* Sell Date is Empty").css({'color': 'red'});
            } else
            {
//                alert('Success ');
                if (mobileno.length != 10) {
                    $("#msg_mobile_no").fadeIn(500);
                    $("#msg_mobile_no").html("* required 10 digits, match requested format!").css({'color': 'red'});
                } else {

                    $("#msg_mobile_no").fadeOut(1000);

                    debugger;
                    $.ajax({
                        url: './PHP_Code/bill_entry_customer.php',
                        type: 'POST',
                        data: send,
                        success: function (data)
                        {

                            debugger;
//                            alert('data ' + data);
                            if (data == 'Error:01')
                            {
                                $('#msg_insert_data').fadeIn(500);
                                $('#msg_insert_data').html("* Record Not Inserted ").css({'color': 'red'});
                                $('#msg_insert_data').fadeOut(1000);
                            } else {
                                $('#msg_insert_data').fadeIn(500);
                                $('#msg_insert_data').html("* Data Insert Successfully ").css({'color': 'green'});
                                $('#msg_insert_data').fadeOut(1000);
                                $('#table_body').html('');
                                $('#table_body').html(data);
                                clear();
                                window.location.href = "./product_sell_entry.php";
                                $('html, body').animate({
                                    scrollTop: $("#btn_save_broker").offset().top
                                }, 500);
                            }

                            // window.location.href = "http://localhost/Vegbox_dairy/product_sell_entry.php";
//                            window.location.href = "http://localhost/Rk_Enterprise/print_bill.php";

                        },
                        error: function (err) {
                            alert('error ' + err);
                        }
                    });
                }
            }
        });



        $(document.body).on('click', '.btn_print', function () {
//            alert('view print ' + $(this).attr('id'));
            var broker_id = $(this).attr('id');
            var send = {'order_id': broker_id}
            if (broker_id == '')
            {
                alert('Please Select Valid Record!');
            } else
            {
                $.ajax({
                    url: './PHP_Code/order_id_session.php',
                    type: 'POST',
                    data: send,
                    success: function (data)
                    {
                        debugger;
//                        alert('data ' + data);
//                        $('#broker_detail').html('');
//                        $('#broker_detail').html(data);
//                        $('#broker_name').focus();
                        var url = "./print_bill.php";
                        window.open(url, '_blank');
                    },
                    error: function (err) {
                        alert('error ' + err);
                    }
                });
            }
        });

        $(document.body).on('click', '#btn_update_customer', function () {
//            alert('view print ' + $(this).attr('name'));
            var broker_id_update = $(this).attr('name');
            var broker_name_update = $("#broker_name").val();
            var mobileno = $("#mobile_no").val();
            var address = $("#address").val();
            var cow_litre = $("#cow_litre").val();
            var buffalo_litre = $("#buffalo_litre").val();
            var milk_take_time = $("#milk_time").children(":selected").attr("name");

            var send = {'cust_id_update': broker_id_update, 'cust_name_update': broker_name_update, 'address': address, 'mobileno': mobileno, 'buffalo_litre': buffalo_litre, 'cow_litre': cow_litre, 'milk_take_time': milk_take_time};

            if (broker_id_update == '')
            {
                alert('Customer ID Not Valid!');
            } else if (broker_name_update == '')
            {
                $("#msg_broker_name").html(" * Customer Name is Empty").css({'color': 'red'});
            } else if (mobileno == '')
            {
                $("#msg_mobile_no").html(" * Mobile No is Empty").css({'color': 'red'});
            } else if (address == '')
            {
                $("#msg_address").html(" * Address is Empty").css({'color': 'red'});
            } else if (buffalo_litre == '')
            {
                $("#msg_buffalo_litre").html("* Buffalo Milk Litre is Empty").css({'color': 'red'});
            } else if (cow_litre == '')
            {
                $("#msg_cow_litre").html("* Cow Milk Litre is Empty").css({'color': 'red'});
            } else if (milk_take_time == '')
            {
                $("#msg_milk_time").html("* દુધનો લેવાનો સમય is Empty").css({'color': 'red'});
            } else
            {
//                alert('Success ');
                if (mobileno.length != 10) {
                    $("#msg_mobile_no").fadeIn(500);
                    $("#msg_mobile_no").html("* required 10 digits, match requested format!").css({'color': 'red'});
                } else {

                    $("#msg_mobile_no").fadeOut(1000);

                    debugger;
                    $.ajax({
                        url: './PHP_Code/customer.php',
                        type: 'POST',
                        data: send,
                        success: function (data)
                        {
                            debugger;
//                            alert('data '+data);
                            $('#table_body').html('');
                            $('#table_body').html(data);
                            clear();
                            $('html, body').animate({
                                scrollTop: $("#btn_update_broker").offset().top
                            }, 500);
//                          
                        },
                        error: function (err) {
                            alert('error ' + err);
                        }
                    });
                }
            }
        });

        $(document.body).on('click', '.btn_delete', function () {
//            alert('view print ' + $(this).attr('id'));
            var broker_id = $(this).attr('id');
            $('#btn_delete_confirm').attr('name', broker_id);
        });

        $(document.body).on('click', '#btn_delete_confirm', function () {
//            alert('view print ' + $(this).attr('name'));
            var broker_id_delete = $(this).attr('name');
            var send = {'cust_id_delete': broker_id_delete}
            $('#btn_mode_hide').click();
            if (broker_id_delete == '')
            {
                alert('Please Select Valid Record!');
            } else
            {
                $.ajax({
                    url: './PHP_Code/bill_entry_customer.php',
                    type: 'POST',
                    data: send,
                    success: function (data)
                    {
                        debugger;
//                            alert('data ' + data);
                        $('#table_body').html('');
                        $('#table_body').html(data);
                        clear();
                        $('html, body').animate({
                            scrollTop: $("#btn_update_broker").offset().top
                        }, 500);
                    },
                    error: function (err) {
                        alert('error ' + err);
                    }
                });
            }
        });
    });

</script>

<?php
require_once './admin_footer.php';
?>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Confirmation Message</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p class="mb-0">Are you sure to delete this record ?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btn_mode_hide" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger" id="btn_delete_confirm">Delete</button>
            </div>
        </div>
    </div>
</div>
