<?php
session_start();
include("../../php_crud/my_class.php");
include("../../asset/theme/css/myfunc.php");
$obj = new my_class();
?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="asset/custom/alertifyjs/css/alertify.rtl.css">
<link rel="stylesheet" href="asset/custom/alertifyjs/css/themes/default.rtl.css">
<link rel="stylesheet" href="asset/theme/css/custom_design.css">

<script src="asset/custom/js/typeahead.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> -->
<script src="module/mobiledatalog/js/ffwc_rainfall_info.js" type="text/javascript"></script>

<style type="text/css">
    .centered-div {
        width: 95%;
        /* Adjust the width as needed */
        margin: 0 auto;
        background-color: white;
    }

    .stat div {
        display: inline-grid;
        /* width: auto; */
    }

    .stat-div {
        border: 1px solid #ccc;
        border-radius: 2px;
    }

    .station-list {
        background-color: white;
        /* width: 200px; */
        /* Adjust the width as needed */
        height: 650px;
        /* Adjust the height as needed */
        overflow: auto;
        /* Enable vertical scrolling when needed */
    }

    .station {
        cursor: pointer;
        padding: 2px;
        margin: 2px;
        border: 1px solid #ccc;
        border-radius: 2px;
    }

    /* Define the selected class */
    .selected {
        background-color: #2283C5 !important;
        color: white !important;
    }

    .modal {
        position: fixed;
        top: 50%;
        left: 65%;
        /* transform: translate(-50%, -50%); */
    }

    .modal-footer {
        height: 14px;
        /* margin-top: 10px; */
    }

    #btn_save {
        display: block;
        margin: 0 auto;
        margin-top: -10px;
    }

    .modal-body {
        height: 140px;
        margin-top: 30px;
        font-size: 16px;
        /* font:center; */
        /* overflow-y: auto; */
    }
</style>

<div id="cover-spin"></div>


<div class="table-header"><i class="fas fa-list"></i> Rainfall Information</div>
<input type="hidden" style="width: 95%;" id="act_tab_name" name="act_tab_name" value="data_entry" />
<div class="row-fluid" style="background-color:#f5f5f5; -webkit-box-shadow:0px 8px 6px -6px black; -moz-box-shadow:0px 8px 6px -6px black; box-shadow:opx 8px 6px -6px black;">
    <div class="widget-body" style="border: none;  background-color: #f5f5f5;">
        <div class="widget-main padding-5">
            <div class="tab-content" style="overflow: visible; position: sticky; z-index: 999;">
                <!--data entry -->
                <div id="data_entry" class="tab-pane in active" style="text-align: center;">
                    <div class="span3" style="padding-bottom:20px;">
                        <div class="control-group stat" style="width: 100%;">
                            <div>
                                <?php
                                $table = "FFWC.STATIONS_TBL";
                                $where_cond = "STATION_TYPE='2' ORDER BY STATION_NAME ASC";
                                $total_row = $obj->Total_Count_By_Cond($table, $where_cond);
                                ?>
                                <label align="center"><b>List of Stations: <?php echo $total_row ?> </b>
                                    <font style="color:#FF0000;"></font>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="span3" style="padding-bottom:20px;">
                        <div class="control-group stat">
                            <div class="controls">
                                <label align="right"><b>Data For</b>
                                </label>
                            </div>
                            <div class="controls">
                                <input type="number" style="width: 90%; height:15px!important;" name="from_date" id="day5" value="7" min="1" onchange="handleDaysChange(this.value)">
                            </div>
                            <div>
                                <label align="left"><b>Days</b>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="span3">
                        <div class="control-group stat">
                            <div class="controls">
                                <p align="left"><b>Upto:</b></p>
                            </div>
                            <!-- <label class="control-label" for="form-field-1">&nbsp;</font></label> -->
                            <div class="controls" id="branch_control">
                                <input style="width: 100%; height:12px!important;" id="to_date" name="date" class="date-picker" type="text" data-date-format="dd-mm-yyyy" placeholder="dd-mm-yyyy" onchange="handleDateChange(this.value)" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row-fluid">
    <div class="span3" style="margin-top: 25px;">
        <div class="stat-div centered-div">
            <input type="text" id="stationSearch" placeholder="Search Stations" style="width: 98%; height: 15px !important;">
            <div class="station-list">
                <!-- Replace this static station list with your PHP-generated station list -->
                <?php
                $table = "FFWC.STATIONS_TBL";
                $where_cond = "STATION_TYPE IN (0,2) ORDER BY STATION_NAME ASC";
                $column = "*";
                $firstStation = true; // To track the first station div
                $sl = 1;

                foreach ($obj->View_colmn_By_Cond($table, $column, $where_cond) as $value) {
                    // Determine if this is the first station div
                    $selectedClass = $firstStation ? 'selected' : '';

                    echo '<div id="default-station" class="station ' . $selectedClass . '" onclick="load_ffwc_rf_info(this)" data-station-key="' . $value['KEYWORD'] . '" data-station-name="' . $value['STATION_NAME'] . '" data-river-name="' . $value['RIVER_NAME'] . '">' . $sl . ". " . $value['STATION_NAME'] . ' (' . $value['KEYWORD'] . ')</div>';

                    // After the first station div, set $firstStation to false
                    $firstStation = false;
                    $sl++;
                }
                ?>
            </div>
        </div>
    </div>
    <div class="span3" id="data_to_show_ffwc_rf" style="margin-top: 25px;"></div>
    <!-- <div class="span6" id="graph_to_show_ffwc_rf" style="margin-top: 10px;"></div> -->
    <div class="span6" id="graph_to_show_ffwc_rf" style="margin-top: 10px;">
        <canvas id="graph_canvas_ffwc_rf" style="width: 100%; height: 500px;"></canvas>
    </div>

</div>

<div id="modal_ffwc_rf_edit" class="modal hide fade" style="margin-top: 200px; margin-left: -28%; width: 25%; " tabindex="-1">
    <div class="modal-header no-padding">
        <div class="table-header">
            <button type="button" class="close" data-dismiss="modal" style="opacity:1 !important"><i class="fa fa-window-close" style="font-size: 26px;font-weight: bold;color: #FFF;"></i> </button>
            <b> Edit Rainfall </b>
        </div>
    </div>
    <div class="modal-body" id="ffwc_rf_model_edit_body" style="max-height: 600px;">
    </div>
    <div class="modal-footer ">
        <div class="row-fluid">
            <button class="btn btn-small btn-success pull-right " type="button" id="btn_save" onclick="update_rf_data()">
                <i class="icon-ok bigger-40"></i>
                Save
            </button>
        </div>
    </div>
</div>


<div id="modal_ffwc_rf_add" class="modal hide fade" style="margin-top: 200px; margin-left: -28%; width: 25%; " tabindex="-1">
    <div class="modal-header no-padding">
        <div class="table-header">
            <button type="button" class="close" data-dismiss="modal" style="opacity:1 !important"><i class="fa fa-window-close" style="font-size: 26px;font-weight: bold;color: #FFF;"></i> </button>
            <b> Add Rainfall </b>
        </div>
    </div>
    <div class="modal-body " id="ffwc_rf_model_add_body" style="max-height: 600px;">
    </div>
    <div class="modal-footer ">
        <div class="row-fluid">
            <button class="btn btn-small btn-success pull-right " type="button" id="btn_save" onclick="rainfalldata()">
                <i class="icon-ok bigger-40"></i>
                Save
            </button>
        </div>
    </div>
</div>

<script>
    // Remove event listeners when navigating away from the page
    window.onbeforeunload = function() {
        // Remove event listeners here
        // For example, if you have a keydown event listener:
        document.removeEventListener('keydown', handleKeyDown);
    };
</script>

<!-- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> -->
<script>
    document.getElementById('day5').addEventListener('keyup', function(event) {
        // Check if the key pressed is "Enter" (key code 13)
        if (event.keyCode === 13) {
            // Simulate a click on the previously selected div
            if (selectedDiv) {
                selectedDiv.click();
            }
        }
    });

    function handleDateChange(dateValue) {
        // Simulate a click on the previously selected div
        if (selectedDiv) {
            selectedDiv.click();
        }
        $('#to_date').datepicker('hide');
    }
	
	function handleDaysChange(dateValue) {
        if (selectedDivWL) {
            selectedDivWL.click();
        }
    }
</script>


<!-- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> -->
<script>
    setTimeout(function() {
        var firstStationDiv = document.querySelector('.station.selected');
        if (firstStationDiv) {
            firstStationDiv.click();
        }
    }, 50); // adjust the delay as needed
</script>

<script>
    var stationList = document.querySelector('.station-list');
    var stations = stationList.querySelectorAll('.station');
    let focusedIndex = 0;
    let selectedStation = null;

    // Function to find and select the first visible station
    function findAndSelectVisibleStation() {
        for (var i = 0; i < stations.length; i++) {
            if (isStationVisible(stations[i])) {
                handleStationClick(stations[i], i);
                break;
            }
        }
    }

    // Function to handle station click
    function handleStationClick(station, index) {
        selectedStation = station;
        focusedIndex = index;
        console.log('Selected Station:', selectedStation.textContent);
    }

    // Function to check if the station is visible
    function isStationVisible(station) {
        var rect = station.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)
        );
    }

    // Event listener for input in the search field
    document.getElementById('stationSearch').addEventListener('input', function() {
        var searchTerm = this.value.trim().toLowerCase();

        stations.forEach((station, index) => {
            var stationName = station.textContent.toLowerCase();
            var isMatch = stationName.includes(searchTerm);
            station.style.display = isMatch ? 'block' : 'none';
        });

        if (selectedStation && !isStationVisible(selectedStation)) {
            findAndSelectVisibleStation();
        }
    });

    // Event listener for keydown event
    document.addEventListener('keydown', function(e) {
        if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
            if (selectedStation) {
                selectedStation.classList.remove('selected');
            }

            focusedIndex = e.key === 'ArrowDown' ?
                getNextVisibleIndex(focusedIndex) :
                getPrevVisibleIndex(focusedIndex);

            selectedStation = stations[focusedIndex];
            selectedStation.classList.add('selected');
            selectedStation.click();
        }
    });

    // Function to get the index of the next visible station
    function getNextVisibleIndex(currentIndex) {
        for (var i = currentIndex + 1; i < stations.length; i++) {
            if (isStationVisible(stations[i])) {
                return i;
            }
        }
        return currentIndex;
    }

    // Function to get the index of the previous visible station
    function getPrevVisibleIndex(currentIndex) {
        for (var i = currentIndex - 1; i >= 0; i--) {
            if (isStationVisible(stations[i])) {
                return i;
            }
        }
        return currentIndex;
    }

    // Event listener for window load event
    window.addEventListener('load', function() {
        focusedIndex = 0;
        selectedStation = null;
        findAndSelectVisibleStation();
    });
</script>


<!-- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> -->
<script>
    var currentDate = new Date();

    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1; // Months are 0-based
    var year = currentDate.getFullYear();

    var formattedDate = (day < 10 ? '0' : '') + day + '-' + (month < 10 ? '0' : '') + month + '-' + year;
    document.getElementById('to_date').value = formattedDate;
</script>

<!--for load datatable-->
<script type="text/javascript">
    $('.date-picker').datepicker().next().on(ace.click_event, function() {
        $(this).prev().focus();
    });
    $(".date-picker").attr("autocomplete", "off");
</script>

<!-- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> -->