<?php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../inc/auth.php';
auth_session_start();

if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Не авторизован']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['photo'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Нет файла']);
    exit;
}

$taskId = (int)($_POST['task_id'] ?? 0);
$reportId = (int)($_POST['report_id'] ?? 0);
$type = $_POST['type'] ?? 'other';
$desc = trim($_POST['description'] ?? '');

$uploadDir = __DIR__ . '/../uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$file = $_FILES['photo'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg','jpeg','png','gif','webp','heic'];

if (!in_array($ext, $allowed)) {
    http_response_code(400);
    echo json_encode(['error' => 'Недопустимый формат. Разрешены: ' . implode(', ', $allowed)]);
    exit;
}

if ($file['size'] > 20 * 1024 * 1024) {
    http_response_code(400);
    echo json_encode(['error' => 'Файл больше 20MB']);
    exit;
}

$fileName = uniqid('photo_') . '.' . $ext;
$destPath = $uploadDir . $fileName;

if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    http_response_code(500);
    echo json_encode(['error' => 'Ошибка сохранения файла']);
    exit;
}

$dbPath = '/service/uploads/' . $fileName;

try {
    $pdo = getDB();
    $stmt = $pdo->prepare("INSERT INTO task_photos (task_id, report_id, file_path, description, type, uploaded_by) VALUES (?,?,?,?,?,?)");
    $stmt->execute([$taskId ?: null, $reportId ?: null, $dbPath, $desc, $type, $_SESSION['user_id']]);
    echo json_encode(['success' => true, 'path' => $dbPath, 'id' => $pdo->lastInsertId()]);
} catch (\Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Ошибка БД: ' . $e->getMessage()]);
}
