<?php  
if( ! defined( 'ABSPATH' ) ) exit;
global $wpdb ?>
<h3 class="sync-entries-title">Rented Cars</h3>
<main class="sync_backend_cars">
    <div class="sync-table-cars-rented">
        <br>
        <table class="table table-striped table-sm" id="rented_cars_table">
                <thead>
                    <tr>
                        <th scope="col">Date Rented</th>
                        <th scope="col">Returned Date</th>
                        <th scope="col">Name</th>
                        <th scope="col">Car | Type | Model</th>
                        <th scope="col">Car Image (before released) </th>
                    </tr>
                </thead>
                <tbody>

                    <?php

                        $table_name = $wpdb->prefix . "sync_rent_car_entries";
                        $table_name_car = $wpdb->prefix . "sync_rented_car_images";
                        $entries = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $table_name WHERE status != %s OR status != %s ORDER BY return_date DESC", 'deleted', 'inactive'));
                        
                        if ( ! $entries ) {
                            $wpdb->print_error(); 
                        }else {
                            foreach ( $entries as $key => $value) {
                                $meta = get_post_meta( $entries[0]->car_id, 'easync_car', true );
                                $car_name  = get_post($entries[0]->car_id)->post_title;
                                $car_type = '';
                                $car_model = '';
                                $entries2 = $wpdb->get_results("select * from $table_name_car where transaction_id= '".$value->id."';");
                                
                                if(isset( $meta['type'] )) {
                                    $car_type  = ' | '.$meta['type'];
                                }
                                if(isset( $meta['model'] )) {
                                    $car_model = ' | '.$meta['model'];
                                }

                                ?>
                                <tr>
                                    <td scope="row"><?php echo $value->pick_date; ?></td>
                                    <td><?php echo $value->return_date; ?></td>
                                    <td><?php echo $value->lastname.', '.$value->firstname; ?></td>
                                    <td><?php echo $car_name.''.$car_type.''.$car_model; ?></td>
                                    <td class="image_button">
                                        <?php 
                                            
                                            if (!empty($entries2[0]->transaction_id)) {
                                        ?>
                                            <button type="button" value="<?php echo $value->id; ?>" class="view-car-image btn btn-primary">View Image</button>
                                            
                                        <?php
                                            }
                                            else {
                                        ?>
                                            <button type="button" value="<?php echo $value->id; ?>" class="upload_car_b4 btn-success">Upload</button>

                                        <?php
                                            }
                                        
                                        ?>
                                        
                                    </td>

                                    
                                </tr>
                                <?php
                            }
                        }

                    ?>
                </tbody>
            </table>
    </div>

</main>

<div class="modall fade upload_car_image" id="upload_car_image" tabindex="-1" role="dialog" aria-labelledby="supload_car_imageLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5>Upload Car Image</h5>   
            </div>
            <form id="upload_car_images" method="POST" action="" enctype="multipart/form-data"> 
                <div class="modal-body">      
                    <div class="field">
                        <input class="car_id" name="car_id" type="hidden" value="" >
                        <input type="file" id="file-input" name="files[]" multiple accept="image/jpg, image/jpeg, image/png"/>
                        <div class="remove-btn">
                            <input type="button" value="Remove Images" class="remove btn btn-danger" style="display:none;"> 
                        </div>
                    </div>
                    <div id="thumb-output"></div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary btn-upload" >Upload</button>
                    <button type="button" class="btn btn-default sync-cancel-upload" data-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modall fade view_car_image" id="view_car_image" tabindex="-1" role="dialog" aria-labelledby="view_car_imageLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5>Car Images before Released</h5>   
            </div>
            <div class="modal-body">      
                <div class="view_images" id="view_images">

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success sync-print-btn" onclick="printImages()" >Print Images</button>
                <button type="button" class="btn btn-default sync-close-modal"onclick="closeModal()">Close</button>
            </div>
        </div>
    </div>
</div>

<?php 

if(isset($_FILES['files'])) {

    $table_rented_cars = $wpdb->prefix . 'sync_rented_car_images';
    $image = $_FILES['files']['name'];
    $tmp_name = $_FILES['files']['tmp_name'];
    $trans_id = $_POST['car_id'];
    define ('SITE_ROOT', realpath(dirname(__FILE__)));
    $path = home_url('wp-content/plugins/easync-booking/modules/rented-car-images/');
    

    for ($i = 0; $i < count($tmp_name); $i++) {
        $image_path = $path.''.$image[$i] ;
        if(move_uploaded_file($tmp_name[$i], SITE_ROOT. "/rented-car-images/".$image[$i])) {
            $insert = $wpdb->query("INSERT INTO $table_rented_cars(image_path, transaction_id) VALUES('".$image_path."','".$trans_id."')");
        }
        else {
            echo "<script>alert('Failed to Upload Image/s.');</script>";
        }
    }
}

?>

<script>
    var links = [];
    jQuery(document).ready(function () 
    {
        jQuery(".upload_car_b4").click(function () {
            var car_id = jQuery(this).val();
            jQuery('#upload_car_image').modal('show');
            jQuery(".car_id").val(car_id);
        });

        jQuery('.view-car-image').click(function () {
            var tr_id = jQuery(this).val();
            jQuery('#view_car_image').modal('show');
            jQuery('.view_images').empty();
            links = [];
            jQuery.ajax({
                type: "POST",
                dataType: "json",
                url: easync_admin_ajax_directory.ajaxurl,
                data: { action: "view_image", id: tr_id },
                success: function(data){
                    
                    for(i = 0; i < data.length; i++) {
                        jQuery('.view_images').append('<img class="rented_car_images" src="'+data[i]['image_path']+'">');
                        links.push(data[i]['image_path']);
                    }
                    console.log(links);
                }
            });
        });

        jQuery("#upload_car_images .sync-cancel-upload").click(function () {
            jQuery('#upload_car_images #thumb-output').empty();
            jQuery('#upload_car_images #file-input').val('');
            jQuery('#upload_car_image .remove.btn.btn-danger').hide();
        });

    });

    function closeModal () {
        jQuery('#view_car_image').modal('hide');
    }

    function printImages() {
        var printContent = document.getElementById('view_images').innerHTML;
        var allContent = document.body.innerHTML;
        document.body.innerHTML = printContent;
        window.print();
        document.body.innerHTML = allContent;
        window.onunload = window.location.reload();
    }


</script>

