<?php
declare(strict_types=1);

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

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

$user = require_auth($pdo);

/* =========================
   ROLE CHECK
   ========================= */

if (!in_array($user['role_key'], ['supervisor','manager','company_admin'], true)) {
    error_forbidden('Not permitted');
}

/* =========================
   INPUT
   ========================= */

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

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

/* =========================
   LOAD DECLARATION
   ========================= */

$stmt = $pdo->prepare("
    SELECT *
    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');
}

/* =========================
   SHIFTBOSS SECURITY
   ========================= */

if ($user['role_key'] === 'supervisor') {

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

/* =========================
   LOAD ANSWERS
   ========================= */

$stmt = $pdo->prepare("
    SELECT
        question_key,
        answer_value
    FROM md_answers
    WHERE declaration_id = :id
");

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

$answers = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   LOAD PHOTOS
   ========================= */

$stmt = $pdo->prepare("
    SELECT
        question_key,
        file_path
    FROM md_photos
    WHERE declaration_id = :id
");

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

$photos = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   LOAD SIGNATURES
   ========================= */

$stmt = $pdo->prepare("
    SELECT
        role,
        file_path,
        signed_at
    FROM md_signatures
    WHERE declaration_id = :id
");

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

$signatures = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

success('Declaration loaded', [
    'declaration' => $declaration,
    'answers' => $answers,
    'photos' => $photos,
    'signatures' => $signatures
]);