<?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);
$questionKey = trim($_POST['question_key'] ?? '');

if ($declarationId <= 0 || $questionKey === '') {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid declaration or question']);
    exit;
}

if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => 'Photo missing']);
    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 || in_array($decl['status'], ['reviewed','archived'], true)) {
    http_response_code(403);
    echo json_encode(['error' => 'Declaration locked']);
    exit;
}

/* ---------- FILE VALIDATION ---------- */

$mime = mime_content_type($_FILES['photo']['tmp_name']);
if (!in_array($mime, ['image/jpeg','image/png'], true)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid image type']);
    exit;
}

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

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

$filename = sprintf(
    'md_%d_%s_%d.jpg',
    $declarationId,
    preg_replace('/[^a-zA-Z0-9_\-]/', '_', $questionKey),
    time()
);

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

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

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

/* ---------- DB INSERT ---------- */

$stmt = $pdo->prepare("
    INSERT INTO md_photos (
        declaration_id,
        question_key,
        photo_path,
        captured_by
    ) VALUES (
        :decl,
        :qkey,
        :path,
        :user
    )
");

$stmt->execute([
    'decl' => $declarationId,
    'qkey' => $questionKey,
    'path' => $relativePath,
    'user' => $user['id']
]);

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

audit_log(
    $pdo,
    $user,
    'modify',
    'md_declaration',
    $declarationId,
    [
        'section' => 'photos',
        'question_key' => $questionKey,
        'sync_mode' => 'push_on_connect'
    ]
);

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