<?php
require '../db.php';
require '../functions.php';

header('Content-Type: application/json');
$villager = requireVillagerToken($pdo);

$type = cleanInput($_POST['type'] ?? '');
$allowedtypes = ['photo' => APPROOT . '/uploads/photos', 'aadhaar' => APPROOT . '/uploads/aadhaar'];

if (!isset($allowedtypes[$type])) {
    jsonOut(false, 'Invalid upload type');
}

$result = uploadFile($_FILES['file'] ?? [], $allowedtypes[$type], ['jpg', 'jpeg', 'png']);

if (!$result['success']) {
    jsonOut(false, $result['message']);
}

logActivity($pdo, 'villager', $villager['id'], 'upload' . $type, 'villager', $villager['id'], 'Uploaded ' . $type . ': ' . $result['filename']);

jsonOut(true, 'File uploaded successfully', ['filename' => $result['filename']]);
