<?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 = 'CDR';
// Get user details from session
$user = $_SESSION['user'];
$pid = $user['pid'];
$Id = $_POST['cdr_id'];

$query = "SELECT * FROM `cdr` WHERE id = $Id";
$result = mysqli_query($con, $query);
$CDRData = 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);

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

// Fetch Notice Options
$noticeOptions = "";
$noticeQuery = "SELECT * FROM `notice` WHERE `n_name` = 'Request under section 95 of BNSS 2003'";
$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="" ;

$subjectOptions = ''; // ✅ initialize first

$subjectQuery = "
    SELECT `id`, `s_name`
    FROM `subject`
    WHERE `s_name` = 'Request for CDR, CAF, and SDR Details for the Following Numbers'
";

$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_cdr.php">
            <input type="hidden" name="cdr_id" value="<?= $Id ?>">

            <div class="row">

                <!-- LEFT SIDE -->
                <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($CDRData['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($CDRData['c_id']) &&
                                            $row['id'] == $CDRData['c_id']
                                        ) ? 'selected' : '';

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

                                <!-- Disabled select does not submit value -->
                                <?php if (!empty($CDRData['c_id'])) { ?>
                                <input type="hidden" name="atf" value="<?= $CDRData['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($CDRData['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'] == $CDRData['police_id']) ? 'selected' : '';

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

                                <?php if (!empty($CDRData['police_id'])) { ?>
                                <!-- Disabled select does not submit value -->
                                <input type="hidden" name="police_id" value="<?php echo $CDRData['police_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>

                        </div>

                        <!-- Date Range -->
                        <div class="mb-3">
                            <div class="row">
                                <div class="col-6">
                                    <label class="form-label">From Date</label>
                                    <input type="date" id="fromDate" name="from_date" class="form-control" required>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">To Date (Auto-filled)</label>
                                    <input type="text" id="toDate" name="to_date" class="form-control" readonly>
                                </div>
                            </div>
                        </div>

                        <!-- Mobile Number Input -->
                        <div class="mb-3">
                            <div class="row">
                                <div class="col-9">
                                    <label class="form-label">Mobile Number</label>
                                    <input id="dataInput" class="form-control" type="text"
                                        placeholder="Enter Mobile Number">
                                </div>
                                <div class="col-3">
                                    <label class="form-label" style="visibility:hidden;">Mobile</label>
                                    <button class="btn btn-primary w-100" type="button" onclick="addData()">
                                        <i class="bi bi-check-circle-fill me-2"></i>Add
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Hidden JSON Holder -->
                        <input type="hidden" name="data_ids" id="data_ids">

                        <!-- Buttons -->
                        <div class="tile-footer mb-3">
                            <button class="btn btn-primary" type="submit">
                                <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>Mobile Number</th>
                                            <th>DELETE</th>
                                        </tr>
                                    </thead>
                                    <tbody id="socialTableBody"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </form>




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


    <script>
    const existingCDRIds = <?= !empty($CDRData['cdr_id'])
    ? json_encode(json_decode($CDRData['cdr_id'], true))
    : '[]'; ?>;
    </script>


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

    /* ======================
       ON PAGE LOAD
    ====================== */
    window.onload = function() {

        // Auto set today's date
        const today = new Date();
        document.getElementById("toDate").value = formatDate(today);

        // Load existing CDR data
        if (Array.isArray(existingCDRIds)) {
            existingCDRIds.forEach(entry => {
                addExistingRow(entry);
                dataIds.push(entry);
            });
            updateHiddenField();
        }
    };

    /* ======================
       DATE FORMAT
    ====================== */
    function formatDate(inputDate) {
        const date = new Date(inputDate);
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = date.getFullYear();
        return `${day}-${month}-${year}`;
    }

    /* ======================
       ADD EXISTING ROW
    ====================== */
    function addExistingRow(entry) {
        const tableBody = document.getElementById("socialTableBody");

        const row = document.createElement("tr");
        row.innerHTML = `
        <td>${idCounter++}</td>
        <td>
            ${entry.number}<br>
            <small>${entry.from_date} to ${entry.to_date}</small>
        </td>
        <td>
            <button type="button"
                class="btn btn-danger btn-sm"
                onclick="deleteRow(this, '${entry.number}')">
                Delete
            </button>
        </td>
    `;

        tableBody.appendChild(row);
    }

    /* ======================
       ADD NEW DATA
    ====================== */
    function addData() {
        const input = document.getElementById("dataInput");
        const fromDateRaw = document.getElementById("fromDate").value;
        const value = input.value.trim();

        if (!value) {
            alert("Please enter Mobile Number");
            return;
        }

        if (!fromDateRaw) {
            alert("Please select From Date");
            return;
        }

        // Prevent duplicate numbers
        if (dataIds.some(item => item.number === value)) {
            alert("Mobile number already added");
            return;
        }

        const entry = {
            number: value,
            from_date: formatDate(fromDateRaw),
            to_date: formatDate(new Date())
        };

        dataIds.push(entry);
        addExistingRow(entry);
        updateHiddenField();

        input.value = "";
    }

    /* ======================
       DELETE ROW
    ====================== */
    function deleteRow(button, number) {
        button.closest("tr").remove();

        const index = dataIds.findIndex(item => item.number === number);
        if (index !== -1) {
            dataIds.splice(index, 1);
        }

        updateHiddenField();
    }

    /* ======================
       UPDATE HIDDEN FIELD
    ====================== */
    function updateHiddenField() {
        document.getElementById("data_ids").value = JSON.stringify(dataIds);
    }
    </script>

    <script>
    const fraudTypes = [{
            value: "identity_theft",
            label: "Identity Theft"
        },
        {
            value: "cyber_fraud",
            label: "Cyber Fraud"
        },
        {
            value: "financial_fraud",
            label: "Financial Fraud"
        },
        {
            value: "phishing",
            label: "Phishing"
        },
        {
            value: "other",
            label: "Other"
        }
    ];

    const fraudTypeSelect = document.getElementById("fraudTypeSelect");

    fraudTypes.forEach(type => {
        const option = document.createElement("option");
        option.value = type.value;
        option.textContent = type.label;
        fraudTypeSelect.appendChild(option);
    });

    fraudTypeSelect.addEventListener("change", function() {
        const selected = this.value;

    });
    </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>