<?php
session_start();
require_once '../config/database.php';

header('Content-Type: application/json');

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "customer") {
    echo json_encode(["success" => false]);
    exit;
}

$stmt = $pdo->prepare("SELECT id FROM customers WHERE user_id = ? LIMIT 1");
$stmt->execute([$_SESSION["user_id"]]);
$customer = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$customer) {
    echo json_encode(["success" => false]);
    exit;
}

$stmt = $pdo->prepare("
    SELECT balance
    FROM customers
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$customer["id"]]);
$currentBalance = $stmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM transactions
    WHERE to_type = 'customer'
    AND to_id = ?
    AND customer_read_at IS NULL
");
$stmt->execute([$customer["id"]]);

echo json_encode([
    "success" => true,
    "unread" => (int)$stmt->fetchColumn(),
    "balance" => number_format((float)$currentBalance, 2)
]);