<?php
include('include/auth.php');
?>
<!doctype html>
<html class="fixed dark">
<?php
include('include/head.php');

// Sanitize and validate input
$startdateinit = filter_input(INPUT_GET, 'sdateg3', FILTER_SANITIZE_STRING);
$startdateinit = urldecode($startdateinit); // Decode the URL-encoded string
$cargroup = filter_input(INPUT_GET, 'cargroup', FILTER_SANITIZE_NUMBER_INT);

// Parse the date and time correctly from the URL
if ($startdateinit) {
    $startdate = strtotime($startdateinit);
    if (!$startdate) {
        die("Invalid or missing start date.");
    }
} else {
    die("Invalid or missing start date.");
}

$sdate = date("Y-m-d H:i:s", $startdate);

// Generate a date range (14 days from start date)
$dateRanges = [];
for ($i = 0; $i < 14; $i++) {
    $dateRanges[] = strtotime("+$i day", $startdate);
}

// Fetch distinct availability groups and aggregate total units
$carGroupsQuery = $db2->prepare("
    SELECT cag.avail_group, ag.name AS group_name, COUNT(f.fleet_id) AS total_units
    FROM car_availability_groups cag
    INNER JOIN availability_groups ag ON cag.avail_group = ag.id
    INNER JOIN fleet f ON cag.car_id = f.veh_id
    WHERE cag.car_id IN (
        SELECT car_id
        FROM car_availability_groups
        WHERE avail_group = 1
    )
    AND cag.avail_group != 1
    AND f.active = 1
    GROUP BY cag.avail_group

");
$carGroupsQuery->execute();
$carGroupsResult = $carGroupsQuery->get_result();

$availabilityGroups = [];
while ($row = $carGroupsResult->fetch_assoc()) {
    $availabilityGroups[] = $row;
}
$carGroupsQuery->close();
?>
<style>
    .green {
        background-color: green !important;
        color:#fff!important;
        font-weight:bold;
        text-align:center;
    }

    .red {
        background-color: red !important;
        color:#fff!important;
        font-weight:bold;
        text-align:center;
    }
    .orange {
        background-color: orange !important;
        color:#fff!important;
        font-weight:bold;
        text-align:center;
    }
</style>
<body>
    <section class="body">
        <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>

            <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>
        </header>

        <div class="inner-wrapper">
            <?php include('include/nav.php'); ?>

            <section role="main" class="content-body">
                <header class="page-header">
                    <h2>Vehicle Availability: Group <?php if ($cargroup==1){ echo "CARS";} elseif($cargroup==1){echo "BIKES";} ?></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>Availability</span></li>
                            <li><span>Availability Groups</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">
                    <div class="col">
                        <section class="card">
                            <header class="card-header">
                                <h2 class="card-title">Availability From: <?php echo date("d/m/Y", $startdate); ?></h2>
                            </header>

                            <div class="card-body">
                                <table class="table table-bordered table-striped mb-0" id="datatable-tabletools">
                                    <thead>
                                        <tr>
                                            <th>Group</th>
                                            <th>Units</th>
                                            <?php foreach ($dateRanges as $date) : ?>
                                                <th><?php echo date("d/m", $date); ?></th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                   <tbody>
    <?php foreach ($availabilityGroups as $group) : ?>
        <?php
        // Calculate daily availability for each group
        $dailyAvailability = [];
        foreach ($dateRanges as $date) {
            $dateString = date("Y-m-d H:i:s", $date);

            // Fetch reserved cars for this group and date
            $reservedQuery = $db2->prepare("
                SELECT COUNT(*) AS reserved_count
                FROM jostj_vikrentcar_orders o
                INNER JOIN car_availability_groups cag ON o.idcar = cag.car_id
                WHERE cag.avail_group = ?
                  AND DATE(?) BETWEEN DATE(FROM_UNIXTIME(o.ritiro)) AND DATE(DATE_ADD(FROM_UNIXTIME(o.consegna), INTERVAL 2 HOUR))
                  AND o.status IN ('contract', 'confirmed')
            ");
            $reservedQuery->bind_param("is", $group['avail_group'], $dateString);
            $reservedQuery->execute();
            $reservedResult = $reservedQuery->get_result();
            $reservedCount = $reservedResult->fetch_assoc()['reserved_count'] ?? 0;
            $reservedQuery->close();

            // Calculate available units
            $dailyAvailability[] = max(0, $group['total_units'] - $reservedCount);
        }
        ?>
        <tr>
            <td><?php echo htmlspecialchars($group['group_name']); ?></td>
            <td><?php echo $group['total_units']; ?></td>
            <?php foreach ($dailyAvailability as $availability) : ?>
                <td class="<?php echo ($availability < 1 ? 'red' : ($availability < 2 ? 'orange' : 'green')); ?>">
                    <?php echo $availability; ?>
                </td>
            <?php endforeach; ?>
        </tr>
    <?php endforeach; ?>
</tbody>
                                </table>
                            </div>
                        </section>
                    </div>
                </div>
<?php } ?>
            </section>
        </div>
    </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 src="  //cdn.datatables.net/plug-ins/1.10.24/api/sum().js"></script>
    <script>
        (function ($) {

            'use strict';

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


                var table = $table.dataTable({
                    "pageLength": 100,
                    "order": [
                        [0, "asc"]
                    ],
                    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>
</body>
</html>
<?php  include('include/footer.php')?>