<?php
session_start();
include "config.php";

// Redirect if user is not logged in
if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}

$platform = 'IPDR';
// Get user details from session
$user = $_SESSION['user'];
$pid = $user['pid'];

$IPDRId = isset($_POST['ipdr_id']) ? (int) $_POST['ipdr_id'] : 0;

if ($IPDRId === 0) {
    die("Invalid IPDR ID");
}

$query = "SELECT * FROM `ipdr` WHERE id = $IPDRId";
$result = mysqli_query($con, $query);
$IPDRData = mysqli_fetch_assoc($result);

//echo "Welcome " . htmlspecialchars($user['name'] ?? 'User') . "<br>";
//echo "Email: " . htmlspecialchars($user['email'] ?? '') . "<br>";
//echo "Phone: " . htmlspecialchars($user['phone'] ?? '') . "<br>";
$ATFQuery = "SELECT * FROM `cyber_police` WHERE `pid` = '$pid'";
$resultATF = mysqli_query($con, $ATFQuery);


// Fetch Notice Options
$noticeOptions = "";
$noticeQuery = "SELECT * FROM `notice` WHERE `n_name` = 'Request under section 95 of BNSS 2023'";
$noticeResult = mysqli_query($con, $noticeQuery);
if ($noticeResult && mysqli_num_rows($noticeResult) > 0) {
    while ($row = mysqli_fetch_assoc($noticeResult)) {
        $noticeOptions .= "<option value='" . htmlspecialchars($row['id']) . "'>" . htmlspecialchars($row['n_name']) . "</option>";
    }
}

// Fetch Subject Options
$subjectOptions = "";
$subjectQuery = 'SELECT `id`, `s_name` FROM `subject` WHERE `s_name` = \'Please provide the "IP User" Detail of the following IP Address\'';
//$subjectQuery = "SELECT `id`, `s_name` FROM `subject` WHERE `s_name`='Please provide the "IP User" Detail of the following IP Address'";
$subjectResult = mysqli_query($con, $subjectQuery);
if ($subjectResult && mysqli_num_rows($subjectResult) > 0) {
    while ($row = mysqli_fetch_assoc($subjectResult)) {
        $subjectOptions .= "<option value='" . htmlspecialchars($row['id']) . "'>" . htmlspecialchars($row['s_name']) . "</option>";
    }
}


$policeOptions = "";
$policeQuery = "SELECT `id`, `i_name` FROM `police` WHERE pid=$pid";
$policeResult = mysqli_query($con, $policeQuery);
if ($policeResult && mysqli_num_rows($policeResult) > 0) {
    while ($row = mysqli_fetch_assoc($policeResult)) {
        $policeOptions .= "<option value='" . htmlspecialchars($row['id']) . "'>" . htmlspecialchars($row['i_name']) . "</option>";
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="images/favicon.ico" sizes="32x32" type="image/x-icon">

    <title><?php echo strtoupper($platform); ?></title>

    <!-- Main CSS -->
    <link rel="stylesheet" type="text/css" href="css/main.css">

    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
</head>

<body class="app sidebar-mini">
    <!-- Navbar-->
    <?php include "header.php" ?>
    <!-- Sidebar menu-->
    <div class="app-sidebar__overlay" data-toggle="sidebar"></div>
    <aside class="app-sidebar">

        <?php include "./common/name.php" ?>

        <?php include 'sidebar.php'; ?>



    </aside>

    <main class="app-content">
        <div class="app-title">
            <div>
                <h1><i class="bi bi-database"></i> <?php echo strtoupper($platform); ?></h1>
            </div>
            <ul class="app-breadcrumb breadcrumb">
                <li class="breadcrumb-item"><i class="bi bi-house-door fs-6"></i></li>
                <li class="breadcrumb-item"><a href="#"> <?php echo strtoupper($platform); ?></a></li>
            </ul>
        </div>

        <form method="POST" action="update_a_ipdr.php" id="ipdrForm">

            <input type="hidden" name="ipdr_id" value="<?= $IPDRId ?>">

            <div class="row">

                <!-- Left Side - Form Inputs -->
                <div class="col-md-6">
                    <div class="tile">
                        <div class="tile-body">

                            <div class="mb-3">
                                <label class="form-label">Select Acknowledgement / FIR No.</label>

                                <select class="form-control" name="atf" id="atf_id"
                                    <?= !empty($IPDRData['c_id']) ? 'disabled' : 'required' ?>>

                                    <option value="">-- Select Acknowledgement No / FIR No --</option>

                                    <?php
                                    while ($row = mysqli_fetch_assoc($resultATF)) {

                                        $displayText = htmlspecialchars($row['acknowlegement']) . ' - ' . htmlspecialchars($row['complain_name']);

                                        $selected = (
                                            !empty($IPDRData['c_id']) &&
                                            $row['id'] == $IPDRData['c_id']
                                        ) ? 'selected' : '';

                                        echo '<option value="' . $row['id'] . '" ' . $selected . '>'
                                            . $displayText .
                                            '</option>';
                                    }
                                    ?>
                                </select>

                                <!-- Disabled select does not submit value -->
                                <?php if (!empty($IPDRData['c_id'])) { ?>
                                <input type="hidden" name="atf" value="<?= $IPDRData['c_id'] ?>">
                                <?php } ?>
                            </div>

                            <!-- Hidden Notice -->
                            <div class="mb-3 d-none">
                                <label class="form-label">Select Notice</label>
                                <select class="form-control" name="notice_id">
                                    <?= $noticeOptions ?>
                                </select>
                            </div>

                            <!-- Hidden Subject -->
                            <div class="mb-3 d-none">
                                <label class="form-label">Select Subject</label>
                                <select class="form-control" name="subject_id">
                                    <?= $subjectOptions ?>
                                </select>
                            </div>

                            <!-- Police Options -->
                            <div class="mb-3">
                                <label class="form-label">Select Police</label>
                                <select class="form-control" name="police_id" required disabled>
                                    <?= $policeOptions ?>
                                </select>
                            </div>

                            <!-- IP Type and Address -->
                            <div class="mb-0 row">
                                <div class="col-3">
                                    <label class="form-label">Select Type Of IP</label>
                                    <select class="form-control" name="ip_type" id="ip_type" required>
                                        <option value="">-- Select Type --</option>
                                        <option value="IPv4">IPv4</option>
                                        <option value="IPv6">IPv6</option>
                                    </select>
                                </div>

                                <div class="col-9">
                                    <label class="form-label">IP Address</label>
                                    <input id="dataInput" class="form-control" type="text"
                                        placeholder="Enter IP Address" required>
                                </div>
                            </div>

                            <!-- Date and Time -->
                            <div class="mb-3 row">
                                <div class="col-6">
                                    <label class="form-label">Start Date</label>
                                    <input type="date" id="startDate" name="start_date" class="form-control" required>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Start Time (UTC)</label>
                                    <input type="time" id="startTime" name="start_time" class="form-control" step="1"
                                        required>
                                </div>
                            </div>

                            <div class="mb-3 row">
                                <div class="col-6">
                                    <label class="form-label">End Date</label>
                                    <input type="date" id="endDate" name="end_date" class="form-control" required>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">End Time (UTC)</label>
                                    <input type="time" id="endTime" name="end_time" class="form-control" step="1"
                                        required>
                                </div>
                            </div>

                            <!-- Add IP Button -->
                            <center>
                                <div class="row col-4">
                                    <label class="form-label" style="visibility: hidden;">Add Button</label>
                                    <button class="btn btn-primary" type="button" onclick="addIPAddressData()">
                                        <i class="bi bi-check-circle-fill me-2"></i>Add
                                    </button>
                                </div>
                            </center>

                        </div>

                        <!-- Hidden Field to hold all IP data -->
                        <input type="hidden" name="data_ids" id="data_ids">

                        <!-- Submit Button -->
                        <div class="tile-footer">

                            <button class="btn btn-primary" type="submit" formnovalidate>
                                <i class="bi bi-check-circle-fill me-2"></i>Submit
                            </button>


                            <a class="btn btn-secondary" href="#">
                                <i class="bi bi-x-circle-fill me-2"></i>Cancel
                            </a>
                        </div>

                    </div>
                </div>

                <!-- Right Side - Table -->
                <div class="col-md-6">
                    <div class="tile">
                        <div class="tile-body">
                            <div class="table-responsive">
                                <table class="table table-hover table-bordered" id="sampleTable">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>IP TYPE</th>
                                            <th>IP Address</th>
                                            <th>Start Date</th>
                                            <th>Start Time (UTC / IST)</th>
                                            <th>End Date</th>
                                            <th>End Time (UTC / IST)</th>
                                            <th>DELETE</th>
                                        </tr>
                                    </thead>
                                    <tbody id="socialTableBody"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </form>



        <!-- Bootstrap Modal -->
        <div class="modal fade" id="welcomeModal" tabindex="-1" aria-labelledby="welcomeModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="welcomeModalLabel">Instruction! સૂચના </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        સ્ટાર્ટ ટાઇમ અને એન્ડ ટાઇમમાં જે પણ સમય તમે ઉપયોગ કરો — Instagram, Facebook અથવા અન્ય કોઇ લૉ
                        એન્ફોર્સમેન્ટમાંથી માગતી IP એડ્રેસમાં જે સમય મળશે — એ જ સમય અમારા સોફ્ટવેરમાં નોંધાશે. અમારા
                        સોફ્ટવેરમાં સેટ છે કે તે આપમેળે UTC ને રૂપાંતર કરીને IST માં ઉપયોગ કરશે.

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">OK</button>
                    </div>
                </div>
            </div>
        </div>




    </main>
    <!-- Essential javascripts for application to work-->
    <script src="js/jquery-3.7.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>
    <!-- Page specific javascripts-->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <!-- Google analytics script-->

    <script>
    $(document).ready(function() {
        $('#atf_id').select2({
            placeholder: "-- Select Acknowledgement No / FIR No --",
            allowClear: true,
        });
    });
    </script>

    <script>
    $(document).ready(function() {
        $('.selectpicker').selectpicker();
    });
    </script>

    <?php
$existingIpData = [];

if (!empty($IPDRData['ip_data'])) {
    $decoded = json_decode($IPDRData['ip_data'], true);
    if (is_array($decoded)) {
        $existingIpData = $decoded;
    }
}
?>

    <script>
    const existingIpData = <?= json_encode($existingIpData, JSON_UNESCAPED_SLASHES) ?>;
    </script>



    <script>
    let dataIds = [];
    let idCounter = 1;

    // Convert UTC to IST
    function convertUTCtoIST(timeUTC) {
        let [h, m, s] = timeUTC.split(':').map(Number);
        h += 5;
        m += 30;
        if (m >= 60) {
            h++;
            m -= 60;
        }
        h = h % 24;
        return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s||0).padStart(2,'0')}`;
    }

    // Render existing data
    function renderExistingData() {
        const tableBody = document.getElementById("socialTableBody");

        existingIpData.forEach(item => {
            const row = document.createElement("tr");

            row.innerHTML = `
            <td>${item.id}</td>
            <td>${item.ip_type}</td>
            <td>${item.ip_address}</td>
            <td>${item.start_date}</td>
            <td>UTC: ${item.start_time_utc}<br>IST: ${item.start_time_ist}</td>
            <td>${item.end_date}</td>
            <td>UTC: ${item.end_time_utc}<br>IST: ${item.end_time_ist}</td>
            <td>
                <button class="btn btn-danger btn-sm" onclick="deleteRow(this, ${item.id})">
                    Delete
                </button>
            </td>
        `;

            tableBody.appendChild(row);
            dataIds.push(item);
            idCounter = Math.max(idCounter, item.id + 1);
        });

        document.getElementById("data_ids").value = JSON.stringify(dataIds);
    }

    // Add new row
    function addIPAddressData() {

        const ipType = document.getElementById("ip_type").value;
        const ipAddress = document.getElementById("dataInput").value.trim();
        const sDate = document.getElementById("startDate").value;
        const sTime = document.getElementById("startTime").value;
        const eDate = document.getElementById("endDate").value;
        const eTime = document.getElementById("endTime").value;

        if (!ipType || !ipAddress || !sDate || !sTime || !eDate || !eTime) {
            alert("All fields are required");
            return;
        }

        const entry = {
            id: idCounter,
            ip_type: ipType,
            ip_address: ipAddress,
            start_date: sDate,
            start_time_utc: sTime,
            start_time_ist: convertUTCtoIST(sTime),
            end_date: eDate,
            end_time_utc: eTime,
            end_time_ist: convertUTCtoIST(eTime)
        };

        dataIds.push(entry);

        document.getElementById("data_ids").value = JSON.stringify(dataIds);

        const row = document.createElement("tr");
        row.innerHTML = `
        <td>${entry.id}</td>
        <td>${entry.ip_type}</td>
        <td>${entry.ip_address}</td>
        <td>${entry.start_date}</td>
        <td>UTC: ${entry.start_time_utc}<br>IST: ${entry.start_time_ist}</td>
        <td>${entry.end_date}</td>
        <td>UTC: ${entry.end_time_utc}<br>IST: ${entry.end_time_ist}</td>
        <td>
            <button class="btn btn-danger btn-sm" onclick="deleteRow(this, ${entry.id})">
                Delete
            </button>
        </td>
    `;

        document.getElementById("socialTableBody").appendChild(row);

        idCounter++;

        // Clear inputs
        document.getElementById("dataInput").value = "";
        document.getElementById("startDate").value = "";
        document.getElementById("startTime").value = "";
        document.getElementById("endDate").value = "";
        document.getElementById("endTime").value = "";
        document.getElementById("ip_type").value = "";
    }

    // Delete row
    function deleteRow(btn, id) {
        btn.closest("tr").remove();
        dataIds = dataIds.filter(item => item.id !== id);
        document.getElementById("data_ids").value = JSON.stringify(dataIds);
    }

    // Load existing rows on page load
    window.addEventListener("DOMContentLoaded", renderExistingData);
    </script>



    <script>
    function updateLabel() {
        const selectedValue = document.querySelector('input[name="reference_type"]:checked').value;
        const label = document.getElementById("referenceLabel");
        const input = document.querySelector('input[name="reference_number"]');

        if (selectedValue === "0") {
            label.innerText = "Acknowledgement Number";
            input.placeholder = "Enter Acknowledgement Number";
        } else if (selectedValue === "1") {
            label.innerText = "FIR No.";
            input.placeholder = "Enter FIR No.";
        }
    }
    </script>


    <script>
    window.onload = function() {
        var welcomeModal = new bootstrap.Modal(document.getElementById('welcomeModal'));
        welcomeModal.show();
    };
    </script>


</body>

</html>