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

$input = mobile_input();
mobile_boot_tenant($input);
$authorisedSurveyor = mobile_authorise();
$surveyorId = (int)($authorisedSurveyor['id'] ?? 0);
$action = strtolower(trim((string)($input['action'] ?? 'get')));

if ($surveyorId <= 0) {
    mobile_json(['ok' => false, 'error' => 'Surveyor unavailable'], 400);
}

function mobile_profile_column_exists(mysqli $con, string $column): bool
{
    $stmt = $con->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'surveyor' AND COLUMN_NAME = ? LIMIT 1");
    if (!$stmt) {
        return false;
    }
    $stmt->bind_param('s', $column);
    $stmt->execute();
    $stmt->store_result();
    $exists = $stmt->num_rows > 0;
    $stmt->close();
    return $exists;
}

function mobile_profile_normalise_day_start($value): ?string
{
    $value = trim((string)$value);
    if ($value === '') {
        return null;
    }
    if (preg_match('/^([01]?\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/', $value, $matches)) {
        return sprintf('%02d:%02d:00', (int)$matches[1], (int)$matches[2]);
    }
    return null;
}

function mobile_profile_require_string(array $input, string $key, string $label): string
{
    $value = trim((string)($input[$key] ?? ''));
    if ($value === '') {
        mobile_json(['ok' => false, 'error' => $label . ' is required'], 400);
    }
    return $value;
}

function mobile_profile_load(int $surveyorId): array
{
    $hasDayStartTime = mobile_profile_column_exists($GLOBALS['con'], 'day_start_time');
    $dayStartSelect = $hasDayStartTime ? ", `day_start_time`" : "";
    $sql = "SELECT `id`, `surname`, `forename`, `address1`, `address2`, `address3`, `postcode`, `phone1`, `phone2`, `fax`, `mobile`, AES_DECRYPT(`password`, `email`) AS `password_plain`, `email`, `qual`{$dayStartSelect} FROM `surveyor` WHERE `id`=? LIMIT 1";
    $stmt = $GLOBALS['con']->prepare($sql);
    if (!$stmt) {
        mobile_json(['ok' => false, 'error' => 'Profile unavailable'], 500);
    }
    $stmt->bind_param('i', $surveyorId);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
    $row = mysqli_fetch_assoc($result);
    if (!$row) {
        mobile_json(['ok' => false, 'error' => 'Profile not found'], 404);
    }

    return [
        'id' => (int)$row['id'],
        'forename' => (string)($row['forename'] ?? ''),
        'surname' => (string)($row['surname'] ?? ''),
        'address1' => (string)($row['address1'] ?? ''),
        'address2' => (string)($row['address2'] ?? ''),
        'address3' => (string)($row['address3'] ?? ''),
        'postcode' => (string)($row['postcode'] ?? ''),
        'phone1' => (string)($row['phone1'] ?? ''),
        'phone2' => (string)($row['phone2'] ?? ''),
        'fax' => (string)($row['fax'] ?? ''),
        'mobile' => (string)($row['mobile'] ?? ''),
        'email' => (string)($row['email'] ?? ''),
        'qual' => (string)($row['qual'] ?? ''),
        'day_start_time' => $hasDayStartTime && !empty($row['day_start_time']) ? substr((string)$row['day_start_time'], 0, 5) : '',
        'password' => (string)($row['password_plain'] ?? ''),
    ];
}

if ($action === 'update') {
    $forename = mobile_profile_require_string($input, 'forename', 'Forename');
    $surname = mobile_profile_require_string($input, 'surname', 'Surname');
    $address1 = mobile_profile_require_string($input, 'address1', 'Address1');
    $postcode = mobile_profile_require_string($input, 'postcode', 'Postcode');
    $phone1 = mobile_profile_require_string($input, 'phone1', 'Phone1');
    $email = mobile_profile_require_string($input, 'email', 'Email');
    $qual = mobile_profile_require_string($input, 'qual', 'Qualifications');
    $password = mobile_profile_require_string($input, 'password', 'Password');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        mobile_json(['ok' => false, 'error' => 'Email is not valid'], 400);
    }

    $hasDayStartTime = mobile_profile_column_exists($GLOBALS['con'], 'day_start_time');
    $dayStartTime = mobile_profile_normalise_day_start($input['day_start_time'] ?? '');
    if ($hasDayStartTime && trim((string)($input['day_start_time'] ?? '')) !== '' && $dayStartTime === null) {
        mobile_json(['ok' => false, 'error' => 'Day start time must be HH:MM'], 400);
    }

    $dayStartClause = $hasDayStartTime ? ", `day_start_time`=?" : "";
    $sql = "UPDATE `surveyor` SET
        `surname`=?, `forename`=?, `address1`=?, `address2`=?, `address3`=?, `postcode`=?,
        `phone1`=?, `phone2`=?, `fax`=?, `mobile`=?,
        `password`=AES_ENCRYPT(?, ?), `email`=?, `qual`=?{$dayStartClause}
        WHERE `id`=?";
    $stmt = $GLOBALS['con']->prepare($sql);
    if (!$stmt) {
        mobile_json(['ok' => false, 'error' => 'Profile save unavailable'], 500);
    }
    $address2 = trim((string)($input['address2'] ?? ''));
    $address3 = trim((string)($input['address3'] ?? ''));
    $phone2 = trim((string)($input['phone2'] ?? ''));
    $fax = trim((string)($input['fax'] ?? ''));
    $mobile = trim((string)($input['mobile'] ?? ''));
    if ($hasDayStartTime) {
        $stmt->bind_param(
            'sssssssssssssssi',
            $surname,
            $forename,
            $address1,
            $address2,
            $address3,
            $postcode,
            $phone1,
            $phone2,
            $fax,
            $mobile,
            $password,
            $email,
            $email,
            $qual,
            $dayStartTime,
            $surveyorId
        );
    } else {
        $stmt->bind_param(
            'ssssssssssssssi',
            $surname,
            $forename,
            $address1,
            $address2,
            $address3,
            $postcode,
            $phone1,
            $phone2,
            $fax,
            $mobile,
            $password,
            $email,
            $email,
            $qual,
            $surveyorId
        );
    }
    $ok = $stmt->execute();
    $stmt->close();
    if (!$ok) {
        mobile_json(['ok' => false, 'error' => 'Profile could not be saved'], 500);
    }
}

mobile_json([
    'ok' => true,
    'profile' => mobile_profile_load($surveyorId),
]);
