<?php
require_once 'db.php';

// Helper function to create an in-app notification programmatically
function createNotification($pdo, $userEmail, $role, $title, $message, $type = 'general', $link = '') {
    try {
        $stmt = $pdo->prepare("INSERT INTO notifications (user_email, role, title, message, type, is_read, link, createdAt) VALUES (?, ?, ?, ?, ?, 0, ?, ?)");
        $stmt->execute([
            $userEmail ?? '',
            $role ?? 'customer',
            $title,
            $message,
            $type,
            $link ?? '',
            time()
        ]);
        return true;
    } catch (Exception $e) {
        error_log("Failed to create notification: " . $e->getMessage());
        return false;
    }
}

if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $email = $_GET['email'] ?? '';
        $role = $_GET['role'] ?? 'customer';

        try {
            if ($email) {
                $stmt = $pdo->prepare("SELECT * FROM notifications WHERE user_email = ? OR role = 'all' ORDER BY createdAt DESC LIMIT 50");
                $stmt->execute([$email]);
            } else {
                $stmt = $pdo->prepare("SELECT * FROM notifications WHERE role = ? OR role = 'all' ORDER BY createdAt DESC LIMIT 50");
                $stmt->execute([$role]);
            }
            $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Cast is_read to boolean
            foreach ($notifications as &$n) {
                $n['is_read'] = (bool)$n['is_read'];
                $n['createdAt'] = (int)$n['createdAt'];
            }

            echo json_encode($notifications);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    } else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents("php://input"), true);
        $action = $_GET['action'] ?? '';

        if ($action === 'mark_read') {
            $id = $data['id'] ?? null;
            if ($id) {
                $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = ?");
                $stmt->execute([$id]);
                echo json_encode(['success' => true]);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'Notification ID required']);
            }
        } else if ($action === 'mark_all_read') {
            $email = $data['email'] ?? '';
            if ($email) {
                $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_email = ? OR role = 'all'");
                $stmt->execute([$email]);
                echo json_encode(['success' => true]);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'User email required']);
            }
        } else if ($action === 'create') {
            $success = createNotification(
                $pdo,
                $data['user_email'] ?? '',
                $data['role'] ?? 'customer',
                $data['title'] ?? 'Notification',
                $data['message'] ?? '',
                $data['type'] ?? 'general',
                $data['link'] ?? ''
            );
            echo json_encode(['success' => $success]);
        }
    }
}
?>
