<?php

if ( ! defined( 'ABSPATH' ) ) exit;


add_action('admin_init', 'dvs_ucp_create_loadsheet');
function dvs_ucp_create_loadsheet() {

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

        $courier_name = $_POST['courier_name'];
        $orders = $_POST['order'];
        foreach ($orders as $order) {
            if (isset($order['check'])) {
                $trackings[] = $order['tracking'];
                $order_ids[] = $order['id'];
                $param_order_ids[] = "'{$order['id']}'";
            }
        }

        $args = [
            'shop_url' => get_home_url(),
            'courier_name' => $courier_name,
        ];

        $bookings = new CourierBooking($args);
        $bookings->paginate_by = 500;

        $parcels = [];
        
        $parameters[] = [
            'key' => 'id',
            'value' => '(' . implode(',', $param_order_ids) . ')',
            'operator' => 'IN',
        ];
        $parcels = $bookings->get($parameters);

        if ($parcels) {
            $courier_total = 0;
            $courier_cod = 0;

            foreach ($parcels as $parcel) {
                global $wpdb;
                $dbData = array();
                $dbData['courier_status'] = 'loadsheet';
                $wpdb->update('dvs_ucp_logs', $dbData, array('id' => $parcel->id));

                $courier_total += $parcel->order_total;
                $courier_cod += $parcel->order_amount;
            }

            date_default_timezone_set('Asia/Karachi');
            $loadsheet_date = date("d-m-Y h:i A");            

            $loadsheet_param = [
                'courier_name'      => $courier_name,
                'courier_datetime'  => $loadsheet_date,
                'courier_count'     => count($parcels),
                'courier_total'     => $courier_total,
                'courier_cod'       => $courier_cod,
                'courier_ids'       => json_encode($order_ids),
            ];
            dvs_ucp_add_loadsheet($loadsheet_param);
            wp_safe_redirect(admin_url("admin.php?page=dvs_ucp_loadsheet_logs"));

        }
    }
    return;
}


function dvs_ucp_create_loadsheet_page($courier_name, $courier_folder) {
    dvs_ucp_common_loadsheet_page($courier_name, $courier_folder);
}

function dvs_ucp_common_loadsheet_page($courier_name, $courier_folder) {
    $parameters = [];
    $form_date = "";
    $form_order = "";
    $form_tracking = "";
    $form_status = "";
    $form_status_type = "";
            
    if (isset($_GET['hxs_search_btn'])) { 
        if (isset($_GET['hxs_order']) && !empty($_GET['hxs_order'])) {
            $form_order = $_GET['hxs_order'];
            $orders_array = explode(',', $_GET['hxs_order']);
            foreach ($orders_array as $i => $order_name) {
                $orders_array[$i] = "'" . trim($order_name) . "'";
            }
            $parameters[] = [
                'key' => 'order_name',
                'value' => '(' . implode(',', $orders_array) . ')',
                'operator' => 'IN',
            ];
        }
        if (isset($_GET['hxs_tracking']) && !empty($_GET['hxs_tracking'])) {
            $form_tracking = $_GET['hxs_tracking'];
            $tracking_arr = explode(',', $_GET['hxs_tracking']);
            foreach ($tracking_arr as $i => $tracking_name) {
                $tracking_arr[$i] = "'" . trim($tracking_name) . "'";
            }
            $parameters[] = [
                'key' => 'courier_tracking',
                'value' => '(' . implode(',', $tracking_arr) . ')',
                'operator' => 'IN',
            ];
        }       
        if (isset($_GET['hxs_date']) && !empty($_GET['hxs_date'])) {
            $form_date = $_GET['hxs_date'];
            $created_at_min = substr($_GET['hxs_date'], 0, 10) . ' 00:00:00';
            $created_at_max = substr($_GET['hxs_date'], -10) . ' 23:59:59';
            $parameters[] = [
                'key' => 'courier_datetime',
                'value' => "'{$created_at_min}' AND '{$created_at_max}'",
                'operator' => 'BETWEEN',
            ];
        }
    }

    $parameters[] = [
        'key' => 'courier_status',
        'value' => 'active',
        'operator' => '=',
    ];

    $bookings = new CourierBooking([
        'shop_url' => get_home_url(),
        'courier_name' => $courier_name,
    ]);

    $paginate_number = 500;
    $bookings->paginate_by = $paginate_number;
    $page = $_GET['hxs_page'] ?? 1;
    $last_seen = $_GET['hxs_last_seen'] ?? null;
    $dir = $_GET['hxs_dir'] ?? null;    
    $parcels = $bookings->get($parameters, [], $page, $last_seen, $dir);
    $current_page = admin_url("admin.php");

    ?>

    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">  
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

        <style>
            .hxs-upload-table tr {
                font-size: 14px;
            }

            .hxs-upload-table td {
                padding: 2px 3px !important;
            }

            .hxs-upload-table .form-control {
                font-size: 13px;
                border: none;
            }
            .form-check-input:checked {
                background-color: unset;
            }
            .nav-link {
                padding: 0px 15px !important;
                margin-top: 5px !important;
                color: #888888 !important;
            }
            .nav-link.active {
                color: #198754 !important;
                background-color: transparent !important;
                border: 1px solid #198754 !important;
            }
            .dvs_log_modal p {
                font-size: 12px;
                margin-bottom: 5px;
            }
            .dvs_log_finance {
                font-size: 12px;
            }
            .finance_btn {
                width: 100%;
                padding: 0px;
                margin-top: 3px;                
            }
            .hxs-upload-table .btn-outline-secondary {
                opacity: 0.3;
            }
            .dvs-table-stats th {
                padding-left: 15px;
                background-color: #eeeeee;
                font-weight: 500;
            }           
            .dvs-table-stats td {
                text-align: center;
            }
            .dvs_courier_stats_head {
                width: 100%;
                text-align: center;
                float: left;
                background-color: #000000;
                color: #ffffff;
                padding: 5px 0px;
                font-weight: bold;              
            }
            .dvs-table-stats td {
                font-size: 13px;
            }
            .dvs-table-stats-couriers th {
                font-size: 12px;
                padding-left: 15px;
                background-color: #eeeeee;              
            }           
            .dvs-table-stats-couriers td {
                font-size: 12px;
                text-align: center;
            }
            .dvs-btn-woo {
                background-color: #720EEC;
                border-color: #720EEC;
            }                               
        </style>

        <script>
        $(document).on("click", "#hxs_print_btn", function() {
            $('#hxs_date').prop('required',false);
            $('#hxs_delivery').prop('required',false);
        });
        </script>
    </head>
<body>

<?php
    $dvs_admin_url = get_admin_url(null, 'admin.php?page=dvs_ucp_'.$courier_folder.'_loadsheet');
?>

<div class="container-fluid mt-2">
    <div class="row">
        <div class="col-12 text-center">
            <img 
                src="<?php echo plugin_dir_url(__DIR__) . "images/{$courier_folder}-label-logo.png"; ?>" 
                alt="Universal Courier" 
                height="35"
                style="display:block;margin:0 auto;"
            >
            <div style="
                font-size:14px;
                background-color:#e3e3e3;
                color:#303030;
                padding:2px 10px;
                border-radius:30px;
                display:inline-block;
                margin-top:5px;
            ">
                Create Loadsheet
            </div>
        </div>
    </div>
</div>


<div class="dvs-upload-table mb-4">
    <br>
    <div class="container-fluid">
        <div class="row">
            <div id="hxs-form-filters pe-0" class="col-7">
                <form class="input-group" method="get" action=""  id="hxs-sheet-form courier-name-all">
                    <?php
                    foreach ($_GET as $key => $value) {
                        if (in_array($key, ['hxs_page', 'hxs_last_seen', 'hxs_dir']))
                            continue;
                        $key = htmlspecialchars($key);
                        $value = htmlspecialchars($value);
                        echo "<input type='hidden' name='$key' value='$value'/>";
                    }
                    ?>
                    <input class="form-control" type="text" name="hxs_date" value="<?= $form_date ?>" autocomplete="off" placeholder="Date Range">
                    <input class="form-control" type="text" name="hxs_order" value="<?= $form_order ?>" autocomplete="off" placeholder="Order #">
                    <input class="form-control" type="text" name="hxs_tracking" value="<?= $form_tracking ?>" autocomplete="off" placeholder="Tracking">
                    <input class="form-control" type="text" name="hxs_delivery" value="Status = Booked" autocomplete="off" placeholder="">
                    <button class="btn btn-success" name="hxs_search_btn" type="submit">Filter</button>
                </form>
            </div>

            <div class="col-5 ps-0">
                <?php 
                    $get_params_without_hxs_pagination = '?';
                    foreach ($_GET as $key => $value) {
                        if (!in_array($key, ['hxs_page', 'hxs_last_seen', 'hxs_dir']))
                            $get_params_without_hxs_pagination .= $key . "=" . $value . '&';
                    }
                ?>
                 <?php if ($next_page = $bookings->get_next()){ ?>
                    <a href="<?= $current_page ?><?= $get_params_without_hxs_pagination ?>hxs_page=<?= $next_page['page_num'] ?>&hxs_last_seen=<?= $next_page['last_seen']?>&hxs_dir=<?= CourierBooking::$NEXT ?>" class="btn btn-outline-primary float-end">Next</a>
        
                <?php } if ($prev_page = $bookings->get_prev()){ ?>
                    <a href="<?= $current_page ?><?= $get_params_without_hxs_pagination ?>hxs_page=<?= $prev_page['page_num'] ?>&hxs_last_seen=<?= $prev_page['last_seen']?>&hxs_dir=<?= CourierBooking::$PREV ?>" class="btn btn-outline-primary me-2 float-end">Back</a>
                <?php } ?> 

    <form class="" method="post" action="" id="hxs-sheet-form">
                        <button class="btn btn-primary dvs-btn-woo float-start ms-2 me-3" id="hxs_create_loadsheet_btn" name="hxs_create_loadsheet_btn" type="submit">Create Loadsheet</button>
                        <a href="https://www.youtube.com/watch?v=j8F7vY52X60" class="btn btn-outline-secondary" target="_blank">Video Guide</a>

            </div>

        </div> <!-- end row -->
    </div> <!-- end container-fluid -->   

        <table class="table table-bordered table-sm table-responsive hxs-upload-table mt-2">
            <thead class="table-dark" style="text-align: center;">
                <tr>
                    <th scope="col"><input type="checkbox" class="form-check-input bulkcheckbox" value="" id="bulkcheckbox" name="bulkcheckbox"></th>
                    <th scope="col">#</th>
                    <th scope="col">Date</th>
                    <th scope="col">Order</th>
                    <th scope="col">Name</th>
                    <th scope="col">Phone</th>
                    <th scope="col">Address</th>
                    <th scope="col">City</th>
                    <th scope="col">COD</th>
                    <th scope="col">Amount</th>
                    <th scope="col">Tracking</th>
                    <th scope="col">Status</th>
                </tr>
            </thead>

            <tbody>
                <?php
                $count = 1;
                $dvs_ucp_courier_pagination = $paginate_number;
                $dvs_ucp_courier_pagination_minus = $dvs_ucp_courier_pagination - 1;
                
                if (isset($_GET['hxs_page'])) {
                    $dvs_current_page = $_GET['hxs_page'];
                    if ($dvs_current_page == 2 ) {
                        $count = $dvs_ucp_courier_pagination + 1;
                    }
                    if ($dvs_current_page > 2 ) {
                        $count = ($dvs_current_page * $dvs_ucp_courier_pagination) - $dvs_ucp_courier_pagination_minus;
                    }                
                }
                else {
                    $count = 1;
                }

                foreach ($parcels as $parcel) {
                    $order_datetime = $parcel->courier_datetime;
                    $dvs_parcel_days = get_post_meta($parcel->order_id, '_dvs_parcel_days', true);
                    $order_name = $parcel->order_name;
                    $order_id = $parcel->order_id;
                    $consignee_name = $parcel->consignee_name;
                    $consignee_phone = $parcel->consignee_phone;
                    $consignee_address = $parcel->consignee_address;
                    $courier_destination = $parcel->courier_destination;
                    $order_products = $parcel->order_products;
                    $order_total = $parcel->order_total;
                    $order_amount = $parcel->order_amount;
                    $courier_title = $parcel->courier_name;
                    $courier_tracking = $parcel->courier_tracking;
                    $courier_link = get_post_meta($parcel->order_id, '_dvs_courier_link', true);
                    $courier_delivery = $parcel->courier_delivery;
                ?>

                    <tr>
                        <td width="2%">
                            <input type="checkbox" class="form-check-input singlecheckbox" value="" id="check_<?= $count ?>" name="order[<?= $count ?>][check]">
                        </td>

                        <td width="4%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="<?= $count ?>" name="<?= $count ?>" value="<?= $count ?>" />
                        </td>

                        <td width="12%">
                            <input type="hidden" class="form-control form-control-sm hxs-center" readonly id="" name="order[<?= $count ?>][id]" value="<?= $parcel->id ?>" required />

                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="<?= substr($order_datetime, 0, -3) ?>" required />
                        </td>

                        <td width="8%">
                            <a class="form-control form-control-sm text-center"  href="<?php echo site_url() ?>/wp-admin/post.php?post=<?php echo $order_id ?>&action=edit" target="blank" style="background-color: #e9ecef;text-decoration: none;"><?= $order_name ?></a>
                        </td>

                        <td width="10%">
                            <input type="text" class="form-control form-control-sm" readonly id="" name="" value="<?= $consignee_name ?>" required />
                        </td>

                        <td width="10%">
                            <?php

                                $dvs_ucp_wa_text = get_option('dvs_ucp_wa_tracking_text');

                                if($dvs_ucp_wa_text) {
                                    $whatsapp_text = $dvs_ucp_wa_text;
                                    $whatsapp_text = str_replace("[order_number]", $order_name, $whatsapp_text);
                                    $whatsapp_text = str_replace("[order_total]", (int)$order_total, $whatsapp_text);
                                    $whatsapp_text = str_replace("[customer_name]", $consignee_name, $whatsapp_text);
                                    $whatsapp_text = str_replace("[courier_name]", $courier_title, $whatsapp_text);
                                    $whatsapp_text = str_replace("[courier_tracking]", $courier_tracking, $whatsapp_text);
                                    $whatsapp_text = str_replace("[courier_link]", $courier_link, $whatsapp_text);
                                }
                                else {
                                    $whatsapp_text = "Dear ".$consignee_name.", your order #".$order_name." has been shipped. Courier is ".$courier_name." with Tracking ".$courier_tracking.". Get Live tracking: ".site_url()."/track/";
                                }

                                $whatsapp_text = urlencode($whatsapp_text);

                                $custphone = trim($consignee_phone);
                                $custphone = str_replace(["O","o"],['0','0'],$custphone);
                                $custphone = preg_replace("/[^0-9]+/", "", $custphone);                         
                            ?>

                            <a class="form-control form-control-sm text-center" 
                               href="https://wa.me/92<?php echo $custphone ?>?text=<?php echo $whatsapp_text; ?>" 
                               target="_blank" 
                               style="background-color: #e9ecef; text-decoration: none;">
                                <?= $consignee_phone ?>
                            </a>
                        </td>

                        <td width="10%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="<?= $consignee_address ?>" required />
                        </td>

                        <td width="10%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="<?= $courier_destination ?>" required />
                        </td>

                        <td width="6%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="Rs <?= substr($order_amount, 0, -3) ?>" required />
                        </td>

                        <td width="6%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly id="" name="" value="Rs <?= substr($order_total, 0, -3) ?>" required />
                        </td>                        

                        <td width="12%">
                            <?php
                            add_thickbox();
                            echo'<a href="#TB_inline?width=650&height=600&inlineId=dvs-content-track" class="thickbox form-control form-control-sm hxs-center" onclick="dvstrackparcel(\'' . $order_id . '\', \'' . $parcel->courier_name . '\', \'' . $courier_tracking . '\')" style="text-align: center;text-decoration: none; background-color:#e9ecef; color:#198754;">'.$courier_tracking.'</a>'; 
                            ?>
                            <input type="hidden" class="form-control form-control-sm hxs-center" readonly id="tracking_<?= $count ?>" name="order[<?= $count ?>][tracking]" value="<?= $courier_tracking ?>" required />
                        </td>

                        <td width="12%">
                            <input type="text" class="form-control form-control-sm hxs-center" readonly value="<?= $courier_delivery ?>" required />
                        </td>
                    </tr>
                <?php
                    $count++;
                }
                ?>
            </tbody>
        </table>
        <input type="hidden" name="courier_name" value="<?= $courier_name ?>" />
    </form>

    <div id="dvs-content-track" style="display:none;">
        <div class="track-thickbox">
            <center><img src="<?php echo plugin_dir_url( __DIR__ ) . 'images/loader.gif'; ?>"></center>
        </div>
    </div>

    <style>
        #TB_window {
            width: auto !important;
        }
    </style>    



    <!-- LOADSHEET TOAST -->
    <div class="position-fixed top-50 start-50 translate-middle shadow-lg" style="z-index:1080;">
        <div id="noSelectionToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header bg-warning text-dark">
                <strong class="me-auto fw-bold">Notice</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body bg-white">
                ⚠️ Please select at least one order.
            </div>
        </div>
    </div>


    <!-- LOADSHEET MODAL -->
    <div class="modal fade" id="confirmLoadsheetModal" tabindex="-1" aria-labelledby="confirmLoadsheetLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
            <div class="modal-header bg-warning text-dark py-2">
                <h6 class="modal-title fw-bold" id="confirmLoadsheetLabel">Confirm Loadsheet Generation</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
            This action will change the parcels status to <strong>"Loadsheet"</strong><br>
            Are you sure you want to continue?
            </div>
            <div class="modal-footer d-flex justify-content-between">
                <button type="button" class="btn btn-success" id="confirmYesBtn" data-bs-dismiss="modal">Confirm</button>
                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">No</button>
            </div>
            </div>
        </div>
    </div>

<!--     <script>
        let loadsheetConfirmed = false;
        document.getElementById('hxs_create_loadsheet_btn').addEventListener('click', function(e) {
            if (!loadsheetConfirmed) {
                e.preventDefault();
                const modal = new bootstrap.Modal(document.getElementById('confirmLoadsheetModal'));
                modal.show();
            }
        });
        document.getElementById('confirmYesBtn').addEventListener('click', function() {
            loadsheetConfirmed = true;
            document.getElementById('hxs_create_loadsheet_btn').click();
        });
    </script> -->


    <script>
        let loadsheetConfirmed = false;

        document.getElementById('hxs_create_loadsheet_btn').addEventListener('click', function (e) {
            const checkboxes = document.querySelectorAll('.singlecheckbox:checked');

            if (checkboxes.length === 0) {
                e.preventDefault();

                const toastEl = document.getElementById('noSelectionToast');
                const toast = new bootstrap.Toast(toastEl, {
                    delay: 3000,
                    autohide: true
                });
                toast.show();
                return;
            }

            if (!loadsheetConfirmed) {
                e.preventDefault();
                const modal = new bootstrap.Modal(
                    document.getElementById('confirmLoadsheetModal')
                );
                modal.show();
            }
        });

        document.getElementById('confirmYesBtn').addEventListener('click', function () {
            loadsheetConfirmed = true;
            const modalEl = document.getElementById('confirmLoadsheetModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            modalInstance.hide();
            document.getElementById('hxs_create_loadsheet_btn').click();
        });
    </script>




    <script type="text/javascript">
        jQuery(function($) {
            $('body').on('change', '#bulkcheckbox', function(e) {
                $('.singlecheckbox').prop('checked', e.currentTarget.checked);
                $('.singlecheckbox').change();
            });
        });
    </script>

    <script type="text/javascript">
        $(function() {
            $('input[name="hxs_date"]').daterangepicker({
                autoUpdateInput: <?php echo empty($form_date) ? 'false' : 'true' ?>,
                locale: {
                    cancelLabel: 'Clear',
                    format: "YYYY-MM-DD",
                }
            });

            $('input[name="hxs_date"]').on('apply.daterangepicker', function(ev, picker) {
                $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            });

            $('input[name="hxs_date"]').on('cancel.daterangepicker', function(ev, picker) {
                $(this).val('');
            });

            $('#sync_btn').click(function(e){
                $('#sync_btn').html('<div class="spinner-border" role="status" style="width:1.5rem !important;height:1.5rem !important;"></div>');
            })
        });
    </script>
</body>
<?php
}