<?php
/**
 * POST /api/profile/update
 *
 * Updates name, phone, country, company_name.
 * Email and password are NOT changeable here (separate flows).
 */

declare(strict_types=1);
require_once dirname(__DIR__, 2) . '/config/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonError('Method not allowed', 405);

$user = Auth::apiRequireLogin();
$pid  = (int)$user['publisher_id'];
Csrf::validate();

$name    = Validator::clean((string)($_POST['name'] ?? ''), 120);
$phone   = Validator::clean((string)($_POST['phone'] ?? ''), 20);
$country = Validator::clean((string)($_POST['country'] ?? ''), 80);
$cc      = Validator::clean((string)($_POST['country_code'] ?? ''), 5);
$company = Validator::clean((string)($_POST['company_name'] ?? ''), 150);

if (!Validator::name($name)) jsonError('Please enter a valid name.');
if ($phone !== '' && !Validator::phone($phone)) jsonError('Please enter a valid phone number.');

$pdo = db();
$pdo->prepare("
    UPDATE publisher_user
    SET name = ?, phone = ?, country = ?, country_code = ?, company_name = ?
    WHERE id = ?
")->execute([
    $name,
    $phone !== '' ? $phone : null,
    $country !== '' ? $country : 'India',
    $cc !== '' ? $cc : '+91',
    $company !== '' ? $company : null,
    $pid,
]);

Logger::audit($pid, 'profile_updated');

jsonSuccess('Profile updated successfully.');
