<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'service_providers', 'edit', $pdo);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (
    !$input ||
    empty($input['company_id']) ||
    !isset($input['base_lat']) ||
    !isset($input['base_lng'])
) {
    json_response(false, 'Missing required fields.', [], 400);
}

$company_id = (int)$input['company_id'];
$base_lat   = (float)$input['base_lat'];
$base_lng   = (float)$input['base_lng'];
$radius     = isset($input['coverage_radius_km']) ? (int)$input['coverage_radius_km'] : 25;

/* VALIDATE NUMERIC RANGES */
if ($base_lat < -90 || $base_lat > 90) {
    json_response(false, 'Invalid latitude value.', [], 400);
}

if ($base_lng < -180 || $base_lng > 180) {
    json_response(false, 'Invalid longitude value.', [], 400);
}

if ($radius <= 0 || $radius > 500) {
    json_response(false, 'Invalid coverage radius.', [], 400);
}

/* FETCH COMPANY */
$stmt = $pdo->prepare("
    SELECT id, type, rsp_id
    FROM companies
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$company_id]);
$company = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$company) {
    json_response(false, 'Company not found.', [], 404);
}

/* MUST BE SERVICE PROVIDER */
if ($company['type'] !== 'sp') {
    json_response(false, 'Only service providers can have service profiles.', [], 400);
}

/* TENANT ISOLATION */
if (!empty($user['rsp_id'])) {
    enforce_rsp_isolation($user, (int)$company['rsp_id']);
}

/* UPSERT PROFILE */
$stmt = $pdo->prepare("
    INSERT INTO service_profiles
        (company_id, base_lat, base_lng, coverage_radius_km, penalty_count, created_at)
    VALUES (?, ?, ?, ?, 0, NOW())
    ON DUPLICATE KEY UPDATE
        base_lat = VALUES(base_lat),
        base_lng = VALUES(base_lng),
        coverage_radius_km = VALUES(coverage_radius_km)
");

$stmt->execute([
    $company_id,
    $base_lat,
    $base_lng,
    $radius
]);

/* AUDIT */
log_admin_action(
    $pdo,
    (int)$user['id'],
    'service_providers',
    'edit_profile',
    $company_id
);

/* RESPONSE */
json_response(true, 'SP profile saved.', [
    'company_id' => $company_id,
    'base_lat'   => $base_lat,
    'base_lng'   => $base_lng,
    'coverage_radius_km' => $radius
]);