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

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

$user = $_SESSION['user'];
$pid = $user['pid'];
$platform = $_GET['platform'] ?? '';

// Get Police Station Name
$psQuery = "SELECT p_name FROM policestation WHERE id = '$pid' LIMIT 1";
$psResult = mysqli_query($con, $psQuery);
$policeStationName = mysqli_fetch_assoc($psResult)['p_name'] ?? 'PoliceStation';

// Fetch social media data
$sql = "
    SELECT 
        s.*, 
        c.acknowlegement, 
        c.complain_name, 
        c.mobile, 
        c.incident_date_time, 
        c.status AS complain_status,
        s.status AS social_status
    FROM social_media s
    LEFT JOIN cyber_police c ON s.c_id = c.id
    WHERE s.c_id != 0
    AND c.pid = '$pid'
    AND s.type = '$platform'
    ORDER BY s.id DESC
";
$result = mysqli_query($con, $sql);

// Force browser to download Excel
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"{$policeStationName}_{$platform}_Report.xls\"");
header("Pragma: no-cache");
header("Expires: 0");

echo "<table border='1'>";

// Report Title
echo "<tr><th colspan='7' style='font-size:16px; text-align:center;'>{$policeStationName} - " . strtoupper($platform) . " Report</th></tr>";

// Table Header
echo "<tr style='background-color:#f2f2f2;'>
        <th>#</th>
        <th>Acknowledgement</th>
        <th>Complainant</th>
        <th>Mobile</th>
        <th>Social Media ID(s)</th>
        <th>Incident Date</th>
        <th>Status</th>
      </tr>";

$serial = 1;

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Decode multiple social media IDs
        $social_ids = json_decode($row['social_id'], true);
        $socialHTML = '';

        if (is_array($social_ids) && count($social_ids) > 0) {
            $socialHTML .= "<table border='1'>";
            $socialHTML .= "<tr><th>Social Media ID</th></tr>";
            foreach ($social_ids as $id) {
                $socialHTML .= "<tr><td>" . htmlspecialchars($id) . "</td></tr>";
            }
            $socialHTML .= "</table>";
        } else {
            $socialHTML = htmlspecialchars($row['social_id'] ?? '-');
        }

        echo "<tr>";
        echo "<td>{$serial}</td>";
        echo "<td>" . htmlspecialchars($row['acknowlegement'] ?? '-') . "</td>";
        echo "<td>" . htmlspecialchars($row['complain_name'] ?? '-') . "</td>";
        echo "<td>" . htmlspecialchars($row['mobile'] ?? '-') . "</td>";
        echo "<td>{$socialHTML}</td>";
        echo "<td>" . htmlspecialchars($row['incident_date_time'] ?? '-') . "</td>";
        echo "<td>" . htmlspecialchars($row['social_status'] ?? '-') . "</td>";
        echo "</tr>";

        $serial++;
    }
} else {
    echo "<tr><td colspan='7' style='text-align:center;'>No records found</td></tr>";
}

echo "</table>";
?>