<?php
// api/leave_notifications.php
// Leave routing + HR balance notifications.

declare(strict_types=1);

require_once __DIR__ . '/leave_common.php';

leave_ensure_tables($pdo);
$user = leave_current_user($pdo);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = strtolower(leave_clean($_GET['action'] ?? '', 40));
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

try {
    if ($method === 'GET' && $action === 'count') {
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM leave_notifications WHERE user_id = ? AND is_read = FALSE');
        $stmt->execute([(int)$user['id']]);
        leave_json(['unread_count' => (int)$stmt->fetchColumn()]);
    }

    if ($method === 'GET') {
        $limit = max(1, min(100, (int)($_GET['limit'] ?? 50)));
        $stmt = $pdo->prepare('SELECT * FROM leave_notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT ' . $limit);
        $stmt->execute([(int)$user['id']]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as &$row) {
            $row['id'] = (int)$row['id'];
            $row['leave_id'] = $row['leave_id'] !== null ? (int)$row['leave_id'] : null;
            $row['user_id'] = (int)$row['user_id'];
            $row['is_read'] = in_array($row['is_read'], [true,1,'1','t','true'], true);
        }
        leave_json(['data'=>$rows]);
    }

    if ($method === 'POST' && $action === 'mark_all_read') {
        $stmt = $pdo->prepare('UPDATE leave_notifications SET is_read = TRUE, read_at = CURRENT_TIMESTAMP WHERE user_id = ? AND is_read = FALSE');
        $stmt->execute([(int)$user['id']]);
        leave_json(['message'=>'All leave notifications marked as read.']);
    }

    if ($method === 'POST' && $id > 0) {
        $stmt = $pdo->prepare('UPDATE leave_notifications SET is_read = TRUE, read_at = CURRENT_TIMESTAMP WHERE id = ? AND user_id = ?');
        $stmt->execute([$id,(int)$user['id']]);
        leave_json(['message'=>'Leave notification marked as read.']);
    }

    leave_json(['detail'=>'Unsupported notification operation.'],405);
} catch (PDOException $e) {
    leave_json(['detail'=>'Database error: '.$e->getMessage()],500);
}
