<?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');

/* =========================
   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 create declarations');
}

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

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

if (!is_array($input)) {
    error_bad_request('Invalid JSON body');
}

/* client UUID (idempotent key) */

$clientUuid = trim((string)($input['client_uuid'] ?? ''));

if ($clientUuid === '') {
    error_bad_request('client_uuid is required');
}

/* validate UUID format */

if (!preg_match('/^[a-f0-9\-]{36}$/i', $clientUuid)) {
    error_bad_request('Invalid client_uuid format');
}

/* mine */

$mineId = (int)($input['mine_id'] ?? 0);

if ($mineId <= 0) {
    error_bad_request('Invalid mine_id');
}

/* optional hierarchy */

$shiftbossId = isset($input['shiftboss_id'])
    ? (int)$input['shiftboss_id']
    : null;

$managerId = isset($input['manager_id'])
    ? (int)$input['manager_id']
    : null;


/* =========================
   MINE VALIDATION
   ========================= */

$stmt = $pdo->prepare("
    SELECT id
    FROM companies
    WHERE id = :mine_id
      AND deleted_at IS NULL
    LIMIT 1
");

$stmt->execute([
    'mine_id' => $mineId
]);

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

if (!$mine) {
    error_bad_request('Mine not found');
}

/* ensure user belongs to the same company */

if (!$user['is_global'] && (int)$mineId !== (int)$user['company_id']) {
    error_forbidden('Mine does not belong to your company');
}


/* =========================
   CREATE DECLARATION (IDEMPOTENT)
   ========================= */

$pdo->beginTransaction();

/* check existing declaration */

$stmt = $pdo->prepare("
    SELECT id
    FROM md_declarations
    WHERE client_uuid = :uuid
    LIMIT 1
");

$stmt->execute([
    'uuid' => $clientUuid
]);

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

if ($existing) {

    $pdo->commit();

    success('Declaration already exists', [
        'declaration_id' => (int)$existing['id']
    ]);
}

/* =========================
   CREATE NEW DECLARATION
   ========================= */

$stmt = $pdo->prepare("
    INSERT INTO md_declarations
        (
            client_uuid,
            mine_id,
            created_by,
            shiftboss_id,
            manager_id,
            status,
            delete_after
        )
    VALUES
        (
            :uuid,
            :mine_id,
            :created_by,
            :shiftboss_id,
            :manager_id,
            'draft',
            DATE_ADD(NOW(), INTERVAL 12 MONTH)
        )
");

$stmt->execute([
    'uuid'         => $clientUuid,
    'mine_id'      => $mineId,
    'created_by'   => $user['id'],
    'shiftboss_id' => $shiftbossId,
    'manager_id'   => $managerId
]);

$declarationId = (int)$pdo->lastInsertId();

$pdo->commit();


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

audit_log(
    $pdo,
    $user,
    'create',
    'md_declaration',
    $declarationId,
    [
        'mine_id'      => $mineId,
        'shiftboss_id' => $shiftbossId,
        'manager_id'   => $managerId,
        'status'       => 'draft',
        'sync_mode'    => 'push_on_connect'
    ]
);


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

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