<?php
require_once __DIR__ . '/../includes/bootstrap.php';
requireLogin();

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

function out($ok, $error = '', $data = []) {
    echo json_encode(['ok' => (bool)$ok, 'error' => (string)$error, 'data' => $data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    out(false, 'Method not allowed');
}

try {
    orphan_verify_csrf();
} catch (Throwable $e) {
    http_response_code(403);
    out(false, 'CSRF غير صالح أو انتهت الجلسة. أعد تحميل الصفحة.');
}

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    out(false, 'معرّف الوثيقة غير صحيح.');
}

$st = $pdo->prepare("SELECT is_shareable FROM beneficiary_documents WHERE id=? LIMIT 1");
$st->execute([$id]);
$cur = $st->fetchColumn();
if ($cur === false) {
    http_response_code(404);
    out(false, 'الوثيقة غير موجودة.');
}

$newVal = ((int)$cur === 1) ? 0 : 1;

$up = $pdo->prepare("UPDATE beneficiary_documents SET is_shareable=? WHERE id=? LIMIT 1");
$up->execute([$newVal, $id]);

out(true, '', ['is_shareable' => $newVal]);