<?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 Out of Hours</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 Out of Hours</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="openAddOutOfHoursModal()" class="ecommerce-sidebar-link btn btn-primary btn-md font-weight-semibold btn-py-2 px-4">+ Add Entry</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">Out of Hours Charges</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>Start Time</th>
<th>End Time</th>
<th>Charge</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$where = $pid ? "WHERE o.api_outofhours_partner_id = $pid" : '';
$sql = "
SELECT o.*, p.api_partner_name
FROM api_outofhours o
LEFT JOIN api_partner p ON o.api_outofhours_partner_id = p.api_partner_id
$where
ORDER BY o.api_outofhours_id DESC
";
$res = $db2->query($sql);
while ($row = mysqli_fetch_assoc($res)) {
    echo "<tr>
        <td>{$row['api_outofhours_id']}</td>
        <td>{$row['api_partner_name']}</td>
        <td>{$row['api_outofhours_start']}</td>
        <td>{$row['api_outofhours_end']}</td>
        <td>{$row['api_outofhours_charge']}</td>
        <td>
            <a href='javascript:void(0);' class='btn btn-xs btn-info' onclick='editOutOfHours({$row['api_outofhours_id']})'>Edit</a>
            <a href='javascript:void(0);' class='btn btn-xs btn-danger ml-2' onclick='deleteOutOfHours({$row['api_outofhours_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="outOfHoursModal" tabindex="-1" role="dialog" aria-labelledby="outOfHoursModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <header class="card-header">
        <h2 class="card-title" id="outOfHoursModalLabel">Out of Hours Entry</h2>
      </header>
      <div class="modal-body">
        <form id="outOfHoursForm">
          <input type="hidden" id="outofhours_id" name="id">
          <div class="form-group">
            <label>Partner</label>
            <select id="outofhours_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>Start Time</label>
            <input type="text" id="outofhours_start" name="start" class="form-control" placeholder="HH:MM" required>
          </div>
          <div class="form-group">
            <label>End Time</label>
            <input type="text" id="outofhours_end" name="end" class="form-control" placeholder="HH:MM" required>
          </div>
          <div class="form-group">
            <label>Charge</label>
            <input type="number" step="0.01" id="outofhours_charge" name="charge" class="form-control" required>
          </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="saveOutOfHours()">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 openAddOutOfHoursModal() {
    $('#outofhours_id').val('');
    $('#outofhours_partner_id').val('');
    $('#outofhours_start').val('');
    $('#outofhours_end').val('');
    $('#outofhours_charge').val('');
    $('#outOfHoursModal').modal('show');
}

function editOutOfHours(id) {
    $.post('actions/get_api_outofhours.php', { id: id }, function (data) {
        $('#outofhours_id').val(data.api_outofhours_id);
        $('#outofhours_partner_id').val(data.api_outofhours_partner_id);
        $('#outofhours_start').val(data.api_outofhours_start);
        $('#outofhours_end').val(data.api_outofhours_end);
        $('#outofhours_charge').val(data.api_outofhours_charge);
        $('#outOfHoursModal').modal('show');
    }, 'json');
}

function saveOutOfHours() {
    const id = $('#outofhours_id').val();
    const partner_id = $('#outofhours_partner_id').val();
    const start = $('#outofhours_start').val();
    const end = $('#outofhours_end').val();
    const charge = $('#outofhours_charge').val();

    const url = id ? 'actions/update_api_outofhours.php' : 'actions/add_api_outofhours.php';

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

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

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

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