<?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';
require_once __DIR__ . '/../../system/notification.php';

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

try {

    /* =========================
       AUTH
       ========================= */
    $user = require_auth($pdo);

    /* =========================
       ROLE CHECK
       ========================= */
    if (!in_array($user['role_key'], [
        'supervisor',
        'manager',
        'company_admin'
    ], true)) {
        error_forbidden('Role not permitted to review declarations');
    }

    /* =========================
       INPUT
       ========================= */
    $input = json_decode(file_get_contents('php://input'), true);

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

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

    $pdo->beginTransaction();

    /* =========================
       FETCH DECLARATION
       ========================= */
    $stmt = $pdo->prepare("
        SELECT d.*, c.company_name
        FROM md_declarations d
        JOIN companies c ON c.id = d.mine_id
        WHERE d.id = :id
          AND d.status = 'submitted'
        FOR UPDATE
    ");

    $stmt->execute(['id' => $declarationId]);
    $decl = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$decl) {
        $pdo->rollBack();
        error_not_found('Declaration not found or already reviewed');
    }

    /* =========================
       COMPANY ISOLATION
       ========================= */
    if (!$user['is_global'] && (int)$decl['mine_id'] !== (int)$user['company_id']) {
        $pdo->rollBack();
        error_forbidden('Declaration outside your company');
    }

    /* =========================
       UPDATE STATUS
       ========================= */
    $update = $pdo->prepare("
        UPDATE md_declarations
        SET status = 'reviewed',
            reviewed_by = :user_id,
            reviewed_at = NOW()
        WHERE id = :id
    ");

    $update->execute([
        'user_id' => $user['id'],
        'id'      => $declarationId
    ]);

    $pdo->commit();

    /* =========================
       AUDIT
       ========================= */
    audit_log(
        $pdo,
        $user,
        'review',
        'md_declaration',
        $declarationId,
        [
            'previous_status' => 'submitted',
            'new_status' => 'reviewed',
            'sync_mode' => 'push_on_connect'
        ]
    );

    /* =========================
       RESPONSE
       ========================= */
    success('Declaration reviewed', [
        'declaration_id' => $declarationId
    ]);

} catch (Throwable $e) {

    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    error_log('MD REVIEW ERROR: ' . $e->getMessage());

    error_server('Failed to review declaration');
}