<?php

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

//register plugin field settings
add_action( 'admin_post_dvs_finance_upload', 'dvs_finance_form_submit' );
function dvs_finance_form_submit() {
    global $wpdb;

    if (($handle = fopen($_FILES['dvs_finance_upload']['tmp_name'], "r")) !== FALSE) {
        $data = fgetcsv($handle, 10000, ",");
        $row = 2;
        while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {

            if ($data[0] == NULL)
            continue;

            if( trim(empty($data[0])) ) {
                wp_redirect(admin_url("admin.php?page=dvs_courier_finance&error=".$row));
                return;
            }
            $row++;
        }
        rewind($handle);
        
        $data = fgetcsv($handle, 10000, ",");

        $error_tracking = '';

        while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {

            $courier = $_POST['dvs_finance_courier'];
            $invoice = $_POST['dvs_finance_invoice'];

            // PROCESS DATA
            $courier    = sanitize_text_field($courier);          
            $tracking   = sanitize_text_field($data[1]);
            $status     = sanitize_text_field($data[2]);
            $cod        = sanitize_text_field($data[3]);
            $fee        = sanitize_text_field($data[4]);         
            $weight     = sanitize_text_field($data[5]);
            $order      = sanitize_text_field($data[6]);
            $invoice    = sanitize_text_field($invoice);

            $status = preg_replace("/[^ A-Za-z]+/", "", $status);
            $cod    = preg_replace("/[^0-9.]+/", "", $cod);
            $fee    = preg_replace("/[^0-9.]+/", "", $fee);

            $courier    = trim($courier);            
            $tracking   = trim($tracking);
            $status     = trim($status);            
            $cod        = trim($cod);
            $fee        = trim($fee);
            $weight     = trim($weight);
            $order      = trim($order);            
            $invoice    = trim($invoice);

            $check_tracking_status  = strtolower($status);

            if($check_tracking_status == 'rider delivered' || $check_tracking_status == "delivered payment in progress") {
                $payment = 'Partial';
            }
            else if ( preg_match("~\bdeliver\b~",$check_tracking_status) || preg_match("~\bdelivered\b~",$check_tracking_status) ) {
                $payment = 'Paid';
            }
            else if ( preg_match("~\breturn\b~",$check_tracking_status) || preg_match("~\breturned\b~",$check_tracking_status) || preg_match("~\bcancel\b~",$check_tracking_status) ) {
                $payment = 'Un-Paid';
            }          
            else {
                $payment = 'Partial';
            }

            $get_tracking_row = $wpdb->get_row("SELECT * FROM dvs_ucp_logs WHERE courier_tracking = '$tracking'");

            if (empty($get_tracking_row)) {
                $error_tracking .= $tracking .',';
            }

            $old_courier_finance = $get_tracking_row->courier_finance;
            $old_courier_finance = json_decode($old_courier_finance, true) ;

            $finance_array = $old_courier_finance;

            $finance_array[] = [
                "order"     => $order,
                "courier"   => $courier,
                "tracking"  => $tracking,
                "status"    => $status,
                "payment"   => $payment,
                "cod"       => (int)$cod,
                "fee"       => (int)$fee,
                "weight"    => $weight,
                "invoice"   => $invoice
            ];

            $new_courier_finance = json_encode($finance_array,JSON_UNESCAPED_UNICODE);

            $dbData = array();
            $dbData['courier_finance'] = $new_courier_finance;
            $wpdb->update('dvs_ucp_logs', $dbData, array('courier_tracking' => $tracking));
        }

        fclose($handle);

        // SAVE FILE
        if ($_FILES) {
            $arr_file_type      = wp_check_filetype($_FILES['dvs_finance_upload']['tmp_name']);
            $uploaded_file_type = $arr_file_type['type'];
            $csv_file_types = array('text/csv', 'text/plain', 'application/csv');
            if (!function_exists('wp_handle_upload')) {
                require_once(ABSPATH . 'wp-admin/includes/file.php');
            }
            $uploadedfile = $_FILES['dvs_finance_upload'];
            if ($_FILES['dvs_finance_upload']['type'] !== 'text/csv'){
                echo 'ERROR, Only upload files in the CSV format!';
            }
            else {
                $upload_overrides = array('test_form' => false);
                $movefile  = wp_handle_upload($uploadedfile, $upload_overrides);
            }
        }

        $old_invoice_logs = get_option('dvs_invoice_logs');
        $old_invoice_logs = json_decode($old_invoice_logs, true) ;
        $invoice_array = $old_invoice_logs;
        $invoice_array[] = [
            "date" => wp_date( 'd F, Y g:i a' ),
            "courier" => $courier,
            "invoice" => $invoice,
            "file" => $movefile['url'],
        ];
        $new_invoice_logs = json_encode($invoice_array,JSON_UNESCAPED_UNICODE);
        update_option('dvs_invoice_logs', $new_invoice_logs);

        if($error_tracking) {
            $error_tracking = substr($error_tracking, 0, -1);
            wp_redirect(admin_url('admin.php?page=dvs_courier_finance&success=1&courier='.$courier.'&invoice='.$invoice.'&error_tracking='.$error_tracking));
        }
        else {
            wp_redirect(admin_url('admin.php?page=dvs_courier_finance&success=1&courier='.$courier.'&invoice='.$invoice));
        }
    }
}   


// DISPLAY FINANCE LOGS
function dvs_courier_finance_logs() {

    $dvs_invoice_logs = get_option('dvs_invoice_logs');

    if(empty($dvs_invoice_logs)) {
        echo '<h2 style="margin-bottom: 10px;">Finance Logs</h2>';
        echo '<p>No Record Found</p>';
        return;
    }

    $dvs_invoice_logs = json_decode($dvs_invoice_logs, true);
    $dvs_invoice_logs = array_reverse($dvs_invoice_logs);
?>
    <h2 style="margin-bottom: 10px;">Finance Logs</h2>
    <div style="width: 650px; max-width: 650px;">
        <table id="dvsfinancelogs" class="wp-list-table widefat striped table-view-list">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Date</th>
                    <th scope="col">Courier</th>
                    <th scope="col">Invoice</th>
                    <th scope="col">File</th>
                </tr>
            </thead>
            <tbody>
            <?php
                $count = 1;
                foreach($dvs_invoice_logs as $log) {
            ?>
                <tr>
                    <td style="padding: 5px 10px !important"><?= $count ?></td>
                    <td style="padding: 5px 10px !important"><?= $log['date'] ?></td>
                    <td style="padding: 5px 10px !important"><?= $log['courier'] ?></td>
                    <td style="padding: 5px 10px !important"><?= $log['invoice'] ?></td>
                    <?php
                    if($log['file']) { ?>
                        <td style="padding: 5px 10px !important"><a href="<?= $log['file'] ?>" download>Download</a></td>
                    <?php
                    }
                    else {
                        echo '<td></td>';
                    }
                    ?>
                </tr>
            <?php
                $count++;
            }
            ?>        
            </tbody>
        </table>
    </div>

    <link href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css" rel="stylesheet" />

    <style>
        .dataTables_length {
            display: none;
        }
        .dataTables_filter {
            margin-bottom: 10px;
        }
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript">
        $(document).ready( function () {
            $('#dvsfinancelogs').DataTable({
                "pageLength": 1000
            });
        } );
    </script>

<?php
}

// UPLOAD FINANCE RECORDS
function dvs_courier_finance_upload() {
?>
<div class="wrap">
<form method="post" action="<?php echo admin_url( 'admin-post.php' ); ?>" enctype="multipart/form-data">
    <?php settings_fields( 'dvs-courier-settings-upload-group' ); ?>
    <?php do_settings_sections( 'dvs-courier-settings-upload-group' ); ?>
    <input type="hidden" name="action" value="dvs_finance_upload">

    <?php if(isset($_GET['success'])): ?>
        <div class="updated notice">
            <p>Finance report for <?php echo $_GET['courier'] ?> with Invoice <?php echo $_GET['invoice'] ?> has been submitted.</p>
        </div>
    <?php endif;?>

    <?php if(isset($_GET['error'])): ?>
        <div class="error notice">
            <p>Error In csv file: Line # <?php echo $_GET['error']?></p>
        </div>
    <?php endif;?>

    <?php if( isset($_GET['error_tracking']) && !empty($_GET['error_tracking']) ): ?>
        <div class="error notice">
            <p>Tracking not found: <?php echo $_GET['error_tracking']?></p>
        </div>
    <?php endif;?>    

    <h2 style="margin-bottom: 10px;">Courier Finance</h2>
    <small>Reconcile finance records of any courier company in Pakistan including TCS, Leoaprds Courier, Trax, M&P Courier, Call Courier, BlueEx, PostEx, Daewoo FastEx, Insta World, Do Deliver, Barq Raftar, Rider TPL, RGS Logistics, Oshi Courier, Bouraq Express, Zaaf Courier, Ship NOC, Couriers Next, Rocket Courier, Falcomail and AHL Courier.</small>
        <table class="form-table">

        <tr>
        <th scope="row">Courier Name</th>
        <td>
            <select id="dvs_finance_courier" name="dvs_finance_courier" required="true">
                <option value="Select">Select Courier</option>
                <option value="TCS">TCS</option>
                <option value="Leopards Courier">Leopards Courier</option>
                <option value="Trax">Trax</option>
                <option value="MNP Courier">MNP Courier</option>
                <option value="Call Courier">Call Courier</option>
                <option value="BlueEx">BlueEx</option>
                <option value="PostEx">PostEx</option>
                <option value="Daewoo Courier">Daewoo Courier</option>
                <option value="Insta World">Insta World</option>
                <option value="Rider">Rider</option>
                <option value="Do Deliver">Do Deliver</option>
                <option value="Barq Raftar">Barq Raftar</option>
                <option value="Bouraq Express">Bouraq Express</option>
                <option value="Oshi Courier">Oshi Courier</option>
                <option value="Zaaf Courier">Zaaf Courier</option>
                <option value="RGS Logistics">RGS Logistics</option>
                <option value="Couriers Next">Couriers Next</option>
                <option value="Falcomail">Falcomail</option>
                <option value="Ship NOC">Ship NOC</option>
                <option value="Couriers Next">Couriers Next</option>
                <option value="AHL Courier">AHL Courier</option>
                <option value="Rocket Courier">Rocket Courier</option>
                <option value="Covered Logistics">Covered Logistics</option>
                <option value="Active Courier">Active Courier</option>
            </select>
        <td>        
        </tr>

        <tr>
        <th scope="row" >Invoice #</th>
        <td>
            <input class="regular-text" type="text" id="dvs_finance_invoice" name="dvs_finance_invoice" required="true" value="" />
        </td>
        </tr>

        <tr>
        <th scope="row" >Upload File (.csv):</th>
        <td>
            <input class="regular-text" type="file" name="dvs_finance_upload" required="true" value="<?php echo esc_attr( get_option('dvs_finance_upload') ); ?>" />
        </td>
        </tr>
    </table>             
    <?php submit_button('Upload'); ?>
</form>
<?php 
$dvs_tracking_sample = plugin_dir_url( __FILE__ ).'sample-finance.csv'; 
echo '<a href="'.$dvs_tracking_sample.'" target="blank">Download Sample File</a>';
?>
<br>
<br>
<a href="<?= admin_url() ?>admin.php?page=dvs_courier_finance" class="woocommerce-Button button">Refresh</a>
<br>
    <h3>Important Note</h3>
    <p>These are the following rules that must be apply before bulk uploading:</p>
    <ul>
        <li><strong>1.</strong> It only accept .csv file format</li>
        <li><strong>2.</strong> Download Sample file and keep the format as it is</li>
        <li><strong>3.</strong> Always upload oldest invoices first</li>
        <li><strong>4.</strong> You can view or export Finance details in courier logs</li>
        <li><strong>5.</strong> Please watch the video guide to avoid errors</li>
    <ul>  
</div>

<br>
<a href="https://www.youtube.com/watch?v=bDAZCRyUtV8" target="blank" class="woocommerce-Button button">Video: How to Upload & Reconcile Courier Finance via CSV</a>
<br>
<br>
<a href="https://devsol.pk/contact/" target="blank" class="woocommerce-Button button">Get Support</a>
<br>
<br>
<a href="https://wa.me/9203234152099" target="blank" class="woocommerce-Button button">WhatsApp Support</a>

<?php 
}