<?php
/**
 * POST /api/profile/update.php
 * Works for ANY account type - personal, business, or admin.
 * Fields (all optional): full_name, address, city, country, latitude, longitude, phone
 *
 * Writes to whichever of personal_profiles/business_profiles actually has
 * a row for this user (see profile/me.php's docblock for why account_type
 * alone doesn't tell you that). Business accounts should still generally
 * use business/profile_update.php (it also handles category, logo, and
 * "full_name" doesn't really apply there) - this endpoint exists mainly so
 * personal accounts AND admin accounts (which are usually promoted
 * personal accounts) have a working profile editor.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$pdo = Database::connect();

// Determine which profile table this user actually has a row in.
$stmt = $pdo->prepare('SELECT 1 FROM personal_profiles WHERE user_id = ?');
$stmt->execute([$userId]);
$isPersonalShape = (bool) $stmt->fetchColumn();

$table = $isPersonalShape ? 'personal_profiles' : 'business_profiles';
$nameColumn = $isPersonalShape ? 'full_name' : 'business_name';

$set = [];
$params = [];

if (array_key_exists('full_name', $input)) {
    $set[] = "$nameColumn = ?";
    $params[] = trim($input['full_name']);
}
foreach (['address' => 'address', 'city' => 'city', 'country' => 'country'] as $key => $column) {
    if (array_key_exists($key, $input)) {
        $set[] = "$column = ?";
        $params[] = trim($input[$key]);
    }
}

foreach (['latitude' => [-90, 90], 'longitude' => [-180, 180]] as $key => [$min, $max]) {
    if (!array_key_exists($key, $input)) {
        continue;
    }
    $raw = trim((string) $input[$key]);
    if ($raw === '') {
        $set[] = "$key = NULL";
        continue;
    }
    if (!is_numeric($raw) || $raw < $min || $raw > $max) {
        send_error(ucfirst($key) . " must be a number between $min and $max.", 422);
    }
    $set[] = "$key = ?";
    $params[] = (float) $raw;
}

if ($set) {
    $params[] = $userId;
    $stmt = $pdo->prepare("UPDATE $table SET " . implode(', ', $set) . ' WHERE user_id = ?');
    $stmt->execute($params);
}

if (array_key_exists('phone', $input)) {
    $stmt = $pdo->prepare('UPDATE users SET phone = ? WHERE id = ?');
    $stmt->execute([trim($input['phone']), $userId]);
}

send_json(true, 'Profile updated.');
