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

// Redirect if user is not logged in
if (!isset($_SESSION['user'])) {
    header("Location: index.php");
    exit();
}

$record_id = $_POST['record_id'] ?? '';
$record_id = (int) $record_id;

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

//echo "Welcome " . htmlspecialchars($user['name'] ?? 'User') . "<br>";
//echo "Email: " . htmlspecialchars($user['email'] ?? '') . "<br>";
//echo "Phone: " . htmlspecialchars($user['phone'] ?? '') . "<br>";


$cctvQuery = "
    SELECT c.*, 
           p.id,
           p.acknowlegement, 
           p.complain_name, 
           p.mobile, 
           p.incident_date_time, 
           p.total_fraud_amount, 
           p.total_lien_amount, 
           p.atf, 
           p.pid, 
           p.status, 
           p.time_stamp
    FROM cctv c
    LEFT JOIN cyber_police p ON c.c_id = p.id
    WHERE p.pid = '$pid' AND c.id = $record_id
    ORDER BY c.id DESC
";

//$queryCCTV = "SELECT * FROM `cctv` WHERE `id`= $record_id";
$resultCCTV = mysqli_query($con, $cctvQuery);
$CCTVData = mysqli_fetch_assoc($resultCCTV);


$ATFQuery = "SELECT * FROM `cyber_police` WHERE `pid` = '$pid'";
$resultATF = mysqli_query($con, $ATFQuery);

// Fetch all users
$noticeQuery = "SELECT * FROM `notice`";
$resultNotice = mysqli_query($con, $noticeQuery);


$policeStationQuery = "SELECT * FROM `policestation` WHERE id='{$user['pid']}'";
$resultPoliceStation = mysqli_query($con, $policeStationQuery);

$policeQuery = "SELECT * FROM `police` WHERE pid = '{$user['pid']}'";
$resultPolice = mysqli_query($con, $policeQuery);

//$policeQuery = "SELECT * FROM `policestation` WHERE id='{$user['pid']}'";
//$resultPolice = mysqli_query($con, $policeQuery);

$subjectQuery = "SELECT * FROM `subject` WHERE `s_name` = 'Request for CCTV Footage of ATM ID :'";
$resultSubject = mysqli_query($con, $subjectQuery);

$noticeQuery = "SELECT * FROM `notice` WHERE `n_name` LIKE '%94%' ";
$resultNotice = mysqli_query($con, $noticeQuery);

$bankQuery = "SELECT * FROM `bank`";
$resultBank = mysqli_query($con, $bankQuery);



?>

<!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>CCTV</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-->

    <!-- 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>CCTV</h1>
            </div>
            <ul class="app-breadcrumb breadcrumb side">
                <li class="breadcrumb-item"><i class="bi bi-house-door fs-6"></i></li>
                <li class="breadcrumb-item">BANK</li>
                <li class="breadcrumb-item active"><a href="#">CCTV</a></li>
            </ul>
        </div>


        <div class="row">
            <form method="POST" action="update_cctv_form.php" enctype="multipart/form-data">
                <input type="hidden" name="record_id" value="<?= $record_id ?>">

                <div class="text-end mb-3">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>

                <div class="row">
                    <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($CCTVData['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($CCTVData['c_id']) &&
                $row['id'] == $CCTVData['c_id']
            ) ? 'selected' : '';

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

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




                                <div class="mb-3">
                                    <label class="form-label">Select Investigation Officer</label>

                                    <select class="form-control" name="police_id" id="police_id"
                                        <?php echo (!empty($CCTVData['police_id'])) ? 'disabled' : 'required'; ?>>
                                        <option value="">-- Select Investigation Officer --</option>

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

                                                    // match police.id with kyc.police_id
                                                    $selected = ($row['id'] == $CCTVData['police_id']) ? 'selected' : '';

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

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


                                <div class="mb-3 d-none">
                                    <label class="form-label">Select Subject</label>
                                    <select class="form-control" name="subject_id" required>
                                        <?php while ($row = mysqli_fetch_assoc($resultSubject)) { ?>
                                        <option value="<?php echo $row['id']; ?>">
                                            <?php echo htmlspecialchars($row['s_name']); ?>
                                        </option>
                                        <?php } ?>
                                    </select>
                                </div>

                                <div class="mb-3 d-none">
                                    <label class="form-label">Select Notice</label>
                                    <select class="form-control" name="notice_id" required>
                                        <?php while ($row = mysqli_fetch_assoc($resultNotice)) { ?>
                                        <option value="<?php echo $row['id']; ?>">
                                            <?php echo htmlspecialchars($row['n_name']); ?>
                                        </option>
                                        <?php } ?>
                                    </select>
                                </div>



                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="tile">
                            <div class="tile-body">

                                <!-- BANK FIELDS -->
                                <div id="bank-form">
                                    <div class="mb-3">
                                        <label class="form-label">Select Bank</label>
                                        <select class="form-control" id="bank_id" name="bank_id">
                                            <option value=""></option> <!-- Empty option for placeholder -->
                                            <?php while ($row = mysqli_fetch_assoc($resultBank)) { ?>
                                            <option value="<?php echo $row['id']; ?>"
                                                data-name="<?php echo htmlspecialchars($row['b_name']); ?>">
                                                <?php echo htmlspecialchars($row['b_name']); ?>
                                            </option>
                                            <?php } ?>
                                        </select>
                                    </div>


                                    <div class="mb-3">
                                        <label class="form-label">ATM ID</label>
                                        <input class="form-control" type="text" id="atm_id" placeholder="Enter ATM ID">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">START DATE TIME</label>
                                        <input class="form-control" type="datetime-local" id="start_date_time"
                                            name="start_date_time">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">END DATE TIME</label>
                                        <input class="form-control" type="datetime-local" id="end_date_time"
                                            name="end_date_time">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Difference in Time</label>
                                        <p id="time_difference" style="font-weight: bold;"></p>
                                    </div>

                                    <input type="hidden" name="bank_accounts_json" id="bank_accounts_json" required>

                                    <button type="button" class="btn btn-primary btn-sm" onclick="addBankCctv()">Add
                                        Bank
                                        Data</button>
                                </div>
                            </div>
                        </div>
            </form>
        </div>

        <!-- Display added bank accounts -->
        <div class="row">
            <div class="col-md-12">
                <div class="tile">
                    <h5 class="mt-0">Added Bank Accounts:</h5>
                    <div class="tile-body">
                        <div class="table-responsive">

                            <table class="table table-bordered" id="bank-table">
                                <thead>
                                    <tr>
                                        <th>Bank</th>
                                        <th>ATM ID</th>
                                        <th>Start</th>
                                        <th>End</th>
                                        <th>Delete</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </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-->
    <link rel="stylesheet" href="https://cdn.datatables.net/v/bs5/dt-1.13.4/datatables.min.css">
    <!-- Data table plugin-->
    <script type="text/javascript" src="js/plugins/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="js/plugins/dataTables.bootstrap.min.js"></script>
    <script type="text/javascript">
    //$('#bank-table').DataTable();
    </script>
    <!-- Google analytics 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() {
        $('#bank_id').select2({
            placeholder: "-- Select Bank --",
            allowClear: true,
            width: '100%',
            // Dropdown height limit
            dropdownCssClass: "custom-dropdown"
        });
    });
    </script>

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

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

    <script>
    let bankCctvData = <?=
    !empty($CCTVData['cctv_details'])
    ? json_encode(json_decode($CCTVData['cctv_details']))
    : '[]';
?>;


    // Render table
    function renderBankTable() {
        const tbody = document.querySelector('#bank-table tbody');
        tbody.innerHTML = '';

        bankCctvData.forEach((e, i) => {
            tbody.innerHTML += `
        <tr>
            <td>${e.bank_name}</td>
            <td>${e.atm_id}</td>
            <td>${e.start_date_time}</td>
            <td>${e.end_date_time}</td>
            <td>
                <button class="btn btn-danger btn-sm" onclick="deleteBankRow(${i})">
                    Delete
                </button>
            </td>
        </tr>`;
        });

        document.getElementById('bank_accounts_json').value =
            JSON.stringify(bankCctvData);
    }

    function formatDateTime(dateTimeStr) {
        const date = new Date(dateTimeStr);
        return date.toLocaleString('en-IN', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            hour12: true
        });
    }

    function addBankCctv() {
        const bankSelect = document.getElementById('bank_id');
        const bankId = bankSelect.value;
        const bankName = bankSelect.options[bankSelect.selectedIndex].getAttribute('data-name');
        const atmId = document.getElementById('atm_id').value.trim();
        const startDateTime = document.getElementById('start_date_time').value;
        const endDateTime = document.getElementById('end_date_time').value;

        if (!bankId || !atmId || !startDateTime || !endDateTime) {
            alert("Please fill in all fields.");
            return;
        }

        // Format the datetime strings
        const formattedStart = formatDateTime(startDateTime);
        const formattedEnd = formatDateTime(endDateTime);

        const entry = {
            bank_id: bankId,
            bank_name: bankName,
            atm_id: atmId,
            start_date_time: formattedStart,
            end_date_time: formattedEnd
        };


        // Add to array
        bankCctvData.push(entry);

        // Render the table (this already shows all rows)
        // renderBankTable();

        // Clear the form
        clearBankForm();


        // Update hidden JSON input
        document.getElementById('bank_accounts_json').value = JSON.stringify(bankCctvData);

        // Add to table
        const tableBody = document.querySelector('#bank-table tbody');
        const rowIndex = bankCctvData.length - 1;

        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${bankName}</td>
            <td>${atmId}</td>
             <td>${formattedStart}</td>
        <td>${formattedEnd}</td>
            <td><button type="button" class="btn btn-danger btn-sm" onclick="deleteBankRow(${rowIndex})">Delete</button></td>
        `;
        tableBody.appendChild(row);

        // Clear form fields
        bankSelect.selectedIndex = 0;
        document.getElementById('atm_id').value = '';
        document.getElementById('start_date_time').value = '';
        document.getElementById('end_date_time').value = '';
        document.getElementById('time_difference').innerText = '';
    }

    // Delete Bank
    function deleteBankRow(index) {
        if (!confirm("Delete this entry?")) return;

        bankCctvData.splice(index, 1);
        renderBankTable();

        $.post('delete_cctv_details.php', {
            cctv_id: <?= $record_id ?>,
            cctv_details: JSON.stringify(bankCctvData)
        });
    }


    function clearBankForm() {
        const bankSelect = document.getElementById('bank_id');
        const atmInput = document.getElementById('atm_id');
        const startInput = document.getElementById('start_date_time');
        const endInput = document.getElementById('end_date_time');
        const diffDisplay = document.getElementById('time_difference');

        // Reset dropdown
        bankSelect.selectedIndex = 0;
        $('#bank_id').trigger('change'); // for Select2

        // Clear text inputs
        atmInput.value = '';
        startInput.value = '';
        endInput.value = '';

        // Clear time difference display
        diffDisplay.innerText = '';
    }

    document.addEventListener('DOMContentLoaded', renderBankTable);
    </script>


    <script>
    document.getElementById('policestation_id').addEventListener('change', function() {
        var stationId = this.value;
        var policeDropdown = document.getElementById('police_id');
        policeDropdown.innerHTML = '<option value="">Loading...</option>';

        fetch('get_police_by_station.php?station_id=' + stationId)
            .then(response => response.json())
            .then(data => {
                console.log('Fetched Police Data:', data); // 👈 This prints data to the console
                policeDropdown.innerHTML = '<option value="">-- Select Police --</option>';
                data.forEach(function(police) {
                    var option = document.createElement('option');
                    option.value = police.id;
                    option.text = police.i_name;
                    policeDropdown.appendChild(option);
                });
            })
            .catch(error => console.error('Error fetching police data:', error));
    });
    </script>

    <script>
    const startInput = document.getElementById('start_date_time');
    const endInput = document.getElementById('end_date_time');
    const diffDisplay = document.getElementById('time_difference');

    function updateTimeDifference() {
        const start = new Date(startInput.value);
        const end = new Date(endInput.value);

        if (!isNaN(start) && !isNaN(end)) {
            const diffMs = end - start;
            const diffMins = Math.floor(diffMs / 60000); // Convert ms to minutes
            if (diffMins >= 0) {
                diffDisplay.innerText = diffMins + ' minute(s)';
            } else {
                diffDisplay.innerText = 'End time must be after start time';
            }
        } else {
            diffDisplay.innerText = '';
        }
    }

    startInput.addEventListener('change', updateTimeDifference);
    endInput.addEventListener('change', updateTimeDifference);
    </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 = "Ticket No.";
            input.placeholder = "Enter Ticket No.";
        } else if (selectedValue === "2") {
            label.innerText = "FIR No.";
            input.placeholder = "Enter FIR No.";
        }
    }
    </script>

</body>

</html>