<?php
/**
 * POST /api/business/profile_update.php
 * multipart/form-data fields (all optional — send only what changed):
 *   business_name, category, contact_person, address, city, country,
 *   latitude, longitude, phone, logo (file)
 */

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

only_post_allowed();
$userId = require_login();
require_role(['business']);

$pdo = Database::connect();

$fieldMap = [
    'business_name'   => 'business_name',
    'category'        => 'category',
    'contact_person'  => 'contact_person',
    'address'         => 'address',
    'city'            => 'city',
    'country'         => 'country',
];

$set = [];
$params = [];
foreach ($fieldMap as $key => $column) {
    if (array_key_exists($key, $_POST)) {
        $set[] = "$column = ?";
        $params[] = trim($_POST[$key]);
    }
}

// Latitude/longitude need their own handling: empty string must become
// NULL (a DECIMAL column can't store ''), and values must be validated
// as real coordinates before trusting them.
foreach (['latitude' => [-90, 90], 'longitude' => [-180, 180]] as $key => [$min, $max]) {
    if (!array_key_exists($key, $_POST)) {
        continue;
    }
    $raw = trim($_POST[$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 (!empty($_FILES['logo']) && $_FILES['logo']['error'] !== UPLOAD_ERR_NO_FILE) {
    $result = save_uploaded_image($_FILES['logo'], 'business-logos');
    if (!$result['ok']) {
        send_error($result['error'], 422);
    }
    $set[] = 'logo_path = ?';
    $params[] = $result['path'];
}

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

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

send_json(true, 'Business profile updated.');
