<?php
declare(strict_types=1);

// push_subscribe.php
header('Content-Type: application/json; charset=utf-8');

// حتماً قبل از استفاده از $_SESSION
session_start();

require __DIR__ . '/db.php'; // اتصال PDO

// تابع کمکى: پیدا کردن user_id از روی ایمیل سشن
function current_user_id_from_session(PDO $pdo): ?int
{
    $email = $_SESSION['user_email'] ?? '';
    if ($email === '') {
        return null;
    }

    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :e LIMIT 1");
    $stmt->execute([':e' => $email]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ? (int)$row['id'] : null;
}

// داده خام JSON
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data) || empty($data['endpoint'])) {
    echo json_encode([
        'ok'      => false,
        'message' => 'Invalid subscription payload',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$endpoint = trim($data['endpoint']);
$keys     = $data['keys'] ?? [];
$p256dh   = isset($keys['p256dh']) ? trim($keys['p256dh']) : '';
$auth     = isset($keys['auth'])   ? trim($keys['auth'])   : '';

if ($endpoint === '' || $p256dh === '' || $auth === '') {
    echo json_encode([
        'ok'      => false,
        'message' => 'Missing endpoint/keys',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// اگر لاگین باشد → user_id واقعی
$userId    = current_user_id_from_session($pdo); // ممکن است null باشد (مهمان)
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

try {
    // چک کنیم آیا قبلاً این endpoint ثبت شده یا نه
    $sql = "SELECT id FROM push_subscriptions WHERE endpoint = :endpoint LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':endpoint' => $endpoint]);
    $existingId = $stmt->fetchColumn();

    if ($existingId) {
        // آپدیت رکورد قبلی
        $sql = "
            UPDATE push_subscriptions
            SET user_id = :user_id,
                p256dh_key = :p256dh,
                auth_key = :auth,
                user_agent = :user_agent,
                updated_at = NOW()
            WHERE id = :id
        ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':user_id'    => $userId,
            ':p256dh'     => $p256dh,
            ':auth'       => $auth,
            ':user_agent' => $userAgent,
            ':id'         => $existingId,
        ]);
    } else {
        // این اولین باره؛ رکورد جدید
        $sql = "
            INSERT INTO push_subscriptions (user_id, endpoint, p256dh_key, auth_key, user_agent, created_at)
            VALUES (:user_id, :endpoint, :p256dh, :auth, :user_agent, NOW())
        ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':user_id'    => $userId,
            ':endpoint'   => $endpoint,
            ':p256dh'     => $p256dh,
            ':auth'       => $auth,
            ':user_agent' => $userAgent,
        ]);
    }

    echo json_encode([
        'ok'      => true,
        'message' => 'Subscription saved',
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    echo json_encode([
        'ok'      => false,
        'message' => 'DB error',
    ], JSON_UNESCAPED_UNICODE);
}
