<?php include('include/auth.php'); 
if (isset($_GET['pid'])  && $_GET['pid']!='0') {
    $pid=$_GET['pid'];}
    else {$pid='0';}
?>
<!doctype html>
<html class="fixed dark">
<?php 
	$pagerole="lists";
	include('include/head.php');?>
<style>
    .green{color:green;}
    .red{color:red;}
    .nav-tabs {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    border-bottom: 2px solid #ddd;
}

.nav-tabs .nav-item {
    white-space: nowrap;
}

.nav-tabs .nav-link {
    padding: 10px;
    font-weight: bold;
    border: 1px solid #ddd;
}

.tab-content {
    padding: 15px;
    border: 1px solid #ddd;
    border-top: none;
}

</style>
<body>
    <section class="body">

        <!-- start: header -->
        <header class="header">
            <div class="logo-container">
                <a href="index.php" class="logo">
                    <img src="img/logo-light.png" width="75" height="35" alt="Web Voyage" />
                </a>
                <div class="d-md-none toggle-sidebar-left" data-toggle-class="sidebar-left-opened" data-target="html"
                    data-fire-event="sidebar-left-opened">
                    <i class="fas fa-bars" aria-label="Toggle sidebar"></i>
                </div>
            </div>

            <!-- start: search & user box -->
            <div class="header-right">
                <?php include('include/search.php');?>


                <span class="separator"></span>
                <?php include('include/notifications.php');?>


                <span class="separator"></span>
                <?php include('include/userbox.php');?>

            </div>
            <!-- end: search & user box -->
        </header>
        <!-- end: header -->

        <div class="inner-wrapper">
            <!-- start: sidebar -->
            <?php include('include/nav.php');?>
            <!-- end: sidebar -->

            <section role="main" class="content-body">
                <header class="page-header">
                    <h2>API Partners Fleet</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 Partners Fleet</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">
        <button class="btn btn-primary btn-md font-weight-semibold btn-py-2 px-4" id="add-partner-fleet-btn">
            + Add Partner Fleet
        </button>
    </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</option>
                            <?php $sqlin2 = $db2->query("SELECT * FROM api_partner ") or die(mysql_error()); 
					 while($rowin2 = mysqli_fetch_array($sqlin2)) {?>



                            <option
                                value="?<?php echo http_build_query(array_merge($_GET, array("pid"=>$rowin2['api_partner_id'])))?>"
                                <?php if($pid==$rowin2['api_partner_id']) { echo "selected";} ?>>
                                <?php echo $rowin2['api_partner_name'];?></option> <?php }?> 
                                
                            </select>
                    </div>
					</div>   
                    <div class="row">
                        <div class="col">
                            <section class="card">
                                <header class="card-header">
                                    <div class="card-actions">
                                        <a href="#" class="card-action card-action-toggle" data-card-toggle></a>
                                        <a href="#" class="card-action card-action-dismiss" data-card-dismiss></a>
                                    </div>

                                    <h2 class="card-title">Seasons</h2>
                                </header>

                                <div class="card-body">

                                    <table class="table table-bordered table-striped mb-0" id="datatable-tabletools">
                                        <thead>
                                        <th>ID</th>
                                     <th>Partner</th>
                                       
                                         <th>Vehicle</th>
                                     
                                       
                                        <th>ACRISS</th>
                                        <th>Excess</th>
                                        <th>Has Rates?</th>
                                        <th>Actions </th>
                                            </tr>
                                        </thead>
                                        <tbody>

                                        <?php 
$sql = "SELECT DISTINCT api_fleet.api_fleet_id, api_fleet.api_fleet_acriss,api_fleet_excess, 
       jostj_vikrentcar_cars.name, api_partner.api_partner_name,
       CASE WHEN api_ext_rates.api_ext_rate_acriss IS NOT NULL THEN 'Yes' ELSE 'No' END AS has_rates
FROM api_fleet 
LEFT JOIN jostj_vikrentcar_cars ON jostj_vikrentcar_cars.id = api_fleet.api_fleet_idcar 
LEFT JOIN api_partner ON api_partner.api_partner_id = api_fleet.api_fleet_partner
LEFT JOIN api_ext_rates ON TRIM(api_ext_rates.api_ext_rate_acriss) = TRIM(api_fleet.api_fleet_acriss)


";

            if ($pid!='0'){
                $sql .=" WHERE api_fleet.api_fleet_partner='$pid' ";
                }
$result = mysqli_query($db2,$sql);

if ($result->num_rows > 0) {
    // output data of each row
   while($row = mysqli_fetch_array($result)) {
	 
     ?>
                                            <tr>
                                            <td><?php echo $row["api_fleet_id"]; ?></td>
                                        <td class="text-center"><?php echo $row["api_partner_name"]; ?></td>
                                        <td  class="text-center"><?php echo $row["name"]; ?></td>
                                          
                                             
                                              <td  class="text-center"><?php echo $row["api_fleet_acriss"]; ?></td>
                                              <td  class="text-center"><?php echo $row["api_fleet_excess"]; ?></td>
                                              <td class="text-center">
    <?php echo ($row["has_rates"] === 'Yes') ? "<span class='green'>Yes</span>" : "<span class='red'>No</span>"; ?>
</td>
                                           <td class="actions">
                                                     <a href="#" class="on-default edit-row" 
       onclick="openEditPartnerFleetModal(
           '<?php echo $row['api_fleet_id']; ?>', 
           '<?php echo $row['api_fleet_partner']; ?>', 
           '<?php echo $row['api_fleet_idcar']; ?>', 
           '<?php echo addslashes($row['api_fleet_acriss']); ?>', 
           '<?php echo addslashes($row['api_fleet_excess']); ?>')">
        <i class="fas fa-pencil-alt"></i>
    </a>
                                                   
  <?php if ($row["has_rates"] === 'No') { ?>
       <a href="#" class="on-default add-rates" 
           onclick="openAddRatesModal('<?php echo addslashes($row['api_fleet_acriss']); ?>')">
           <i class="fas fa-plus-circle text-success"></i> Add Rates
       </a>
   <?php } ?>
   <!-- Delete Button -->
    <a href="#" class="on-default delete-row " 
        onclick="deleteFleetRecord('<?php echo $row['api_fleet_id']; ?>')">
        <i class="fas fa-trash-alt"></i>
    </a>
   </td>
                                            </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>

                            </section>

                        </div>
                    </div>
                    <?php } }?>
                    <!-- end: page -->
            </section>
        </div>

        <?php include('include/aside.php');?>

    </section>


    <!-- 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]);
    </script>
    <!-- Add Partner Fleet Modal -->
<div id="modalAddPartnerFleet" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Add Partner Fleet Vehicle</h2>
        </header>
        <div class="card-body">
            <form id="addPartnerFleetForm">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-plus"></i>
                    </div>
                    <div class="modal-text">
                        <!-- Partner -->
                        <div class="form-group mb-3">
                            <label for="api_fleet_partner">Partner</label>
                            <select class="form-control" id="api_fleet_partner" name="api_fleet_partner" required>
                                <option value="">Select Partner</option>
                                <?php
                                $partner_query = "SELECT api_partner_id, api_partner_name FROM api_partner";
                                $partner_result = mysqli_query($db2, $partner_query);
                                while ($partner = mysqli_fetch_assoc($partner_result)) {
                                    echo "<option value='{$partner['api_partner_id']}'>{$partner['api_partner_name']}</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <!-- Vehicle -->
                        <div class="form-group mb-3">
                            <label for="api_fleet_idcar">Vehicle</label>
                            <select class="form-control" id="api_fleet_idcar" name="api_fleet_idcar" required>
                                <option value="">Select Vehicle</option>
                                <?php
                                $vehicle_query = "SELECT id, name FROM jostj_vikrentcar_cars";
                                $vehicle_result = mysqli_query($db2, $vehicle_query);
                                while ($vehicle = mysqli_fetch_assoc($vehicle_result)) {
                                    echo "<option value='{$vehicle['id']}'>{$vehicle['name']}</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <!-- ACRISS -->
                        <div class="form-group mb-3">
                            <label for="api_fleet_acriss">ACRISS Code</label>
                            <input type="text" class="form-control" id="api_fleet_acriss" name="api_fleet_acriss" required>
                        </div>

                        <!-- Excess -->
                        <div class="form-group mb-3">
                            <label for="api_fleet_excess">Excess</label>
                            <input type="number" class="form-control" id="api_fleet_excess" name="api_fleet_excess" required>
                        </div>
                    </div>
                </div>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-partner-fleet">Save</button>
                   
                </div>
            </div>
        </footer>
            </form>
    </section>
</div>
<!-- Edit Partner Fleet Modal -->
<div id="modalEditPartnerFleet" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Edit Partner Fleet Vehicle</h2>
            <div class="card-actions">
                <a href="#" class="modal-dismiss"><i class="fas fa-times"></i></a>
            </div>
        </header>
        <div class="card-body">
            <form id="editPartnerFleetForm">
                <div class="modal-wrapper">
                    <div class="modal-icon">
                        <i class="fas fa-edit"></i>
                    </div>
                    <div class="modal-text">
                        <!-- Partner -->
                        <div class="form-group mb-3">
                            <label for="edit_api_fleet_partner">Partner</label>
                            <select class="form-control" id="edit_api_fleet_partner" name="api_fleet_partner" required>
                                <option value="">Select Partner</option>
                                <?php
                                $partner_query = "SELECT api_partner_id, api_partner_name FROM api_partner";
                                $partner_result = mysqli_query($db2, $partner_query);
                                while ($partner = mysqli_fetch_assoc($partner_result)) {
                                    echo "<option value='{$partner['api_partner_id']}'>{$partner['api_partner_name']}</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <!-- Vehicle -->
                        <div class="form-group mb-3">
                            <label for="edit_api_fleet_idcar">Vehicle</label>
                            <select class="form-control" id="edit_api_fleet_idcar" name="api_fleet_idcar" required>
                                <option value="">Select Vehicle</option>
                                <?php
                                $vehicle_query = "SELECT id, name FROM jostj_vikrentcar_cars";
                                $vehicle_result = mysqli_query($db2, $vehicle_query);
                                while ($vehicle = mysqli_fetch_assoc($vehicle_result)) {
                                    echo "<option value='{$vehicle['id']}'>{$vehicle['name']}</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <!-- ACRISS -->
                        <div class="form-group mb-3">
                            <label for="edit_api_fleet_acriss">ACRISS Code</label>
                            <input type="text" class="form-control" id="edit_api_fleet_acriss" name="api_fleet_acriss" required>
                        </div>

                        <!-- Excess -->
                        <div class="form-group mb-3">
                            <label for="edit_api_fleet_excess">Excess</label>
                            <input type="number" class="form-control" id="edit_api_fleet_excess" name="api_fleet_excess" required>
                        </div>

                        <input type="hidden" id="edit_api_fleet_id" name="api_fleet_id">
                    </div>
                </div>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-edit-partner-fleet">Save Changes</button>
                </div>
            </div>
        </footer>
            </form>
    </section>
</div>
<!-- Add Rates Modal -->
<!-- Add Rates Modal with Tabs -->
<div id="modalAddRates" class="modal-block modal-block-primary mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Add Initial Daily Rates for <span id="selected_acriss"></span></h2>
            <div class="card-actions">
                <a href="#" class="modal-dismiss"><i class="fas fa-times"></i></a>
            </div>
        </header>
        <div class="card-body">
            <form id="addRatesForm">
                <input type="hidden" id="rate_acriss" name="rate_acriss">

                <div class="form-group mb-3">
                    <label>Maximum Rental Days</label>
                    <input type="number" class="form-control" id="max_days" name="max_days" placeholder="30" value="30" required>

                </div>

                <!-- Tab Navigation -->
                <ul class="nav nav-tabs" id="seasonTabs" role="tablist">
                    <?php
                    
                    $season_query = "SELECT api_ext_season_id, api_ext_seasons_name FROM api_ext_seasons";
                    $season_result = mysqli_query($db2, $season_query);
                    $first = true;

                    while ($season = mysqli_fetch_assoc($season_result)) {
                        $season_id = $season['api_ext_season_id'];
                        $season_name = $season['api_ext_seasons_name'];
                        echo "<li class='nav-item'>
                                <a class='nav-link " . ($first ? "active" : "") . "' id='tab-$season_id' data-toggle='tab' href='#season-$season_id' role='tab'>$season_name</a>
                              </li>";
                        $first = false;
                    }
                    ?>
                </ul>

                <!-- Tab Content -->
                <div class="tab-content" id="seasonTabsContent">
                    <?php
                    mysqli_data_seek($season_result, 0); // Reset pointer for reuse
                    $first = true;

                    while ($season = mysqli_fetch_assoc($season_result)) {
                        $season_id = $season['api_ext_season_id'];
                        echo "<div class='tab-pane fade " . ($first ? "show active" : "") . "' id='season-$season_id' role='tabpanel'>";
                        
                        for ($i = 1; $i <= 7; $i++) {
                            echo "<div class='form-group mb-3'>
                                    <label>Day $i Rate</label>
                                    <input type='number' class='form-control' name='season_{$season_id}_day_$i' required>

                                  </div>";
                        }

                        echo "<div class='form-group mb-3'>
                                <label>Per Day Rate (Days 8+)</label>
                                <input type='number' class='form-control' name='season_{$season_id}_day_8_onwards'  required>

                              </div>";
                        echo "</div>";
                        $first = false;
                    }
                    ?>
                </div>

            </form>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="button" class="btn btn-primary" id="submit-add-rates">Save</button>
                </div>
            </div>
        </footer>
    </section>
</div>


<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Open the modal
        document.getElementById('add-partner-fleet-btn').addEventListener('click', function () {
            $.magnificPopup.open({
                items: {
                    src: '#modalAddPartnerFleet'
                },
                type: 'inline'
            });
        });

        // Submit the form
        document.getElementById('submit-partner-fleet').addEventListener('click', function () {
            const form = document.getElementById('addPartnerFleetForm');
            const formData = new FormData(form);

            fetch('actions/add_partner_fleet.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Partner Fleet Vehicle added successfully!');
                    location.reload(); // Reload the page to update the table
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        });
    });
</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Open the Edit Modal
        window.openEditPartnerFleetModal = function (id, partner, vehicle, acriss, excess) {
            document.getElementById('edit_api_fleet_id').value = id;
            document.getElementById('edit_api_fleet_partner').value = partner;
            document.getElementById('edit_api_fleet_idcar').value = vehicle;
            document.getElementById('edit_api_fleet_acriss').value = acriss;
            document.getElementById('edit_api_fleet_excess').value = excess;

            $.magnificPopup.open({
                items: {
                    src: '#modalEditPartnerFleet'
                },
                type: 'inline'
            });
        };

        // Submit the Edit Form
        document.getElementById('submit-edit-partner-fleet').addEventListener('click', function () {
            const form = document.getElementById('editPartnerFleetForm');
            const formData = new FormData(form);

            fetch('actions/edit_partner_fleet.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Partner Fleet Vehicle updated successfully!');
                    location.reload(); // Reload the page to update the table
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        });
    });
document.addEventListener('DOMContentLoaded', function () {
    // Debugging: Ensure Modal Opens
    $('#modalAddRates').on('shown.bs.modal', function () {
        console.log("✅ Modal is open!");
    });

    // Open Add Rates Modal
    window.openAddRatesModal = function (acriss) {
        console.log("🔹 Opening modal for ACRISS:", acriss);

        // Set the selected ACRISS in the modal
        document.getElementById('selected_acriss').textContent = acriss;
        document.getElementById('rate_acriss').value = acriss;

        // Open Modal
        $.magnificPopup.open({
            items: {
                src: '#modalAddRates'
            },
            type: 'inline'
        });

        console.log("✅ Modal should be visible now.");
    };

    // Handle Form Submission
    document.getElementById('submit-add-rates').addEventListener('click', function (event) {
        event.preventDefault(); // Prevent default form submission

        console.log("🟢 Submit button clicked!");

        const form = document.getElementById('addRatesForm');
        const formData = new FormData(form);

        // Debugging: Show the Form Data being sent
        console.log("📤 Form Data:", Object.fromEntries(formData));

        // Send data to the server
        fetch('actions/add_rates.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            console.log("📩 Response from server:", data);
            
            if (data.success) {
                alert('✅ Rates added successfully!');
                location.reload(); // Reload to update the table
            } else {
                alert('❌ Error: ' + data.message);
            }
        })
        .catch(error => {
    console.error('⚠ Fetch Error:', error);
    alert('❌ Fetch Error: ' + error.message);
});
    });
});

<!-- JavaScript to Handle Deletion -->

document.addEventListener('DOMContentLoaded', function () {
    // Delete Function
    window.deleteFleetRecord = function (fleetId) {
        if (!confirm("Are you sure you want to delete this fleet record?")) {
            return;
        }

        console.log("🗑 Deleting Fleet ID:", fleetId); // Debugging log

        fetch('actions/delete_fleet.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'fleet_id=' + encodeURIComponent(fleetId)
        })
        .then(response => response.json())
        .then(data => {
            console.log("📩 Response from server:", data);
            if (data.success) {
                alert('✅ Record deleted successfully!');
                location.reload(); // Refresh the table
            } else {
               alert('❌ Error: ' + data.message);

            }
        })
        .catch(error => {
            console.error('⚠ Fetch Error:', error);
            alert('An error occurred. Please try again.');
        });
    };
});


</script>

</body>

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