<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Report Document</title>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.0.8/css/dataTables.bootstrap4.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.5.2/css/dataTables.dateTime.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/bootstrap.datepicker-fork/1.3.0/css/datepicker3.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/3.0.2/css/buttons.dataTables.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="../assets/css/style.css" crossorigin="anonymous">
    <script src="../assets/js/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/bootstrap.datepicker-fork/1.3.0/js/bootstrap-datepicker.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/2.0.8/js/dataTables.js"></script>
    <script src="https://cdn.datatables.net/2.0.8/js/dataTables.bootstrap4.js"></script>
    <script src="https://cdn.datatables.net/buttons/3.0.2/js/dataTables.buttons.js"></script>
    <script src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.dataTables.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
    <script>
        function fetchInputValues(event) {
            // Prevent default form submission
            event.preventDefault();

            // Fetch input values
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            // Log the values to the console
            if(username == $username && password == $password){
                // session_start();

            }
        }
    </script>

    <style>
        .form-control {
            /* text-transform: capitalize; */
        }
        tbody tr .dt-type-numeric:not(:first-child){
            text-align: left !important;
        }
    </style>
</head>
<body id="paymentReport">

<?php
session_start();
$_SESSION['reportLogin'] = false;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once('../config/db_config.php');
require_once('../config/functionclass.php');

$classObject = new PHPClass();
$token = $classObject->getToken();
$token = json_decode($token);

$authorization = "Authorization: Bearer " . $token->access_token;
$params = "type=reportCredentials";
$options = array(
	'public_key' => isset($token->nonsec)?$token->nonsec:'',
	'params' => $params,
	'jsonData' => '',
	'access_token' => isset($token->access_token)?$token->access_token:'',
);
$nonce = $classObject->secMe($options);

if (isset($_POST['username']) && isset($_POST['password'])) {
    $inputUsername = $_POST['username'];
    $inputPassword = $_POST['password'];
    
    $ch = curl_init(baseURL . getDropdown . '?' . $params);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt(
        $ch,
        CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json', $authorization,
            'nonce:' .$nonce
        )
    );
    $resultcurl = curl_exec($ch);
    $responceERP2 = json_decode($resultcurl);
   
    $authenticated = false;
    if ($responceERP2 && count($responceERP2) > 0) {
        foreach ($responceERP2 as $response) {
            if ($inputUsername == $response->code && $inputPassword == $response->value) {
                $authenticated = true;
                break;
            }
        }

        if ($authenticated) {
            $_SESSION['reportLogin'] = true;
            // header("Location: reports");
            // exit();
        } else {
            $_SESSION['reportLogin'] = false;
            $error = "Invalid username or password.";
        }
    }
   
}

    ?>
    <div class="container">
        <div class="row">
            <div class="col-12">
                <?php 
                    if(isset($_SESSION['reportLogin']) && $_SESSION['reportLogin'])
                    {
                        ?>
                       
                        <div class="paymentReport_innerWrapper">
                        <div class="d-flex justify-content-end">
                        <button class="btn btn-danger mt-2" type="button" onClick="logoutUser()">Logout</button>
                            </div>
                            <div class="text-center">
                                <h1 class="heading">Payment Report</h1>
                            </div>
                            <div id="filterForPayment" class="">
                                <form id="searchForm" class="g-3 needs-validation" name="registration" autocomplete="off">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label>Payment Type <span class="text-danger">*</span></label>
                                                <select class="form-control" name="screenName" id="screenNameDropdown" require>
                                                    <option value="" disabled="disabled" selected="true">Select</option>
                                                    <option value="sendPaymentLink_payment">Send Payment Link</option>
                                                    <?php include './fetchScreen.php';?>
                                                </select>
                                            </div>
                                        </div>
        
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label>From Date <span class="text-danger">*</span></label>
                                                <input class="datepicker form-control" type="text" id="minDate" name="minDate" placeholder="Select Date" require autocomautocomplete="off">
                                            </div>
                                        </div>
        
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label>To Date <span class="text-danger">*</span></label>
                                                <input class="datepicker form-control" type="text" id="maxDate" name="maxDate" placeholder="Select Date" require>
                                            </div>
                                        </div>
        
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label>Email Id</label>
                                                <input type="email" id="email" name="email" class="form-control" placeholder="Type Email">
                                            </div>
                                        </div>
        
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label>Username</label>
                                                <input type="username" id="username" name="username" class="form-control" placeholder="Type Username">
                                            </div>
                                        </div>
        
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label>Payment Status <span class="text-danger">*</span></label>
                                                <select class="form-control" name="paymentStatus" id="paymentStatus" required>
                                                    <option value="">Select</option>
                                                    <option value="all">All</option>
                                                    <option value="success">Success</option>
                                                    <option value="failed">Failed</option>
                                                </select>
                                            </div>
                                        </div>
        
                                        <div class="col-md-4">
                                            <div class="form-group mt-4">
                                                <button class="btn btn-primary mt-2" type="submit">Search</button>
                                                <button class="btn btn-danger mt-2" type="reset" onClick="resetForm()">Reset</button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
        
                            <div class="table-responsive">
                                <table id="paymentDataTable" class="table table-striped table-bordered display nowrap capitalize" style="width:100%">
                                    <thead>
                                        <tr>
                                            <th>SR. No.</th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Code</th>
                                            <th>Transaction ID</th>
                                            <th>Payment Date</th>
                                            <th>Payment Status</th>
                                            <th>Receipt Status</th>
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                        </div>
                        <?php
                    }
                    else
                    {
                        ?>
                        <form method="post" action="index.php">
                        <div class="container d-flex justify-content-center align-items-center vh-100">
                            <div class="card p-4 shadow-lg" style="width: 25rem;">
                                <div class="card-body">
                                    <h3 class="card-title text-center mb-4">Login</h3>
                                    <form action="" method="post">
                                        <div class="mb-3">
                                            <label for="username" class="form-label">Username</label>
                                            <input type="text" class="form-control" id="text" placeholder="Enter your email" name="username" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="password" class="form-label">Password</label>
                                            <input type="password" class="form-control" name="password" id="password" placeholder="Enter your password" required>
                                        </div>
                                        <?php
                                        if(isset($_POST['username']) && isset($_POST['password']) &&  $_SESSION['reportLogin'] == false){
                                            echo '<span class="text-danger">Invalid user credentials</span>';
                                        }
                                        ?>
                                        
                                        <button type="submit" class="btn btn-primary w-100">Login</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php
                    }
                ?>

            </div>
        </div>
    </div>
</body>
<script>
    // new DataTable('#paymentDataTable');

    $(document).ready(function() {
        $('.datepicker').datepicker({
            format: "dd/mm/yyyy",
            autoclose:true,
            endDate:new Date(),
            clearBtn:true,
        }).on('changeDate', function (e) {
            var min = $('#minDate').val();
            var max = $('#maxDate').val();

            // $("form[name='registration']").valid();
            if(e.target.id == 'minDate') {
                if(min== '') {
                    $('#maxDate').datepicker('setStartDate', new Date('01/01/1950'));
                }else {
                    $('#maxDate').datepicker('setStartDate', new Date(e.date.valueOf()));
                }

            }
            if(e.target.id === 'maxDate') {
                if(max == '') {
                    $('#minDate').datepicker('setEndDate', new Date());
                }else {
                    $('#minDate').datepicker('setEndDate', new Date(e.date.valueOf()));
                }
            }
            // updateDate($(this).closest('form').find('input:text'), e);
        }).on('hide', function(ev) { // <-----------
            // alert("hide");
            $("form[name='registration']").data("validator")
            $(this).valid();
        });
    });
    // var table = $('#paymentDataTable').DataTable();
    var table = $('#paymentDataTable').DataTable({
        // dom: 'Blfrtip',
        "dom": '<"top"lB>rt<"bottom"pi>',
        "buttons": [
            {
                "extend": 'spacer',
                "text": 'Export files:'
            },
            {
                "extend": 'excelHtml5',
                "text": '<i class="fa fa-file-excel-o"></i>',
                "titleAttr": 'Excel',
                "filename": "payment_reports",
                "enabled": false
            },
            {
                "extend": 'csvHtml5',
                "text": '<i class="fa fa-file-text-o"></i>',
                "titleAttr": 'CSV',
                "filename": "payment_reports",
                "enabled": false
            },
            {
                "extend": 'pdfHtml5',
                "text": '<i class="fa fa-file-pdf-o"></i>',
                "titleAttr": 'PDF',
                "title": "Payment Reports",
                "filename": "payment_reports",
                "orientation": 'landscape',
                "pageSize": 'LEGAL',
                "enabled": false,
                "customize": function(doc) {
                    doc.styles.title.fontSize = 20;
                    doc.content[1].margin = [100, 20, 100, 0];
                }
            }
        ],
        "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ],
        "pageLength": 10,
        "language": {
        "paginate": {
            "first": "First",
            "last": "Last",
            "next": "Next",
            "previous": "Previous"
        }
    },
        "layout": {
            "top": [
                { "type": "length", "position": "left",  }, // Length changing input (entries per page) left aligned
                { "type": "buttons", "position": "right" } // Buttons right aligned
            ],
            "bottom": [
            { "type": "info", "position": "right" },
            { "type": "pagination", "position": "left" }
        ]
        }
    });
    // $(document).ready(function() {
    //     var screenName = $('#screenNameDropdown').val();
    //     console.log('screenName: ', screenName);
    //     // ajaxCall(screenName)
    //     $('#screenNameDropdown').change(function(){
    //         screenName = $(this).val();
    //         fecthPaymentStatus(screenName)
    //     })

    // })

    $.fn.dataTable.ext.search.push(
        function( settings, data, dataIndex ) {
            settings.bFiltered = false;
            var min = $('#minDate').val();
            var max = $('#maxDate').val();
            // var min = minDate.val();
            var date = data[5];           
            console.log({
                minDate: $('#minDate').val(),
                maxDate: $('#maxDate').val(),
                tableDate: data[5],
                parsedDate: moment(data[5], "DD/MM/YYYY").format("YYYY-MM-DD")
            });
            var parsedMin = min ? new Date(min.split('/').reverse().join('-')) : null;
        var parsedMax = max ? new Date(max.split('/').reverse().join('-')) : null;
        var parsedDate = date ? new Date(date.split('/').reverse().join('-')) : null;

        if (
            (!parsedMin && !parsedMax) ||
            (!parsedMin && parsedDate <= parsedMax) ||
            (parsedMin <= parsedDate && !parsedMax) ||
            (parsedMin <= parsedDate && parsedDate <= parsedMax)
        ) {
                return true;
            }
            return false;
        }
    );

    // function fecthPaymentStatus(screenName) {
    //     const optionToKeep = $('#paymentStatus option:eq(0)');
    //     $('#paymentStatus option').not(optionToKeep).remove();
    //     // if(screenName =="") {
    //     //     const optionToKeep = $('#paymentStatus option:eq(0)');
    //     //     $('#paymentStatus option').not(optionToKeep).remove();
    //     // }else {
    //         console.log('working', screenName);
    //         $.ajax({
    //             url:'./fetchPaymentStatus.php',
    //             data:{'screenName':screenName},
    //             method:'POST',
    //             success:(function(data){
    //                 // let res = JSON.parse(data)
    //                 if(!data) {
    //                     const optionToKeep = $('#paymentStatus option:eq(0)');
    //                     $('#paymentStatus option').not(optionToKeep).remove();
    //                 }
    //                 $('#paymentStatus').append(data);

    //             })
    //         })
    //     // }
    // }


    $(function() {
        $("form[name='registration']").validate({
            rules: {
                screenName: "required",
                minDate:"required",
                maxDate: "required",
                email: {
                    emailRegex: true // Custom rule for email using regex
                },
                paymentStatus:"required"

            },
            messages: {
                screenName: "Please select Payment type",
                minDate: "Please select From date",
                maxDate: "Please select To date",
                password: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long"
                },
                email: {
                    emailRegex: "Please enter a valid email address"
                },
                paymentStatus:"Please Select Payment Status"

            },
            submitHandler: function(form) {
                searchFilter()
            }
        });
        $.validator.addMethod("emailRegex", function(value, element) {
            // Regex pattern for validating email
            return this.optional(element) || /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value);
        }, "Please enter a valid email address");
    });
    function searchFilter() {
        console.log('working');
        $('#searchForm').serializeArray()
        var formData = $('#searchForm').serializeArray().reduce(function(obj, item) {
            obj[item.name] = item.value.trim();
            return obj;
        }, {});

        $.ajax({
            url:'./fetchData.php',
            data:formData,
            method:'POST',
            success: function (data) {
                table.clear().draw();
                table.button().buttons().disable();
                let res = JSON.parse(data)
                console.log(res.html , 'html')
                if(res.html !== "") {
                    // if(res.rawdata.length ==0) {
                    //     const optionToKeep = $('#paymentStatus option:eq(0)');
                    //     $('#paymentStatus option').not(optionToKeep).remove();

                    // }
                    console.log('data', res)
                    if(!data.includes('No data found')) {
                        table.button().buttons().enable();
                        table.rows.add($(res.html)).draw()

                    }
                }
            },
            error: function (textStatus, errorThrown) {
                console.log('errorThrown: ', errorThrown);
                console.log('textStatus: ', textStatus);
            }
        })
    }

    function resetForm() {
        $("form[name='registration']").validate().resetForm();
        const optionToKeep = $('#paymentStatus option:eq(0)');
        table.button().buttons().disable()
        table.clear().draw();
        $('#paymentStatus option[value=""]').prop('disabled', false);
        $('#searchForm')[0].reset();
        // $('#paymentStatus option').not(optionToKeep).remove();

            // Reset datepicker fields
    $('#minDate').datepicker('setDate', null); // Clear the 'From Date'
    $('#maxDate').datepicker('setDate', null); // Clear the 'To Date'

    // Optionally reset the date range restrictions
    $('#minDate').datepicker('setEndDate', new Date());
    $('#maxDate').datepicker('setStartDate', new Date('01/01/1950'));
    }
    $(document).ready(function(){
    $('#paymentStatus').change(function(){
        if ($(this).val() !== "") {
            $('#paymentStatus option[value=""]').prop('disabled', true);
        }
    });
});

function logoutUser() {
    window.location.href = 'logout.php';
}

</script>
</html>
