<?php

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


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

    // PRINT & DOWNLOAD BTN
    if (isset($_POST['hxs_print_loadsheet_btn']) || isset($_POST['hxs_download_loadsheet_btn'])) {
        $selected_row = $_POST['selected_row'];
        $orders = $_POST['order'];

        if (isset($orders[$selected_row])) {
            $single_order   = $orders[$selected_row];
            $courier_name   = $single_order['courier_name'];
            $courier_key    = get_courier_key($courier_name);
            $courier_logo   = plugin_dir_url( __DIR__ ) . "images/{$courier_key}-label-logo.png";
            $loadsheet_date = $single_order['courier_datetime'];
            $order_ids      = explode(',', $single_order['ids']);

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

            $bookings = new CourierBooking($args);
            $bookings->paginate_by = 500;
            $parameters[] = [
                'key' => 'id',
                'value' => '(' . implode(',', $order_ids) . ')',
                'operator' => 'IN',
            ];
            $parcels = $bookings->get($parameters);

            if ($parcels) {
                
                if(isset($_POST['hxs_print_loadsheet_btn'])) {
                    include_once("dvs-ucp-loadsheet-template.php");
                    die();
                }
                
                if(isset($_POST['hxs_download_loadsheet_btn'])) {
                    $rows = [];
                    $rows[] = [
                        'Booked',
                        'Order',
                        'Name', 
                        'Phone',
                        'Address',
                        "City",
                        "Order Total",
                        "Order COD",
                        "Courier Name",
                        "Courier Tracking",
                        "Weight",
                        "Service",
                        "Products",
                    ];
                    foreach ($parcels as $parcel){
                        $rows[] = [
                            $parcel->courier_datetime,
                            $parcel->order_name,
                            $parcel->consignee_name,
                            $parcel->consignee_phone,
                            $parcel->consignee_address,
                            $parcel->courier_destination,
                            $parcel->order_total,
                            $parcel->order_amount,
                            $parcel->courier_name,
                            $parcel->courier_tracking,
                            $parcel->order_weight,
                            $parcel->courier_service,
                            $parcel->order_products,
                        ];
                    }
                    header('Content-Type: text/csv');
                    header('Content-Disposition: attachment; filename="loadsheet-report-'.$loadsheet_date.'.csv";');
                    header('Pragma: no-cache');
                    header("Expires: 0");        
                    $f = fopen('php://output', 'w'); 
                    foreach ($rows as $line) { 
                        fputcsv($f, $line); 
                    }
                }
            }
            die();
        }
    }
}


function dvs_ucp_loadsheet_logs_page() {

    // $courier_logo = "{$courier_folder}-label-logo.png";
    $parameters = [];
    $args = [
        'shop_url' => get_home_url(),
    ];

    $CourierLoadsheet = new CourierLoadsheet($args);
    $CourierLoadsheet->paginate_by = 50;
    $page = $_GET['hxs_page'] ?? 1;
    $last_seen = $_GET['hxs_last_seen'] ?? null;
    $dir = $_GET['hxs_dir'] ?? null;

    $loadsheets = $CourierLoadsheet->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;                
            }
            .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;
            }                       
        </style>

    </head>
<body>

<div class="container-fluid">

    <div class="row mt-4">
        <div class="col mt-2">
            <?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 = $CourierLoadsheet->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=<?= CourierLoadsheet::$NEXT ?>" class="btn btn-dark float-end">Next</a>
            <?php }
            if ($prev_page = $CourierLoadsheet->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=<?= CourierLoadsheet::$PREV ?>" class="btn btn-dark me-2 float-end">Back</a>
            <?php }
            ?>
        </div>
    </div>

    <form method="POST" action="" id="hxs-loadsheet-logs-form">
        <input type="hidden" name="selected_row" id="selected_row" value="">
        <div class="row" style="max-width:900px;margin:0 auto">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h5 class="fw-bold mb-0">Loadsheets</h5>

                <a href="https://www.youtube.com/watch?v=j8F7vY52X60" class="btn btn-secondary" target="_blank">
                    Video Guide
                </a>
            </div>
            <table class="table table-bordered table-sm table-responsive hxs-upload-table">
                <thead class="table-dark" style="text-align: center;">
                    <tr>
                        <th class="text-center" scope="col">#</th>
                        <th scope="col">Date</th>
                        <th scope="col">Courier</th>
                        <th scope="col">Shipments</th>
                        <th scope="col">Total Amount</th>
                        <th scope="col">Total COD</th>
                        <th scope="col">Action</th>
                    </tr>
                </thead>

                <tbody>
                    <?php
                    $count = 1;
                    $dvs_ucp_courier_pagination = 50;
                    $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 ($loadsheets as $loadsheet) {
                        $courier_id       = $loadsheet->id;
                        $courier_datetime = $loadsheet->courier_datetime;
                        $courier_name     = $loadsheet->courier_name;
                        $courier_count    = $loadsheet->courier_count;
                        $courier_total    = $loadsheet->courier_total;
                        $courier_cod      = $loadsheet->courier_cod;
                        $courier_ids      = json_decode($loadsheet->courier_ids, true);
                    ?>
                        <tr>
                            <td class="text-center" width="5%">
                                <input type="text" class="form-control form-control-sm text-center" readonly id="<?= $count ?>" name="<?= $count ?>" value="<?= $count ?>" />
                                <input type="hidden" name="order[<?= $count ?>][id]" value="<?= $courier_id ?>" />
                                <input type="hidden" name="order[<?= $count ?>][ids]" value="<?= implode(',', $courier_ids) ?>" />
                            </td>
                            <td>
                                <input type="text" class="form-control form-control-sm text-center" readonly id="" name="order[<?= $count ?>][courier_datetime]" value="<?= $courier_datetime ?>" />
                            </td>
                            <td>
                                <input type="text" class="form-control form-control-sm" readonly id="" name="order[<?= $count ?>][courier_name]" value="<?= $courier_name ?>" />
                            </td>

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

                            <td>
                                <input type="text" class="form-control form-control-sm text-center" readonly id="" name="" value="Rs <?= (int)$courier_total ?>" />
                            </td>

                            <td>
                                <input type="text" class="form-control form-control-sm text-center" readonly id="" name="" value="Rs <?= (int)$courier_cod ?>" />
                            </td>
                            <td>
                                <div class="d-flex gap-2">
                                    <button class="btn btn-sm btn-outline-success"
                                            name="hxs_print_loadsheet_btn"
                                            id="hxs_print_loadsheet_btn"
                                            type="submit"
                                            onclick="document.getElementById('selected_row').value = '<?= $count ?>'">
                                        Print
                                    </button>
                                    <button class="btn btn-sm btn-outline-secondary"
                                            name="hxs_download_loadsheet_btn"
                                            id="hxs_download_loadsheet_btn"
                                            type="submit"
                                            onclick="document.getElementById('selected_row').value = '<?= $count ?>'">
                                        Download
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php
                        $count++;
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </form>
</div>

<script type="text/javascript">
    $(function() {
        $('#hxs_print_loadsheet_btn').click(function(e){
            $("#hxs-loadsheet-logs-form").attr('target', '_blank');
        })
    });
</script>
</body> 
<?php
}