<?php
declare(strict_types=1);

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

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

$user = require_auth($pdo);

/* ---------- INPUT ---------- */

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

$allowedRoles = ['miner','assistant','team','shiftboss'];

if ($declarationId <= 0 || !in_array($role, $allowedRoles, true)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid declaration or role']);
    exit;
}

if (!in_array($identityMode, ['NFC','MANUAL'], true)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid identity_mode']);
    exit;
}

if (!isset($_FILES['signature']) || $_FILES['signature']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => 'Signature file missing']);
    exit;
}

/* ---------- IDENTITY VALIDATION ---------- */

$cardUid = null;
$companyNumber = null;
$firstName = null;
$lastName = null;

if ($identityMode === 'NFC') {
    $cardUid = trim($_POST['card_uid'] ?? '');
    if ($cardUid === '') {
        http_response_code(400);
        echo json_encode(['error' => 'card_uid required for NFC']);
        exit;
    }
} else {
    $companyNumber = trim($_POST['company_number'] ?? '');
    $firstName = trim($_POST['first_name'] ?? '');
    $lastName = trim($_POST['last_name'] ?? '');

    if ($companyNumber === '' || $firstName === '' || $lastName === '') {
        http_response_code(400);
        echo json_encode(['error' => 'Manual identity incomplete']);
        exit;
    }
}

/* ---------- DECLARATION STATE ---------- */

$stmt = $pdo->prepare("
    SELECT status
    FROM md_declarations
    WHERE id = :id
");
$stmt->execute(['id' => $declarationId]);

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

if (!$decl || $decl['status'] === 'archived') {
    http_response_code(403);
    echo json_encode(['error' => 'Declaration not signable']);
    exit;
}

/* ---------- STORE FILE ---------- */

$dir = __DIR__ . '/../../storage/md/signatures/' . date('Y/m');
if (!is_dir($dir)) {
    mkdir($dir, 0770, true);
}

$filename = sprintf(
    'md_%d_%s_%d.png',
    $declarationId,
    $role,
    time()
);

$path = $dir . '/' . $filename;

if (!move_uploaded_file($_FILES['signature']['tmp_name'], $path)) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to store signature']);
    exit;
}

$relativePath = 'md/signatures/' . date('Y/m') . '/' . $filename;

/* ---------- UPSERT SIGNATURE ---------- */

$pdo->beginTransaction();

/* Remove existing signature for same user + role */
$delete = $pdo->prepare("
    DELETE FROM md_signatures
    WHERE declaration_id = :decl
      AND role = :role
      AND user_id = :user
");
$delete->execute([
    'decl' => $declarationId,
    'role' => $role,
    'user' => $user['id']
]);

$insert = $pdo->prepare("
    INSERT INTO md_signatures (
        declaration_id,
        user_id,
        role,
        identity_mode,
        card_uid,
        company_number,
        first_name,
        last_name,
        signature_path
    ) VALUES (
        :decl,
        :user,
        :role,
        :mode,
        :card,
        :company,
        :first,
        :last,
        :path
    )
");

$insert->execute([
    'decl' => $declarationId,
    'user' => $user['id'],
    'role' => $role,
    'mode' => $identityMode,
    'card' => $cardUid,
    'company' => $companyNumber,
    'first' => $firstName,
    'last' => $lastName,
    'path' => $relativePath
]);

$pdo->commit();

/* ---------- AUDIT ---------- */

audit_log(
    $pdo,
    $user,
    'modify',
    'md_declaration',
    $declarationId,
    [
        'section' => 'signature',
        'role' => $role,
        'identity_mode' => $identityMode,
        'sync_mode' => 'push_on_connect'
    ]
);

echo json_encode(['status' => 'signature_saved']);
