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

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

try {

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

    /* =========================
       ROLE CHECK
       ========================= */
    if (!in_array($user['role_key'], [
        'user',
        'supervisor',
        'manager',
        'company_admin'
    ], true)) {
        error_forbidden('Role not permitted to submit 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.id AS company_id, c.company_name
        FROM md_declarations d
        JOIN companies c ON c.id = d.mine_id
        WHERE d.id = :id
          AND d.status = 'draft'
        FOR UPDATE
    ");

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

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

    /* =========================
       COMPANY ISOLATION
       ========================= */

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

    /* =========================
       GENERATE NUMBER
       ========================= */

    $companyName = trim((string)$decl['company_name']);

    /*
    Create abbreviation from company name
    Example:
    "Anglo American Platinum" → AAP
    "Impala Platinum" → IP
    */
    $words = preg_split('/\s+/', $companyName);
    
    $abbr = '';
    
    foreach ($words as $w) {
        if ($w !== '') {
            $abbr .= strtoupper(substr($w, 0, 1));
        }
    }
    
    /* fallback if single word */
    if (strlen($abbr) < 3) {
        $abbr = strtoupper(substr($companyName, 0, 3));
    }

    $custShort = substr($abbr, 0, 5);
    $declNumber = generateDeclarationNumber($pdo, $custShort);

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

    $update = $pdo->prepare("
        UPDATE md_declarations
        SET declaration_number = :num,
            status = 'submitted',
            locked_at = NOW()
        WHERE id = :id
    ");

    $update->execute([
        'num' => $declNumber,
        'id'  => $declarationId
    ]);

    $pdo->commit();

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

    audit_log(
        $pdo,
        $user,
        'submit',
        'md_declaration',
        $declarationId,
        [
            'declaration_number' => $declNumber,
            'previous_status' => 'draft',
            'new_status' => 'submitted',
            'sync_mode' => 'push_on_connect'
        ]
    );

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

    success('Declaration submitted', [
        'declaration_number' => $declNumber
    ]);

} catch (Throwable $e) {

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

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

    error_server('Failed to submit declaration');
}