<?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'];

// Receive POST data
$type = $_POST['type'] ?? 'KYC';
$start = $_POST['start'] ?? '';
$end = $_POST['end'] ?? '';

if (!$start || !$end) {
    die("Missing date range!");
}

// 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 domain data
$sql = "SELECT 
    d.id,
    d.domain_id,
    d.status AS domain_status,
    c.acknowlegement,
    c.complain_name,
    c.mobile,
    d.created_at,
    ps.p_name AS police_station
FROM domain_data AS d
LEFT JOIN cyber_police AS c ON d.c_id = c.id
LEFT JOIN policestation ps ON c.pid = ps.id
WHERE DATE(d.created_at) BETWEEN '$start' AND '$end'
ORDER BY d.id DESC";

$result = mysqli_query($con, $sql);

// Set headers to force download as Excel
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=" . $policeStationName . "_Domain_Report_" . $start . "_to_" . $end . ".xls");
header("Pragma: no-cache");
header("Expires: 0");

echo "<table border='1'>";
echo "<tr>
<th>#</th>
<th>Acknowledgement No</th>
<th>Complainant Name</th>
<th>Mobile</th>
<th>Police Station</th>
<th>Domain ID(s)</th>
<th>Status</th>
<th>Created Date</th>
</tr>";

if (mysqli_num_rows($result) > 0) {
    $serial = 1;
    while ($row = mysqli_fetch_assoc($result)) {
        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>" . htmlspecialchars($row['police_station'] ?? '-') . "</td>";

        // Handle multiple domains
        $domains = json_decode($row['domain_id'], true);
        if (is_array($domains)) {
            $domainList = implode(", ", array_map('htmlspecialchars', $domains));
        } else {
            $domainList = htmlspecialchars($row['domain_id'] ?? '-');
        }

        echo "<td>" . $domainList . "</td>";
        echo "<td>" . htmlspecialchars($row['domain_status'] ?? '-') . "</td>";
        echo "<td>" . htmlspecialchars($row['created_at'] ?? '-') . "</td>";
        echo "</tr>";
    }
} else {
    echo "<tr><td colspan='8' style='text-align:center;'>No records found</td></tr>";
}
echo "</table>";
?>