<?php
/**
 * POST /api/profile/delete
 *
 * Soft-deletes the account:
 *  - Verify password
 *  - Set status = 2 (deleted)
 *  - Scramble email to free it (append _deleted_<ts>)
 *  - Kill all sessions
 */

declare(strict_types=1);
require_once dirname(__DIR__, 2) . '/config/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonError('Method not allowed', 405);

$user = Auth::apiRequireLogin();
$pid  = (int)$user['publisher_id'];
Csrf::validate();

$password = (string)($_POST['password'] ?? '');
if ($password === '') jsonError('Please enter your password to confirm.');

$pdo = db();
$stmt = $pdo->prepare("SELECT password_hash, email FROM publisher_user WHERE id = ? LIMIT 1");
$stmt->execute([$pid]);
$row = $stmt->fetch();
if (!$row || !password_verify($password, $row['password_hash'])) {
    jsonError('Incorrect password.');
}

$pdo->beginTransaction();
try {
    $scrambled = $row['email'] . '_deleted_' . time();
    $pdo->prepare("UPDATE publisher_user SET status = 2, email = ? WHERE id = ?")
        ->execute([$scrambled, $pid]);
    Session::destroyAllFor($pid);
    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    Logger::error('Account deletion failed', ['error' => $e->getMessage()]);
    jsonError('Could not delete account. Please try again.', 500);
}

Logger::audit($pid, 'account_deleted');
jsonSuccess('Account deleted. Goodbye.', ['redirect' => '/login']);
