<?php
/**
 * Notifications API
 * Handles fetching notifications for customers
 */

require_once 'bootstrap.php';

$user_id = $_GET['user_id'] ?? $_POST['user_id'] ?? $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? null;
$recipient_type = $_GET['recipient_type'] ?? $_POST['recipient_type'] ?? (isset($_SESSION['admin_logged_in']) ? 'admin' : 'customer');

if (!$user_id) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$pdo = getDBConnection();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? 'get_notifications';

    if ($action === 'get_unread_count') {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND recipient_type = ? AND is_read = 0");
        $stmt->execute([$user_id, $recipient_type]);
        echo json_encode(['success' => true, 'unread_count' => (int)$stmt->fetchColumn()]);
        exit;
    }

    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $stmt = $pdo->prepare("
        SELECT * FROM notifications
        WHERE user_id = ? AND recipient_type = ?
        ORDER BY created_at DESC
        LIMIT ?
    ");
    $stmt->execute([$user_id, $recipient_type, $limit]);
    $notifications = $stmt->fetchAll();

    echo json_encode(['success' => true, 'notifications' => $notifications]);

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? $_POST['action'] ?? 'mark_read';

    if ($action === 'mark_read') {
        $notification_id = $input['notification_id'] ?? $_POST['notification_id'] ?? null;
        if ($notification_id) {
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ? AND recipient_type = ?");
            $stmt->execute([$notification_id, $user_id, $recipient_type]);
        } else {
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ? AND recipient_type = ?");
            $stmt->execute([$user_id, $recipient_type]);
        }
        echo json_encode(['success' => true]);
    } elseif ($action === 'delete') {
        $notification_id = $input['notification_id'] ?? $_POST['notification_id'] ?? null;
        if ($notification_id) {
            $stmt = $pdo->prepare("DELETE FROM notifications WHERE id = ? AND user_id = ? AND recipient_type = ?");
            $stmt->execute([$notification_id, $user_id, $recipient_type]);
        } else {
            $stmt = $pdo->prepare("DELETE FROM notifications WHERE user_id = ? AND recipient_type = ?");
            $stmt->execute([$user_id, $recipient_type]);
        }
        echo json_encode(['success' => true]);
    }
}
