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


$domainId = isset($_POST['domain_id']) ? (int) $_POST['domain_id'] : 0;

$query = "
   SELECT 
    dd.id,
    dd.c_id,
    dd.police_id,
    dd.fraud_type,
    dd.n_id,
    dd.s_id,
    dd.domain_id,
    dd.created_at,
    dd.mobile,
    dd.status,
    cp.id AS cyber_id,
    cp.acknowlegement,
    cp.complain_name,
    cp.mobile AS complain_mobile,
    cp.incident_date_time,
    cp.total_fraud_amount,
    cp.total_lien_amount,
    cp.atf,
    cp.pid,
    cp.status AS cyber_status,
    cp.time_stamp
FROM domain_data AS dd
LEFT JOIN cyber_police AS cp
    ON dd.c_id = cp.id
WHERE dd.id = $domainId;
";

$resultDomain = mysqli_query($con, $query);
$DomainData = mysqli_fetch_assoc($resultDomain);
// Decode JSON domain_id

$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` = 'NOTICE UNDER SECTION 94 OF B.N.S.S 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`='Request for Suspect Account Information'";
$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">Social Media</li>
                <li class="breadcrumb-item"><a href="#"> <?php echo strtoupper($platform); ?></a></li>
            </ul>
        </div>


        <form method="POST" action="update_a_domain.php">
            <input type="hidden" name="domain_id" value="<?= $domainId ?>">

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

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

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

                            <!-- <div class="mb-3">
                                <label class="form-label">Select Fraud Type</label>
                                <select id="fraudTypeSelect" class="form-control" name="fraud_type" required>
                                    <option value="">-- Select Fraud Type --</option>
                                </select>
                            </div> -->

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

                            <div class="mb-3 d-none">
                                <label class="form-label">Select Subject</label>
                                <select class="form-control" name="subject_id" required>
                                    <?= $subjectOptions ?>
                                </select>
                            </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($DomainData['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'] == $DomainData['police_id']) ? 'selected' : '';

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

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

                        </div>

                        <div class="mb-3">
                            <div class="row">
                                <div class="col-9">
                                    <label class="form-label"><?php echo strtoupper($platform); ?> ID</label>
                                    <input id="domainInput" class="form-control" type="text"
                                        placeholder="Enter <?php echo strtoupper($platform); ?> ID Like www.google.com">

                                </div>
                                <div class="col-3">
                                    <label class="form-label"
                                        style="visibility: hidden;"><?php echo strtoupper($platform); ?></label>
                                    <button class="btn btn-primary" type="button" onclick="addDomain()">
                                        <i class="bi bi-check-circle-fill me-2"></i>Add
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Hidden field to hold all Instagram IDs -->
                        <input type="hidden" name="domain_ids" id="domain_ids">

                        <div class="tile-footer">
                            <button class="btn btn-primary" type="submit"><i
                                    class="bi bi-check-circle-fill me-2"></i>Submit</button>&nbsp;&nbsp;&nbsp;<a
                                class="btn btn-secondary" href="#"><i class="bi bi-x-circle-fill me-2"></i>Cancel</a>
                        </div>


                    </div>

                </div>

                <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><?= strtoupper($platform) ?> ID</th>
                                            <th>DELETE</th>
                                        </tr>
                                    </thead>
                                    <tbody id="socialTableBody"></tbody>

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


    <script>
    const existingdomainIds = <?=  !empty($DomainData['domain_id'])
    ? json_encode(json_decode($DomainData['domain_id'], true))
    : '[]'; ?>;
    </script>


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

    window.onload = function() {
        if (Array.isArray(existingdomainIds)) {
            existingdomainIds.forEach(value => {
                addRow(value);
                domainIds.push(value);
            });
            updateHiddenField();
        }
    };

    function addDomain() {
        const input = document.getElementById("domainInput");
        const value = input.value.trim();

        if (value === "") {
            alert("Please enter a Domain ID.");
            return;
        }

        if (domainIds.includes(value)) {
            alert("Domain already added.");
            return;
        }

        domainIds.push(value);
        addRow(value);
        updateHiddenField();
        input.value = "";
    }

    function addRow(value) {
        const tableBody = document.getElementById("socialTableBody");
        const row = document.createElement("tr");

        row.innerHTML = `
        <td>${idCounter++}</td>
        <td>${value}</td>
        <td>
            <button type="button" class="btn btn-danger btn-sm"
                onclick="deleteRow(this, '${value}')">
                Delete
            </button>
        </td>
    `;
        tableBody.appendChild(row);
    }

    function deleteRow(button, value) {
        button.closest("tr").remove();
        domainIds = domainIds.filter(v => v !== value);
        updateHiddenField();
        reindexTable();
    }

    function updateHiddenField() {
        document.getElementById("domain_ids").value = JSON.stringify(domainIds);
    }

    function reindexTable() {
        idCounter = 1;
        document.querySelectorAll("#socialTableBody tr").forEach(row => {
            row.cells[0].innerText = idCounter++;
        });
    }
    </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>