<?php
// ✅ Headers for CORS and JSON
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Include database connection
include __DIR__ . "/../config.php";
 // make sure $conn = new mysqli(...);

try {
    // Read JSON input
    $raw = file_get_contents("php://input");
    $data = json_decode($raw, true);

    // Optional filters from JSON
    $filter_role  = isset($data['role']) ? strtolower(trim($data['role'])) : 'all'; // all/client/admin
    $filter_email = isset($data['email']) ? trim($data['email']) : '';
    $filter_date  = isset($data['date']) ? trim($data['date']) : ''; // e.g., '2025-10-18'

    // Build base query
    $query = "SELECT id, uid, email, role, action, success, ip, user_agent, created_at 
              FROM login_activity WHERE 1=1";

    $params = [];
    $types  = '';

    // Role filter
    if ($filter_role === 'admin' || $filter_role === 'client') {
        $query .= " AND role = ?";
        $params[] = $filter_role;
        $types .= 's';
    }
    // email filter
    if ($filter_email !== '') {
        $query .= " AND email = ?";
        $params[] = $filter_email;
        $types .= 's';
    }
    // date filter
    if ($filter_date !== '') {
        $query .= " AND DATE(created_at) = ?";
        $params[] = $filter_date;
        $types .= 's';
    }

    $query .= " ORDER BY created_at DESC";

    $stmt = $conn->prepare($query);

    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    $activities = [];
    while ($row = $result->fetch_assoc()) {
        $activities[] = [
            "id" => (int)$row['id'],
            "uid" => $row['uid'] !== null ? (int)$row['uid'] : null,
            "email" => $row['email'],
            "role" => $row['role'],
            "action" => $row['action'],
            "success" => (int)$row['success'],
            "ip" => $row['ip'],
            "user_agent" => $row['user_agent'],
            "created_at" => $row['created_at']
        ];
    }

    echo json_encode([
        "success" => true,
        "count" => count($activities),
        "data" => $activities
    ]);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Server error",
        "error" => $e->getMessage()
    ]);
}
