<?php 
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/php-error.log');
include('include/auth.php');
$pid = isset($_GET['pid']) ? (int)$_GET['pid'] : 0;
$lid = isset($_GET['lid']) ? (int)$_GET['lid'] : 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 ACRISS Location Modifiers</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>ACRISS Location Modifiers</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="openAddModifierModal()" class="ecommerce-sidebar-link btn btn-primary btn-md font-weight-semibold btn-py-2 px-4">+ Add Modifier</a>
                    </div>
                </div>

                <h3>Filters</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 
                            $sqlin2 = $db2->query("SELECT * FROM api_partner ORDER BY api_partner_name ASC") or die(mysqli_error($db2));
                            while ($rowin2 = mysqli_fetch_array($sqlin2)) {
                                $selected = ($pid == $rowin2['api_partner_id']) ? 'selected' : '';
                                $query = http_build_query(array_merge($_GET, array("pid" => $rowin2['api_partner_id'])));
                                echo "<option value='?$query' $selected>{$rowin2['api_partner_name']}</option>";
                            }
                            ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label>Location</label>
                        <select class="form-control populate" onChange="window.location.href=this.value">
                            <option value="?<?php echo http_build_query(array_merge($_GET, array("lid" => 0))) ?>" <?php if ($lid == 0) echo "selected"; ?>>All Locations</option>
                            <?php 
                            $res = $db2->query("SELECT id, name FROM jostj_vikrentcar_places ORDER BY name ASC");
                            while ($r = mysqli_fetch_array($res)) {
                                $selected = ($lid == $r['id']) ? 'selected' : '';
                                $query = http_build_query(array_merge($_GET, array("lid" => $r['id'])));
                                echo "<option value='?$query' $selected>{$r['name']}</option>";
                            }
                            ?>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <section class="card">
                            <header class="card-header">
                                <h2 class="card-title">Modifiers Table</h2>
                            </header>
                            <div class="card-body">
                                <table class="table table-bordered table-striped mb-0" id="datatable-tabletools">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Location</th>
                                            <th>ACRISS Code</th>
                                            <th>Modifier (%)</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                $whereParts = [];
if ($pid != 0) {
    $whereParts[] = "m.partner_id = $pid";
}
if ($lid != 0) {
    $whereParts[] = "m.location_id = $lid";
}
$whereClause = $whereParts ? 'WHERE ' . implode(' AND ', $whereParts) : '';

$sql = "
    SELECT m.*, l.name AS location_name, p.api_partner_name
    FROM api_acriss_location_modifiers m
    LEFT JOIN jostj_vikrentcar_places l ON m.location_id = l.id
    LEFT JOIN api_partner p ON m.partner_id = p.api_partner_id
    $whereClause
    ORDER BY m.id DESC
";

                                    $res = $db2->query($sql) or die(mysqli_error($db2));
                                    while ($row = mysqli_fetch_assoc($res)) {
                                      echo "<tr>
  <td>{$row['id']}</td>
  <td>{$row['api_partner_name']}</td>
  <td>{$row['location_name']}</td>
  <td>{$row['acriss_code']}</td>
  <td>{$row['modifier_percent']}</td>
  <td>
    <a href='javascript:void(0);' class='btn btn-xs btn-info' onclick='editModifier({$row['id']})'>Edit</a>
    <a href='javascript:void(0);' class='btn btn-xs btn-danger ml-2' onclick='deleteModifier({$row['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="modifierModal" tabindex="-1" role="dialog" aria-labelledby="modifierModalLabel" aria-hidden="true">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                      <header class="card-header">
                        <h2 class="card-title" id="modifierModalLabel">Modifier Details</h2>
                      </header>
                      <div class="modal-body">
                        <form id="modifierForm">
                          <input type="hidden" id="modifierId" name="id">

                          <div class="form-group">
                            <label>Partner</label>
                            <select id="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>Location</label>
                            <select id="location_id" name="location_id" class="form-control">
                              <?php
                                $res = $db2->query("SELECT id, name FROM jostj_vikrentcar_places ORDER BY name ASC");
                                while($r = mysqli_fetch_array($res)) {
                                  echo "<option value='{$r['id']}'>{$r['name']}</option>";
                                }
                              ?>
                            </select>
                          </div>

                          <div class="form-group">
                            <label>ACRISS Code</label>
                            <select id="acriss_code" name="acriss_code" class="form-control" required>
  <option value="">Select ACRISS</option>
</select>
                          </div>

                          <div class="form-group">
                            <label>Modifier %</label>
                            <input type="number" step="0.01" id="modifier_percent" name="modifier_percent" 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="saveModifier()">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 openAddModifierModal() {
    $('#modifierId').val('');
    $('#partner_id').val('');
    $('#location_id').val('');
    $('#acriss_code').html('<option value="">Select ACRISS</option>');
    $('#modifier_percent').val('');
    $('#modifierModal').modal('show');
}

function editModifier(id) {
    $.post('actions/get_api_acriss_location_modifiers.php', { id: id }, function (data) {
        if (data && data.id) {
            $('#modifierId').val(data.id);
            $('#partner_id').val(data.partner_id);
            $('#location_id').val(data.location_id);
            $('#modifier_percent').val(data.modifier_percent);

            // Fetch ACRISS options and preselect value
            fetchAcrissOptions(data.partner_id, data.acriss_code);

            $('#modifierModal').modal('show');
        } else {
            alert('Modifier not found.');
        }
    }, 'json').fail(function (xhr) {
        console.error(xhr.responseText);
        alert('Error fetching modifier.');
    });
}

function fetchAcrissOptions(partnerId, selectedCode = '') {
    if (!partnerId) {
        $('#acriss_code').html('<option value="">Select ACRISS</option>');
        return;
    }

    $('#acriss_code').html('<option value="">Loading...</option>');

    $.post('actions/get_partner_acriss.php', { partner_id: partnerId }, function (data) {
        let options = '<option value="">Select ACRISS</option>';
        data.forEach(code => {
            const selected = code === selectedCode ? 'selected' : '';
            options += `<option value="${code}" ${selected}>${code}</option>`;
        });
        $('#acriss_code').html(options);
    }, 'json').fail(function () {
        $('#acriss_code').html('<option value="">Error loading ACRISS</option>');
    });
}

$('#partner_id').on('change', function () {
    const partnerId = $(this).val();
    fetchAcrissOptions(partnerId);
});

function saveModifier() {
    const id = $('#modifierId').val();
    const partner_id = $('#partner_id').val();
    const location_id = $('#location_id').val();
    const acriss_code = $('#acriss_code').val();
    const modifier_percent = $('#modifier_percent').val();

    if (!partner_id || !location_id || !acriss_code || modifier_percent === '') {
        alert('Please fill all fields.');
        return;
    }

    const url = id ? 'actions/update_api_acriss_location_modifier.php' : 'actions/add_api_acriss_location_modifier.php';

    $.post(url, {
        id,
        partner_id,
        location_id,
        acriss_code,
        modifier_percent
    }, function (resp) {
        if (resp.success) {
            $('#modifierModal').modal('hide');
            location.reload();
        } else {
            alert(resp.error || 'Save failed.');
        }
    }, 'json').fail(function () {
        alert('Server error on save.');
    });
}

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

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



</body>

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