<?php
session_start();
include "config.php";
$currentDate = "__/" . date("m/Y");
if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['social_id'])) {
    $platform = $_POST['platform'] ?? '';
    $print = $_POST['print'] ?? '';
    $Id = intval($_POST['social_id']);

    // Fetch Facebook data
    $query = "SELECT * FROM `social_media` WHERE id = $Id";
    $result = mysqli_query($con, $query);

    if (!$result || mysqli_num_rows($result) == 0) {
        exit("No record found.");
    }

    $data = mysqli_fetch_assoc($result);
    $c_id = intval($data['c_id']);
    $policeId = intval($data['police_id']);
    $noticeId = intval($data['n_id']);
    $subjectId = intval($data['s_id']);
    $policeStationName = "";
    $pAddress = "";
    $pLandLine = "";
    $pEmail = "";
    $noticeName = "";
    $policeName = "";
    $policeDesignation = "";
    $complainantName = "";
    $policeNumber = "";
    $subjectName = "";


    // Fetch cyber_police data using c_id
    $cpQuery = "SELECT * FROM cyber_police WHERE id = '$c_id'";
    $cpResult = mysqli_query($con, $cpQuery);

    if ($cpRow = mysqli_fetch_assoc($cpResult)) {
        $type = $cpRow['atf'];

        // Map ATF type to human-readable string
        switch ($type) {
            case '0':
                $typeLabel = "Acknowledgement";
                break;
            case '1':
                $typeLabel = "FIR";
                break;
            case '2':
                $typeLabel = "Ticket"; // if you have a third type
                break;
            default:
                $typeLabel = "Unknown";
                break;
        }

        $acknowledgement_no = $cpRow['acknowlegement'];
        $complainant_name = $cpRow['complain_name'];
        $policestationId = $cpRow['pid'];
        $mobile = $cpRow['mobile'];
        $incident_date_time = $cpRow['incident_date_time'];
        $total_fraud_amount = $cpRow['total_fraud_amount'];
        $total_lien_amount = $cpRow['total_lien_amount'];
        $atf = $cpRow['atf'];
        $status = $cpRow['status'];
        $time_stamp = $cpRow['time_stamp'];
    }




    // Fetch Police Station
    $policeStation = $con->query("SELECT * FROM `policestation` WHERE id = $policestationId")->fetch_assoc();

    // Fetch Police Inspector
    $police = $con->query("SELECT * FROM `police` WHERE id = $policeId LIMIT 1")->fetch_assoc();

    // Fetch Notice
    $notice = $con->query("SELECT `n_name` FROM `notice` WHERE id = $noticeId LIMIT 1")->fetch_assoc();

    // Fetch Subject
    $subject = $con->query("SELECT `s_name` FROM `subject` WHERE id = $subjectId LIMIT 1")->fetch_assoc();

    // Display Information
// echo "<h3>Facebook Data Details:</h3>";
// echo "<p><strong>ID:</strong> {$data['id']}</p>";
// echo "<p><strong>UID:</strong> {$data['uid']}</p>";
// echo "<p><strong>Acknowledgement No:</strong> {$acknowledgement_no}</p>";
// echo "<p><strong>Fraud Type:</strong> {$data['fraud_type']}</p>";
// echo "<p><strong>Notice:</strong> {$notice['n_name']}</p>";
// echo "<p><strong>Subject:</strong> {$subject['s_name']}</p>";
// echo "<p><strong>Created At:</strong> {$data['created_at']}</p>";

    $policeStationName = $policeStation['p_name'];
    $pAddress = $policeStation['p_address'];
    $pLandLine = $policeStation['p_landline'];
    $pEmail = $policeStation['p_email'];
    $noticeName = $notice['n_name'];
    $subjectName = $subject['s_name'];
    $policeName = $police['i_name'];
    $policeDesignation = $police['i_designation'];
    $policeNumber = $police['i_number'];
    $complainantName = "";

    // Display Police Station
// echo "<h4>Police Station:</h4>";
// echo "<p><strong>Name:</strong> {$policeStation['p_name']}</p>";
// echo "<p><strong>Address:</strong> {$policeStation['p_address']}</p>";
// echo "<p><strong>Landline:</strong> {$policeStation['p_landline']}</p>";
// echo "<p><strong>Mobile:</strong> {$policeStation['p_number']}</p>";
// echo "<p><strong>Email:</strong> {$policeStation['p_email']}</p>";

    // // Display Police Inspector
// echo "<h4>Police Inspector:</h4>";
// echo "<p><strong>Name:</strong> {$police['i_name']}</p>";
// echo "<p><strong>Mobile:</strong> {$police['i_number']}</p>";
// echo "<p><strong>Designation:</strong> {$police['i_designation']}</p>";

} else {
    echo "Invalid request.";
}


if ($print === 'true') {
    //  echo '<script>window.onload = function() { window.print(); }</script>'; 
}

?>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title><?php echo strtoupper($platform); ?></title>
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="css/styles.css"> <!-- External CSS file -->
</head>

<body>

    <div class="a4-container">
        <!-- Header -->
        <div class="header-container">
            <img src="images/gp_logo.png" class="logo-left" alt="Police Logo">
            <div class="header-text">
                <h2><?php echo $policeStationName ?></h2>
                <p><?php echo htmlspecialchars($pAddress); ?></p>
                <p>Tel. no. <?php echo $pLandLine ?></p>
                <p class="email">E-mail ID: <?php echo $pEmail; ?></p>
            </div>
            <img src="images/azadi.png" class="logo-right" alt="Azadi Ka Amrit Mahotsav">
        </div>

        <!-- Title -->
        <div class="section-title">
            <?php echo strtoupper($noticeName); ?>
        </div>

        <!-- Outward block right aligned -->
        <div class="outward-details">
            <div class="outward-box">
                <b>
                    Outward number _________/2025,<br>
                    Date-<?php echo $currentDate; ?>
                </b>
            </div>
        </div>

        <!-- Recipient Info -->
        <div class="to-box">
            <?php
            $platform = strtolower($platform); // Normalize input
            $address = '';

            switch ($platform) {
                case 'instagram':
                    $address = "Instagram<br>Meta Platforms, Inc.<br>1601 Willow Road,<br>Menlo Park, CA 94025.";
                    break;
                case 'whatsapp':
                    $address = "WhatsApp<br>Meta Platforms, Inc.<br>1601 Willow Road,<br>Menlo Park, CA 94025.";
                    break;
                case 'facebook':
                    $address = "Facebook<br>Meta Platforms, Inc.<br>1601 Willow Road,<br>Menlo Park, CA 94025.";
                    break;
                case 'google':
                    $address = "Google LLC<br>1600 Amphitheatre Parkway,<br>Mountain View, CA 94043.";
                    break;
                case 'snapchat':
                    $address = "Snap Inc.<br>2772 Donald Douglas Loop N,<br>Santa Monica, CA 90405.";
                    break;
                case 'twitter-x':
                case 'twitter':
                    $address = "X Corp. (formerly Twitter)<br>1355 Market Street,<br>San Francisco, CA 94103.";
                    break;
                default:
                    $address = ucfirst($platform);
                    break;
            }
            ?>

            <b>
                To,<br>
                <?= $address ?>
            </b>

        </div>

        <div class="subject">
            Subject: <?php echo $subjectName; ?>
        </div>


        <div class="letter-body">
            <p><b>Dear Sir/Madam,</b></p>

            <p>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                I, the undersigned <b><?php echo $policeName; ?></b>, currently serving as
                <b><?php echo $policeDesignation; ?></b>
                at <b><?php echo $policeStationName; ?></b>, am the designated Investigating Officer for the case
                registered under

                <?php
                $typeLabel = '';

                if ($type == 0) {
                    $typeLabel = 'Acknowledgement Number ';
                } elseif ($type == 1) {
                    $typeLabel = 'Ticket Number ';
                } elseif ($type == 2) {
                    $typeLabel = 'FIR Number';
                }
                ?>
                <b><?php echo $typeLabel; ?> : <?php echo htmlspecialchars($acknowledgement_no); ?></b>
                This case is under active investigation and pertains to suspected cyber activities. During the course of
                inquiry,
                it has been observed that the <b><?= ucfirst($platform) ?> ID(s)</b> listed below may be involved in
                activities
                such as
                financial fraud,
                identity impersonation, online cheating, and potential violations under the Information Technology
                Act.<br>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                We respectfully request your cooperation in providing relevant account details and associated data to
                support
                this investigation.
            </p>
        </div>

        <div class="account-table">
            <table class="w3-table-all w3-bordered">
                <thead>
                    <tr>
                        <th>Sr No.</th>
                        <th><?= ucfirst($platform) ?> ID</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $fbIds = json_decode($data['social_id'], true);

                    if (!is_array($fbIds)) {
                        $fbIds = explode(',', $data['social_id']);
                    }

                    foreach ($fbIds as $i => $fbId) {

                        $fbId = trim($fbId);

                        // If ID is 16 characters long and alphanumeric → treat as device ID
                        if (preg_match('/^[a-fA-F0-9]{16}$/', $fbId)) {
                            $displayId = $fbId . " (device id)";
                        } else {
                            $displayId = $fbId;
                        }

                        echo "<tr>
            <td>" . ($i + 1) . "</td>
            <td>" . htmlspecialchars($displayId) . "</td>
        </tr>";
                    }
                    ?>

                </tbody>
            </table>
        </div>

        <div class="instruction-block">
            <p>
                In accordance with the provisions of <b>BNS Section 318(4)</b> and <b>Section 66(B) of the Information
                    Technology Act, 2008</b>,
                I hereby request access to the following information related to the listed <b> <?= ucfirst($platform) ?>
                    account(s):</b>
            </p>
            <ol>
                <li>Account registration details (Full name, email address, linked phone numbers, etc.)</li>
                <li>IP logs and device login history</li>
                <li>Communication/chat records, if available and legally permissible</li>
                <li>Any complaints or reports filed against this account</li>
                <li>Linked transactions or associated business activities</li>
                <li>Any additional information relevant to the investigation</li>
            </ol>

            <p>
                The requested information is crucial to the progress of an ongoing criminal investigation. We kindly
                request that you
                treat this matter with urgency and confidentiality.<br><b>Thanking you,</b></p>
        </div>

        <!-- Signature Wrapper -->
        <div class="signature-container">
            <div class="signature-block">
                <b>
                    (<?php echo strtoupper($policeName); ?>)<br>
                    <?php echo strtoupper($policeDesignation); ?><br>
                    <?php echo strtoupper($policeStationName); ?><br>
                    <?php echo strtoupper($pAddress); ?><br>
                    <?php echo strtoupper($policeNumber); ?>
                </b>
            </div>

        </div>


    </div>

</body>

</html>