<?php
include('include/auth.php');
$pid = isset($_GET['pid']) ? (int)$_GET['pid'] : 0;
?>
<!doctype html>
<html class="fixed dark">
<?php 
$pagerole = "lists";
include('include/head.php');
?>
<body>
<section class="body">
<?php include('include/header.php'); ?>
<div class="inner-wrapper">
<?php include('include/nav.php'); ?>
<section role="main" class="content-body">
<header class="page-header">
<h2>API Locations</h2>
<div class="right-wrapper text-right">
<ol class="breadcrumbs">
<li><a href="index.php"><i class="fas fa-home"></i></a></li>
<li><span>WV Admin</span></li>
<li><span>API Locations</span></li>
</ol>
<a class="sidebar-right-toggle" data-open="sidebar-right"><i class="fas fa-chevron-left"></i></a>
</div>
</header>

<?php if ($userrole == 2) {
    echo "Δεν έχετε Διακαιώματα για αυτή την λειτουργία";
} else { ?>

<div class="row justify-content-center justify-content-sm-between">
<div class="col-sm-auto text-center mb-4 mb-sm-0 mt-2 mt-sm-0">
<a href="#" onclick="openAddLocationModal()" class="ecommerce-sidebar-link btn btn-primary btn-md font-weight-semibold btn-py-2 px-4 disabled" >+ Add Location</a>
</div>
</div>

<h3>Filter by Partner</h3>
<div class="row mb-0">
<div class="col-md-4">
<label>Partner</label>
<select class="form-control populate" onChange="window.location.href=this.value">
<option value="?<?php echo http_build_query(array_merge($_GET, array("pid" => 0))) ?>" <?php if ($pid == 0) echo "selected"; ?>>All Partners</option>
<?php 
$partners = $db2->query("SELECT * FROM api_partner ORDER BY api_partner_name ASC") or die(mysqli_error($db2));
while ($row = mysqli_fetch_array($partners)) {
    $selected = ($pid == $row['api_partner_id']) ? 'selected' : '';
    $query = http_build_query(array_merge($_GET, array("pid" => $row['api_partner_id'])));
    echo "<option value='?$query' $selected>{$row['api_partner_name']}</option>";
}
?>
</select>
</div>
</div>

<div class="row">
<div class="col">
<section class="card">
<header class="card-header">
<h2 class="card-title">Linked Locations</h2>
</header>
<div class="card-body">
<table class="table table-bordered table-striped mb-0" id="datatable-tabletools">
<thead>
<tr>
<th>ID</th>
<th>Partner</th>
<th>Location</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$where = $pid ? "WHERE l.api_locations_partner_id = $pid" : '';
$sql = "
SELECT l.*, p.api_partner_name, pl.name as location_name
FROM api_locations l
LEFT JOIN api_partner p ON l.api_locations_partner_id = p.api_partner_id
LEFT JOIN jostj_vikrentcar_places pl ON l.api_locations_place_id = pl.id
$where
ORDER BY l.api_locations_id DESC
";
$res = $db2->query($sql);
while ($row = mysqli_fetch_assoc($res)) {
    echo "<tr>
        <td>{$row['api_locations_id']}</td>
        <td>{$row['api_partner_name']}</td>
        <td>{$row['location_name']}</td>
        <td>
            <a href='javascript:void(0);' class='btn btn-xs btn-info disabled' onclick='editLocation({$row['api_locations_id']})'>Edit</a>
            <a href='javascript:void(0);' class='btn btn-xs btn-danger ml-2 disabled' onclick='deleteLocation({$row['api_locations_id']})'>Delete</a>
        </td>
    </tr>";
}
?>
                             </tbody>
                                </table>
                            </div>
                        </section>
                    </div>
                </div>
                <?php } ?>
            </section>
        </div>
        <?php include('include/aside.php'); ?>
    </section>

<!-- Modal -->
<div class="modal fade" id="locationModal" tabindex="-1" role="dialog" aria-labelledby="locationModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <header class="card-header">
        <h2 class="card-title" id="locationModalLabel">Link Location</h2>
      </header>
      <div class="modal-body">
        <form id="locationForm">
          <input type="hidden" id="location_id" name="id">
          <div class="form-group">
            <label>Partner</label>
            <select id="location_partner_id" name="partner_id" class="form-control">
              <?php
              $partners = $db2->query("SELECT api_partner_id, api_partner_name FROM api_partner ORDER BY api_partner_name ASC");
              while ($p = mysqli_fetch_array($partners)) {
                echo "<option value='{$p['api_partner_id']}'>{$p['api_partner_name']}</option>";
              }
              ?>
            </select>
          </div>
          <div class="form-group">
            <label>Place</label>
            <select id="location_place_id" name="place_id" class="form-control">
              <?php
              $places = $db2->query("SELECT id, name FROM jostj_vikrentcar_places ORDER BY name ASC");
              while ($pl = mysqli_fetch_array($places)) {
                echo "<option value='{$pl['id']}'>{$pl['name']}</option>";
              }
              ?>
            </select>
          </div>
        </form>
      </div>
      <footer class="card-footer text-right">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" onclick="saveLocation()">Save</button>
      </footer>
    </div>
  </div>
</div>

    <!-- Vendor -->
    <script src="vendor/jquery/jquery.js"></script>
    <script src="vendor/jquery-browser-mobile/jquery.browser.mobile.js"></script>
    <script src="vendor/popper/umd/popper.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.js"></script>
    <script src="vendor/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
    <script src="vendor/common/common.js"></script>
    <script src="vendor/nanoscroller/nanoscroller.js"></script>
    <script src="vendor/magnific-popup/jquery.magnific-popup.js"></script>
    <script src="vendor/jquery-placeholder/jquery.placeholder.js"></script>

    <!-- Specific Page Vendor -->
    <script src="vendor/select2/js/select2.js"></script>
    <script src="vendor/datatables/media/js/jquery.dataTables.min.js"></script>
    <script src="vendor/datatables/media/js/dataTables.bootstrap4.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/dataTables.buttons.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.bootstrap4.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.html5.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/Buttons-1.4.2/js/buttons.print.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/JSZip-2.5.0/jszip.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/pdfmake-0.1.32/pdfmake.min.js"></script>
    <script src="vendor/datatables/extras/TableTools/pdfmake-0.1.32/vfs_fonts.js"></script>


    <!--(remove-empty-lines-end)-->

    <!-- Theme Base, Components and Settings -->
    <script src="js/theme.js"></script>

    <!-- Theme Custom -->
    <script src="js/custom.js"></script>

    <!-- Theme Initialization Files -->
    <script src="js/theme.init.js"></script>

    <!-- Examples -->
    <script src="js/examples/examples.datatables.default.js"></script>

    <script>
        (function ($) {

            'use strict';

            var datatableInit = function () {
                var $table = $('#datatable-tabletools');


                var table = $table.dataTable({
                    
                    "pageLength": 12,
                    sDom: '<"text-right mb-md"T><"row"<"col-lg-6"l><"col-lg-6"f>><"table-responsive"t>p',
                    buttons: [{
                            extend: 'print',
                            text: 'Print'
                        },
                        {
                            extend: 'excel',
                            text: 'Excel'
                        },
                        {
                            extend: 'pdf',
                            text: 'PDF',
                            customize: function (doc) {
                                var colCount = new Array();
                                $('#datatable-tabletools').find('tbody tr:first-child td').each(
                                    function () {
                                        if ($(this).attr('colspan')) {
                                            for (var i = 1; i <= $(this).attr(
                                                'colspan'); $i++) {
                                                colCount.push('*');
                                            }
                                        } else {
                                            colCount.push('*');
                                        }
                                    });
                                doc.content[1].table.widths = colCount;
                            }
                        }
                    ]
                });

                $('<div />').addClass('dt-buttons mb-2 pb-1 text-right').prependTo(
                    '#datatable-tabletools_wrapper');

                $table.DataTable().buttons().container().prependTo('#datatable-tabletools_wrapper .dt-buttons');

                $('#datatable-tabletools_wrapper').find('.btn-secondary').removeClass('btn-secondary').addClass(
                    'btn-default');
            };

            $(function () {
                datatableInit();
            });

        }).apply(this, [jQuery]);
        
        function partalert() {
  alert("Select Partner First!");
}
    </script>
<script>
function openAddLocationModal() {
    $('#location_id').val('');
    $('#location_partner_id').val('');
    $('#location_place_id').val('');
    $('#locationModal').modal('show');
}

function editLocation(id) {
    $.post('actions/get_api_location.php', { id: id }, function (data) {
        $('#location_id').val(data.api_locations_id);
        $('#location_partner_id').val(data.api_locations_partner_id);
        $('#location_place_id').val(data.api_locations_place_id);
        $('#locationModal').modal('show');
    }, 'json');
}

function saveLocation() {
    const id = $('#location_id').val();
    const partner_id = $('#location_partner_id').val();
    const place_id = $('#location_place_id').val();

    const url = id ? 'actions/update_api_location.php' : 'actions/add_api_location.php';

    $.post(url, {
        id,
        partner_id,
        place_id
    }, function (resp) {
        if (resp.success) {
            $('#locationModal').modal('hide');
            location.reload();
        } else {
            alert(resp.error || 'Save failed.');
        }
    }, 'json');
}

function deleteLocation(id) {
    if (!confirm("Are you sure you want to delete this link?")) return;

    $.post('actions/delete_api_location.php', { id: id }, function (resp) {
        if (resp.success) {
            location.reload();
        } else {
            alert(resp.error || 'Delete failed.');
        }
    }, 'json');
}
</script>
</body>

</html>
<?php include('include/footer.php');?>