<?php
require_once __DIR__ . '/common.php';

$input = mobile_input();
mobile_boot_tenant($input);

$email = trim((string)($input['username'] ?? $input['email'] ?? ''));
$password = (string)($input['password'] ?? '');

if ($email === '' || $password === '') {
    mobile_json(['ok' => false, 'error' => 'Missing surveyor credentials'], 400);
}

$stmt = $GLOBALS['con']->prepare("SELECT `id`, `email`, `forename`, `surname`, `access`, `statuslive`, `contractor`, `delAuth` FROM `surveyor` WHERE `email`=? AND `password`=AES_ENCRYPT(?, ?) LIMIT 1");
if (!$stmt) {
    mobile_json(['ok' => false, 'error' => 'Login unavailable'], 500);
}
$stmt->bind_param('sss', $email, $password, $email);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
$surveyor = mysqli_fetch_assoc($result);

if (!$surveyor) {
    mobile_json(['ok' => false, 'error' => 'Invalid surveyor credentials'], 401);
}

if ((int)($surveyor['access'] ?? 0) === 0 || (int)($surveyor['statuslive'] ?? 0) !== 1) {
    mobile_json(['ok' => false, 'error' => 'Surveyor account is not active'], 403);
}

$surveyorId = (int)$surveyor['id'];

mobile_json([
    'ok' => true,
    'token' => mobile_create_token($surveyorId, (string)$surveyor['email']),
    'expires_in' => 60 * 60 * 24 * 7,
    'tenant' => [
        'url' => defined('TENANT_URL') ? TENANT_URL : '',
        'root_url' => defined('ROOT_URL') ? ROOT_URL : 'enrepcore',
    ],
    'surveyor' => [
        'id' => $surveyorId,
        'name' => trim((string)($surveyor['forename'] ?? '') . ' ' . (string)($surveyor['surname'] ?? '')),
        'email' => (string)$surveyor['email'],
        'delivery_auth' => (int)($surveyor['delAuth'] ?? 0) !== 0,
        'contractor' => (int)($surveyor['contractor'] ?? 0),
    ],
]);
