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

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

$action = cleanInput($_POST['action'] ?? 'add');

try {
    if ($action === 'list') {
        $stmt = $pdo->prepare("SELECT id, vehiclenumber FROM villagervehicle WHERE villagerid = ? AND isdeleted = 0");
        $stmt->execute([$villager['id']]);
        jsonOut(true, '', $stmt->fetchAll());
    }

    if ($action === 'add') {
        $vehiclenumber = strtoupper(cleanInput($_POST['vehiclenumber'] ?? ''));
        if ($vehiclenumber === '') {
            jsonOut(false, 'Vehicle number is required');
        }
        $stmt = $pdo->prepare("INSERT INTO villagervehicle (villagerid, vehiclenumber) VALUES (?, ?)");
        $stmt->execute([$villager['id'], $vehiclenumber]);
        logActivity($pdo, 'villager', $villager['id'], 'addvehicle', 'villager', $villager['id'], 'Vehicle added: ' . $vehiclenumber);
        jsonOut(true, 'Vehicle added successfully', ['id' => (int)$pdo->lastInsertId()]);
    }

    if ($action === 'remove') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("UPDATE villagervehicle SET isdeleted = 1 WHERE id = ? AND villagerid = ?");
        $stmt->execute([$id, $villager['id']]);
        logActivity($pdo, 'villager', $villager['id'], 'removevehicle', 'villager', $villager['id'], 'Vehicle id ' . $id . ' removed');
        jsonOut(true, 'Vehicle removed successfully');
    }

    jsonOut(false, 'Invalid action');
} catch (Exception $e) {
    logDebug('[api_addvehicle] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
