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

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

    // Fetch Facebook data
    $query = "SELECT * FROM `cdr` 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 = $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 LIMIT 1")->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 -->
        <center>
            <div class="title-center" style="margin-top:10px;margin-bottom:-10px;  font-family: Arial, sans-serif;">
                <b>
                    Annexure IX<br>
                    Proforma to seek Call Data/ Detail Record
                </b>
            </div>
        </center>

        <div class="section-title">
            <?php echo strtoupper($noticeName); ?><br>
        </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">
            <b>
                To,<br>
                The Nodal Officer,<br>
                All Mobile Company Gujarat.
            </b>

        </div>

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


        <div class="account-table">
            <table class="w3-table-all w3-bordered">
                <thead>
                    <tr>
                        <th>Sr No.</th>
                        <th>Mobile No</th>
                        <th>From Date</th>
                        <th>To Date</th>
                        <th>Acknowledgement/FIR No.</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $cdrData = json_decode($data['cdr_id'], true);
                    $rowCount = is_array($cdrData) ? count($cdrData) : 0;

                    // Determine label and value based on type
                    $label = '';
                    $refNo = $acknowledgement_no;

                    if ($type == 0) {
                        $label = 'Acknowledgement No.';
                    } elseif ($type == 1) {
                        $label = 'Ticket No.';
                    } elseif ($type == 2) {
                        $label = 'FIR No.';
                    }

                    $mergedCell = "$policeStationName<br>" . htmlspecialchars($label) . "<br>" . htmlspecialchars($refNo);

                    if ($rowCount > 0) {
                        foreach ($cdrData as $i => $entry) {
                            $number = htmlspecialchars(trim($entry['number'] ?? ''));
                            $from = htmlspecialchars(trim($entry['from_date'] ?? ''));
                            $to = htmlspecialchars(trim($entry['to_date'] ?? ''));

                            echo "<tr>
                        <td>" . ($i + 1) . "</td>
                        <td>$number</td>";

                            // Merge From Date, To Date, and Acknowledgement/FIR columns
                            if ($i === 0) {
                                echo "<td rowspan=\"$rowCount\" style=\"vertical-align: middle;\">$from</td>";
                                echo "<td rowspan=\"$rowCount\" style=\"vertical-align: middle;\">$to</td>";
                                echo "<td rowspan=\"$rowCount\" style=\"vertical-align: middle;\">$mergedCell</td>";
                            }
                            echo "</tr>";
                        }
                    } else {
                        echo '<tr><td colspan="5" class="text-center">No CDR records found.</td></tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>

        <div class="instruction-block">
            <ol>
                <li>The subscriber identity has been ascertained and it is ensured that the person in question in not
                    someone whose call details are of a sensitive</li>
                <li>E nature</li>
                <li>The number is not subscriber in the name of a sitting MP/MLA</li>

            </ol>

            <p style="margin-top:-10px">
                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>


        <div class="letter-body">
            <style>
                .letter-body {
                    margin: 0;
                    padding: 0;
                }

                .letter-body .account-table {
                    margin: 0;
                    padding: 0;
                }

                .letter-body table,
                .letter-body th,
                .letter-body td {
                    width: 90%;
                    border: none !important;
                    padding: 4px 3px;
                    font-size: 14px;
                    line-height: 1.3;
                    vertical-align: top;
                    text-align: left;
                }

                .letter-body th[colspan="2"] {
                    padding-bottom: 6px;
                    font-weight: bold;
                }
            </style>

            <div class="account-table">
                <table>
                    <thead>
                        <tr>
                            <th colspan="3">(Name of the Issuing Authority)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Signature of the Investigating Officer</td>
                            <td>
                                .................................................................................................
                            </td>
                        </tr>
                        <tr>
                            <td>Name of the Investigating Officer</td>
                            <td style="text-align: center;"><b><?php echo strtoupper($policeName); ?></b></td>
                        </tr>
                        <tr>
                            <td>Designation of Investigating Officer</td>
                            <td style="text-align: center;"><u><b>
                                        <?= strtoupper($policeDesignation) ?>, <?= ucfirst($policeStationName) ?><br>
                                        <?= ucfirst($pAddress) ?>
                                    </b></u></td>
                        </tr>
                        <tr>
                            <td>Contact Details of Investigating Officer</td>
                            <td style="text-align: center;"><b><?= strtoupper($policeNumber); ?></b></td>
                        </tr>
                        <tr>
                            <td><b>Place : </b></td>
                            <td style="text-align: center;"><b><?php echo strtoupper($policeStationName); ?></b></td>
                        </tr>
                        <tr>
                            <td><b>Date : <?= $currentDate ?></b></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td>Signature of the Authorize Officer</td>
                            <td>
                                ..................................................................................................
                            </td>
                        </tr>
                        <tr>
                            <td>Name of the Authorize Officer</td>
                            <td>
                                ....................................................................................................
                            </td>
                        </tr>
                        <tr>
                            <td>Designation of the Authorize Officer</td>
                            <td>
                                .....................................................................................................
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <br>
        <br>

        <center>
            <img src="images/seald.png" alt="Seal Image" style="max-width: 200px;">
        </center>




    </div>

</body>

</html>