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

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

// IMPORTANT: this call must be multipart/form-data (not JSON, not urlencoded) because
// 'photo' is an actual file field here, not a filename string. Send fullname as a normal
// text field alongside it in the same multipart request. There is no separate "upload
// first" step for this photo - api_uploadfile.php is not needed for this step.

$fullname = cleanInput($_POST['fullname'] ?? '');

if ($fullname === '') {
    jsonOut(false, 'Full name is required');
}

try {
    if (!empty($_FILES['photo']['name'])) {
        $result = uploadFile($_FILES['photo'], APPROOT . '/uploads/photos', ['jpg', 'jpeg', 'png']);
        if (!$result['success']) {
            jsonOut(false, 'Photo: ' . $result['message']);
        }
        $stmt = $pdo->prepare("UPDATE villager SET fullname = ?, photo = ? WHERE id = ?");
        $stmt->execute([$fullname, $result['filename'], $villager['id']]);
    } else {
        // Photo already set from a previous call (e.g. villager is editing just the name) - keep it as is.
        $stmt = $pdo->prepare("UPDATE villager SET fullname = ? WHERE id = ?");
        $stmt->execute([$fullname, $villager['id']]);
    }

    logActivity($pdo, 'villager', $villager['id'], 'updatename', 'villager', $villager['id'], 'Step 1 saved');

    jsonOut(true, 'Saved successfully');
} catch (Exception $e) {
    logDebug('[api_register] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
