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

require 'conexion.php';

$data = array();

// Get the username from the query string (e.g., ?username=Januar)
$username = isset($_GET['username']) ? $_GET['username'] : '';

if ($username) {
    // Query to select notifications for the specified username
    $query = "SELECT * FROM notifications WHERE username = ? ORDER BY isRead, created_at DESC";
    $stmt = $connect->prepare($query);
    $stmt->bind_param("s", $username); // Bind the username parameter
} else {
    // If no username is provided, fetch all notifications
    $query = "SELECT * FROM notifications ORDER BY isRead, created_at DESC";
    $stmt = $connect->prepare($query);
}

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

if ($result) {
    if ($result->num_rows > 0) {
        $count = 0;
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
            if($row['isRead'] == '0'){ 
                $count++;
            }
        }
    }
    else {
    // Handle query failure
    $data = [];
    echo json_encode(["error" => "Query error: " . $connect->error]);
    exit;
}
    $data = ['data' => $data, 'count' => $count];
} else {
    // Handle query failure
    $data = [];
    echo json_encode(["error" => "Query error: " . $connect->error]);
    exit;
}

// Output the JSON data
echo json_encode($data);
?>
