<?php
declare(strict_types=1);

require_once __DIR__ . '/../../system/bootstrap.php';
require_once __DIR__ . '/../../system/auth.php';
require_once __DIR__ . '/../../system/response.php';
require_once __DIR__ . '/../../system/audit.php';

header('Content-Type: application/json');

$user = require_auth($pdo);

if ($user['role_key'] !== 'supervisor') {
    error_forbidden('Only shiftboss may approve declarations');
}

$declarationId = (int)($_POST['declaration_id'] ?? 0);

if ($declarationId <= 0) {
    error_bad_request('Invalid declaration_id');
}

$comment = trim($_POST['comment'] ?? '');

if (!isset($_FILES['signature'])) {
    error_bad_request('Signature image required');
}

/* =========================
   VERIFY DECLARATION
   ========================= */

$stmt = $pdo->prepare("
    SELECT id, shiftboss_id, status
    FROM md_declarations
    WHERE id = :id
    LIMIT 1
");

$stmt->execute(['id' => $declarationId]);

$declaration = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$declaration) {
    error_bad_request('Declaration not found');
}

if ((int)$declaration['shiftboss_id'] !== (int)$user['id']) {
    error_forbidden('Declaration not assigned to this shiftboss');
}

if ($declaration['status'] !== 'submitted') {
    error_bad_request('Declaration not in review state');
}

/* =========================
   SAVE SIGNATURE
   ========================= */

$uploadDir = __DIR__ . '/../../uploads/signatures/shiftboss/';

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0775, true);
}

$filename = 'shiftboss_' . $declarationId . '_' . time() . '.png';

$target = $uploadDir . $filename;

if (!move_uploaded_file($_FILES['signature']['tmp_name'], $target)) {
    error_server('Failed to save signature');
}

/* =========================
   UPDATE DECLARATION
   ========================= */

$stmt = $pdo->prepare("
    UPDATE md_declarations
    SET
        status = 'shiftboss_approved',
        shiftboss_comment = :comment,
        shiftboss_signed_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'comment' => $comment,
    'id' => $declarationId
]);

/* =========================
   AUDIT
   ========================= */

audit_log(
    $pdo,
    $user,
    'approve',
    'md_declaration',
    $declarationId,
    [
        'comment' => $comment
    ]
);

/* =========================
   RESPONSE
   ========================= */

success('Declaration approved', [
    'declaration_id' => $declarationId
]);