<?php
declare(strict_types=1);

/* ================= CONFIG & CORE ================= */
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

$db = Database::getInstance();

/* ================= METHOD CHECK ================= */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/* ================= INPUT ================= */
$data = json_decode(file_get_contents('php://input'), true);

/* ================= VALIDATION ================= */
Validator::required($data, ['email']);

$email = strtolower(trim($data['email']));

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    Response::error('Invalid email address', 422);
}

/* ================= LOOKUP ================= */
$stmt = $db->prepare("
    SELECT id, is_active
    FROM website_subscribers
    WHERE email = :email
");
$stmt->execute(['email' => $email]);
$subscriber = $stmt->fetch();

if (!$subscriber) {
    /* Do not reveal existence */
    Response::success('You have been unsubscribed');
}

/* ================= ALREADY INACTIVE ================= */
if ((int)$subscriber['is_active'] === 0) {
    Response::success('You have already been unsubscribed');
}

/* ================= UNSUBSCRIBE ================= */
$stmt = $db->prepare("
    UPDATE website_subscribers
    SET
        is_active = 0,
        unsubscribed_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'id' => $subscriber['id']
]);

Response::success('You have been unsubscribed successfully');
