<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ✅ Include your config (it already has the DB connection)
include_once __DIR__ . "/../config.php";

// ✅ Check if connection exists
if (!isset($conn) || $conn->connect_error) {
    echo json_encode([
        "success" => false,
        "message" => "Database connection failed: " . ($conn->connect_error ?? 'Unknown error')
    ]);
    exit;
}

// ✅ Query to find inactive users (no login in last 7 days)
$sql = "
    SELECT 
        u.id,
        u.first_name,
        u.last_name,
        u.email,
        u.country,
        COALESCE(MAX(l.created_at), NULL) AS last_login
    FROM 
        loginusers u
    LEFT JOIN login_activity l 
ON CONVERT(u.email USING utf8mb4) COLLATE utf8mb4_general_ci = 
   CONVERT(l.email USING utf8mb4) COLLATE utf8mb4_general_ci

    GROUP BY 
        u.id, u.first_name, u.last_name, u.email, u.country
    HAVING 
        last_login IS NULL OR last_login < DATE_SUB(NOW(), INTERVAL 7 DAY)
";

$result = $conn->query($sql);

// ✅ Check for SQL errors
if (!$result) {
    echo json_encode([
        "success" => false,
        "message" => "Query error: " . $conn->error
    ]);
    exit;
}

$users = [];
while ($row = $result->fetch_assoc()) {
    $users[] = $row;
}

echo json_encode([
    "success" => true,
    "count" => count($users),
    "inactive_users" => $users
]);
?>
