<?php

if (!$user->cdp_is_Admin())
    cdp_redirect_to("login.php");

$userData = $user->cdp_getUserData();

?>

<?php

include "config.php";

if (isset($_POST['submit'])) {

    $var_1 = $_POST['expense_title'];

    $var_2 = $_POST['expense_type'];

    $var_3 = $_POST['created_date'];

    $var_4 = $_POST['expense_amount'];

    $var_5 = $_POST['pre_user'];
    
    $var_6 = $_POST['currency'];
    
    $var_7 = $_POST['name_off'];

    $sql = "INSERT INTO `expenses_master`(`expense_title`, `expense_type`, `created_date`, `expense_amount`, `pre_user`, `currency`, `name_off`) VALUES ('$var_1','$var_2','$var_3','$var_4','$var_5','$var_6','$var_7')";

    $result = $conn->query($sql);

    if ($result == TRUE) {

        echo "New record created successfully.";
        
        header("Location: expenses_list.php");

    } else {

        echo "Error:" . $sql . "<br>" . $conn->error;

    }

    $conn->close();

}

?>

<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Tell the browser to be responsive to screen width -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <!-- Favicon icon -->
    <link rel="icon" type="image/png" sizes="16x16" href="assets/<?php echo $core->favicon ?>">
    <title>Add New Expense | <?php echo $core->site_name ?></title>
    <!-- This Page CSS -->
    <!-- Custom CSS -->
    <link rel="stylesheet" href="assets/intl-tel-input/css/intlTelInput.css">

    <link href="assets/css/style.min.css" rel="stylesheet">

    <link href="assets/css_log/front.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="assets/js/jquery.js"></script>
    <script type="text/javascript" src="assets/js/jquery-ui.js"></script>
    <script src="assets/js/jquery.ui.touch-punch.js"></script>
    <script src="assets/js/jquery.wysiwyg.js"></script>
    <script src="assets/js/global.js"></script>
    <script src="assets/js/custom.js"></script>
    <link href="assets/customClassPagination.css" rel="stylesheet">


    <script>
        $(document).ready(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>

</head>

<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->


<?php include 'views/inc/preloader.php'; ?>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper">
    <!-- ============================================================== -->
    <!-- Topbar header - style you can find in pages.scss -->
    <!-- ============================================================== -->

    <!-- ============================================================== -->
    <!-- Preloader - style you can find in spinners.css -->
    <!-- ============================================================== -->

    <?php include 'views/inc/topbar.php'; ?>

    <!-- End Topbar header -->


    <!-- Left Sidebar - style you can find in sidebar.scss  -->

    <?php include 'views/inc/left_sidebar.php'; ?>


    <!-- End Left Sidebar - style you can find in sidebar.scss  -->

    <!-- Page wrapper  -->
    <!-- ============================================================== -->
    <div class="page-wrapper">

        <div class="page-breadcrumb ">
            <div class="row">
                <div class="col-8 align-self-center offset-1">
                    <h4 class="page-title">
                        Add New Expense</h4>
                </div>
            </div>
        </div>


        <div class="container-fluid">


            <div class="row justify-content-center">
                <!-- Column -->
                <div class="col-lg-12 col-xlg-12 col-md-12">
                    <div class="card">

                        <div class="card-body">
                            <!-- <div id="loader" style="display:none"></div> -->
                            <div id="resultados_ajax"></div>
                            <form action="" method="POST">

                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Expense Title</label>
                                            <input type="text" class="form-control" name="expense_title">
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Expense Type</label>
                                            <select class="form-control" name="expense_type">
                                                <option value="">--Select Expense--</option>
                                                <option value="Meals">Meals</option>
                                                <option value="Utility">Utility</option>
                                                <option value="Others">Others</option>
                                                <option value="Salary">Salary</option>
                                                <option value="Transport">Transportation</option>
                                                <option value="Cargo">Cargo Charges</option>
                                            </select>

                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Expense Date</label>
                                            <input type="date" class="form-control" name="created_date">
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Currency</label>
                                            <select class="form-control" name="currency">
                                                <option value="">--- Pick Currency ---</option>
                                                <option value="Ksh.">KES</option>
                                                <option value="$">USD</option>
                                            </select>

                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Agency</label>
                                            <select class="form-control" name="name_off">
                                                <option value="">--- Pick Agency ---</option>
                                                <option value="Shiine NBO">Shiine NBO</option>
                                                <option value="Shiine MGQ">Shiine MGQ</option>
                                            </select>

                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Expense Amount</label>
                                            <input type="text" class="form-control" name="expense_amount">
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>User</label>
                                            <input type="text" class="form-control" name="pre_user">
                                        </div>
                                    </div>
                                    

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <button class="btn btn-primary" type="submit" name="submit" value="submit">Submit</button>
                                        </div>
                                    </div>
                                </div>

                                <!--                                <fieldset>-->
                                <!---->
                                <!--                                    <legend>Personal information:</legend>-->
                                <!---->
                                <!--                                    EXP name:<br>-->
                                <!---->
                                <!--                                    <input type="text" name="expense_title">-->
                                <!---->
                                <!--                                    <br>-->
                                <!---->
                                <!--                                    EXP Type:<br>-->
                                <!---->
                                <!--                                    <input type="text" name="expense_type">-->
                                <!---->
                                <!--                                    <br>-->
                                <!---->
                                <!--                                    Date:<br>-->
                                <!---->
                                <!--                                    <input type="date" name="created_date">-->
                                <!---->
                                <!--                                    <br>-->
                                <!---->
                                <!--                                    Amount:<br>-->
                                <!---->
                                <!--                                    <input type="number" name="expense_amount">-->
                                <!---->
                                <!--                                    <br>-->
                                <!---->
                                <!--                                    User:<br>-->
                                <!---->
                                <!--                                    <input type="number" name="pre_user">-->
                                <!---->
                                <!--                                    <br>-->
                                <!---->
                                <!--                                    <br><br>-->
                                <!---->
                                <!--                                    <input type="submit" name="submit" value="submit">-->
                                <!---->
                                <!--                                </fieldset>-->

                            </form>
                            <!--                            <form class="form-horizontal form-material" id="save_user" name="save_user" method="post">-->
                            <!--                                <section>-->
                            <!---->
                            <!--                                    <div class="row">-->
                            <!--                                        <div class="col-md-3">-->
                            <!--                                            <div class="form-group">-->
                            <!--                                                <label for="firstName1">-->
                            <?php //echo $lang['salary_manage002'] ?><!--</label>-->
                            <!--                                                <input type="text" class="form-control" id="username" name="username"-->
                            <!--                                                       placeholder="-->
                            <?php //echo $lang['salary_manage002'] ?><!--">-->
                            <!--                                            </div>-->
                            <!--                                        </div>-->
                            <!---->
                            <!--                                        <div class="col-md-3">-->
                            <!--                                            <div class="form-group">-->
                            <!--                                                <label for="firstName1">-->
                            <?php //echo $lang['salary_manage003'] ?><!--</label>-->
                            <!--                                                <input type="text" class="form-control" id="username" name="username"-->
                            <!--                                                       placeholder="-->
                            <?php //echo $lang['salary_manage003'] ?><!--">-->
                            <!--                                            </div>-->
                            <!--                                        </div>-->
                            <!---->
                            <!--                                        <div class="col-md-3">-->
                            <!--                                            <div class="form-group">-->
                            <!--                                                <label for="lastName1">-->
                            <?php //echo $lang['salary_manage004'] ?><!--</label>-->
                            <!--                                                <input type="number" class="form-control" name="password" id="password"-->
                            <!--                                                       placeholder="-->
                            <?php //echo $lang['salary_manage004'] ?><!--">-->
                            <!--                                            </div>-->
                            <!--                                        </div>-->
                            <!--                                        <div class="col-md-3">-->
                            <!--                                            <div class="form-group">-->
                            <!--                                                <label for="firstName1">-->
                            <?php //echo $lang['salary_manage005'] ?><!--</label>-->
                            <!--                                                <input type="number" class="form-control" id="username" name="username"-->
                            <!--                                                       placeholder="-->
                            <?php //echo $lang['salary_manage005'] ?><!--">-->
                            <!--                                            </div>-->
                            <!--                                        </div>-->
                            <!--                                    </div>-->
                            <!---->
                            <!--                                    <hr>-->
                            <!--                                </section>-->
                            <!---->
                            <!--                                <div class="form-group">-->
                            <!--                                    <div class="col-sm-12">-->
                            <!--                                        <button class="btn btn-outline-primary btn-confirmation" id="save_data"-->
                            <!--                                                name="save_data" type="submit">--><?php //echo $lang['salary_manage006'] ?>
                            <!--                                            <span><i class="icon-ok"></i></span></button>-->
                            <!--                                        <a href="customers_list.php" class="btn btn-outline-secondary btn-confirmation"><span><i-->
                            <!--                                                        class="ti-share-alt"></i></span> --><?php //echo $lang['user_manage30'] ?>
                            <!--                                        </a>-->
                            <!--                                    </div>-->
                            <!--                                </div>-->
                            <!--                                <input name="locker" id="locker" type="hidden" value="-->
                            <?php //echo generarCodigo(6); ?><!--"/>-->
                            <!--                            </form>-->
                        </div>
                    </div>

                </div>
                <!-- Column -->
            </div>


        </div>


    </div>
    <!-- ============================================================== -->
    <!-- End Page wrapper  -->
    <!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->


<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<!-- Bootstrap tether Core JavaScript -->
<script src="assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<script src="assets/js/app.min.js"></script>
<script src="assets/js/app.init.js"></script>
<script src="assets/js/app-style-switcher.js"></script>
<!-- slimscrollbar scrollbar JavaScript -->
<script src="assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="assets/extra-libs/sparkline/sparkline.js"></script>
<!--Wave Effects -->
<script src="assets/js/waves.js"></script>
<!--Menu sidebar -->
<script src="assets/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="assets/js/custom.min.js"></script>

<script src="assets/intl-tel-input/js/intlTelInput.js"></script>


<script>


    errorMsg = document.querySelector("#error-msg");
    validMsg = document.querySelector("#valid-msg");

    // here, the index maps to the error code returned from getValidationError - see readme
    var errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];


    var input = document.querySelector("#phone_custom");
    var iti = window.intlTelInput(input, {
        // allowDropdown: false,
        // autoHideDialCode: false,
        // autoPlaceholder: "off",
        // dropdownContainer: document.body,
        // excludeCountries: ["us"],
        // formatOnDisplay: true,
        geoIpLookup: function (callback) {
            $.get("http://ipinfo.io", function () {
            }, "jsonp").always(function (resp) {
                var countryCode = (resp && resp.country) ? resp.country : "";
                callback(countryCode);
            });
        },
        // hiddenInput: "full_number",
        initialCountry: "auto",
        // localizedCountries: { 'de': 'Deutschland' },
        nationalMode: true,
        // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
        // placeholderNumberType: "MOBILE",
        // preferredCountries: ['cn', 'jp'],
        separateDialCode: true,
        utilsScript: "assets/intl-tel-input/js/utils.js",
    });


    var reset = function () {
        input.classList.remove("error");
        errorMsg.innerHTML = "";
        errorMsg.classList.add("hide");
        validMsg.classList.add("hide");
    };

    // on blur: validate
    input.addEventListener('blur', function () {
        reset();
        if (input.value.trim()) {

            if (iti.isValidNumber()) {

                $('#phone').val(iti.getNumber());

                validMsg.classList.remove("hide");

            } else {

                input.classList.add("error");
                var errorCode = iti.getValidationError();
                errorMsg.innerHTML = errorMap[errorCode];
                errorMsg.classList.remove("hide");

            }
        }
    });

    // on keyup / change flag: reset
    input.addEventListener('change', reset);
    input.addEventListener('keyup', reset);

</script>


<script>

    $(document).ready(function () {

        var count = 1;

        $(document).on('click', '#add_row', function () {

            count++;

            $('#total_address').val(count);

            var html_code = '';
            var parent = $('#div_parent_' + count);


            html_code += '<div id="div_parent_' + count + '">';
            html_code += '<hr>';

            html_code += '<h4><?php echo $lang['laddress'] ?> ' + count + '</h4>';


            html_code += '<div class="row">';

            html_code += '<div class="col-md-6">' +
                '<div class="form-group">' +
                '<label for="phoneNumber1"><?php echo $lang['user_manage10'] ?></label>' +
                '<input type="text" class="form-control" name="address[]"  id="address' + count + '"placeholder="<?php echo $lang['user_manage10'] ?>">' +
                '</div>' +
                '</div>';

            html_code += '<div class="col-md-6">' +
                '<div class="form-group">' +
                '<label for="emailAddress1"><?php echo $lang['user_manage12'] ?></label>' +
                '<input type="text" class="form-control" name="country[]"  id="country' + count + '" placeholder="<?php echo $lang['user_manage12'] ?>">' +
                '</div>' +
                '</div>';


            html_code += '</div>';


            html_code += '<div class="row">';

            html_code += '<div class="col-md-6">' +
                '<div class="form-group">' +
                '<label for="phoneNumber1"><?php echo $lang['user_manage13'] ?></label>' +
                '<input type="text" class="form-control" id="city' + count + '" name="city[]" placeholder="<?php echo $lang['user_manage13'] ?>">' +
                '</div>' +
                '</div>';

            html_code += '<div class="col-md-6">' +
                '<div class="form-group">' +
                '<label for="phoneNumber1"><?php echo $lang['user_manage14'] ?></label>' +
                '<input type="text" class="form-control" name="postal[]" id="postal' + count + '" placeholder="<?php echo $lang['user_manage14'] ?>">' +
                '</div>' +
                '</div>';

            html_code += '</div>';

            html_code += '<div class="row pull-">';
            html_code += '<div align="right" class="col-md-12">' +
                '<button type="button" name="remove_row" id="' + count + '" class="btn btn-danger   remove_row mt-2 mb-3"><span class="fa fa-trash"></span> <?php echo $lang['delete_address_recepient'] ?></button>' +
                '</div>';

            html_code += '</div>';


            html_code += '</div>'; //div parent


            $('#div_address_multiple').append(html_code);


        });


        $(document).on('click', '.remove_row', function () {

            var row_id = $(this).attr("id");
            var parent = $('#div_parent_' + row_id);


            count--;
            parent.fadeOut(400, function () {

                $('#div_parent_' + row_id).remove();

            });
            $('#total_address').val(count);

        });


    });


    //Registro de datos

    $("#save_user").submit(function (event) {


        var count = $('#total_address').val();
        var validate = 0;

        for (var no = 1; no <= count; no++) {

            if ($.trim($('#address' + no).val()).length == 0) {
                alert("Please enter address");
                $('#address' + no).focus();

                return false;
            }


            if ($.trim($('#country' + no).val()).length == 0) {
                alert("Please enter country");
                $('#country' + no).focus();

                return false;
            }

            if ($.trim($('#city' + no).val()).length == 0) {
                alert("Please enter city");
                $('#city' + no).focus();

                return false;
            }

            if ($.trim($('#postal' + no).val()).length == 0) {
                alert("Please enter zip code");
                $('#postal' + no).focus();

                return false;
            }

        }


        // if(validate==0){
        if (iti.isValidNumber()) {


            $('#save_data').attr("disabled", true);
            var parametros = $(this).serialize();

            var inputFileImage = document.getElementById("avatar");
            var username = $('#username').val();
            var email = $('#email').val();
            var fname = $('#fname').val();
            var lname = $('#lname').val();
            var notes = $('#notes').val();
            var phone = $('#phone').val();
            var gender = $('#gender').val();
            var locker = $('#locker').val();
            var password = $('#password').val();
            var notify = $('#notify:checked').val();
            var active = $('input:radio[name=active]:checked').val();
            var newsletter = $('input:radio[name=newsletter]:checked').val();
            var total_address = $('#total_address').val();

            var address = document.getElementsByName('address[]');
            var country = document.getElementsByName('country[]');
            var city = document.getElementsByName('city[]');
            var postal = document.getElementsByName('postal[]');
            console.log(address);

            var file = inputFileImage.files[0];
            var data = new FormData();

            data.append('avatar', file);
            data.append('locker', locker);
            data.append('username', username);
            data.append('password', password);
            data.append('fname', fname);
            data.append('lname', lname);
            data.append('email', email);
            data.append('phone', phone);
            data.append('gender', gender);
            data.append('active', active);
            data.append('newsletter', newsletter);
            data.append('notes', notes);
            data.append('notify', notify);
            data.append('total_address', total_address);
            // data.append('address',address);

            for (var a of address) {
                data.append('address[]', a.value);
            }
            for (var c of country) {
                data.append('country[]', c.value);
            }
            for (var ci of city) {
                data.append('city[]', ci.value);
            }
            for (var p of postal) {
                data.append('postal[]', p.value);
            }

            $.ajax({

                type: "POST",
                url: "ajax/customers/customers_add_ajax.php",
                data: data,
                contentType: false,       // The content type used when sending data to the server.
                cache: false,             // To unable request pages to be cached
                processData: false,
                beforeSend: function (objeto) {
                    $("#resultados_ajax").html("Send...");
                },
                success: function (datos) {
                    $("#resultados_ajax").html(datos);
                    $('#save_data').attr("disabled", false);

                    $('html, body').animate({
                        scrollTop: 0
                    }, 600);

                    // window.setTimeout(function() {
                    // $(".alert").fadeTo(500, 0).slideUp(500, function(){
                    // $(this).remove();});}, 5000);
                }
            });

        } else {

            input.classList.add("error");
            var errorCode = iti.getValidationError();
            errorMsg.innerHTML = errorMap[errorCode];
            errorMsg.classList.remove("hide");
            $('#phone_custom').focus();


        }


        event.preventDefault();

    })


</script>
</body>

</html>
