<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_app_guard.php';
require_once dirname(__DIR__, 2) . '/includes/profile_pairing.php';
app_guard_validate();
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    echo json_encode(['status' => 'erro', 'msg' => 'method_not_allowed'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$newStoredPath = '';
try {
    $db = new PDO('sqlite:' . dirname(__DIR__) . '/db.db', null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    $db->exec('PRAGMA busy_timeout = 30000');
    pp_ensure_schema($db);

    $mac = pp_normalize_mac((string)($_POST['mac'] ?? ''));
    if ($mac === '') throw new RuntimeException('mac_invalid');

    $st = $db->prepare('SELECT * FROM usuarios WHERE mac=? LIMIT 1');
    $st->execute([$mac]);
    $current = $st->fetch(PDO::FETCH_ASSOC);
    if (!$current) throw new RuntimeException('user_not_found');

    $nome = array_key_exists('nome_cliente', $_POST)
        ? trim(preg_replace('/\s+/u', ' ', (string)$_POST['nome_cliente']) ?? '')
        : (string)($current['nome_cliente'] ?? '');
    $nameLength = function_exists('mb_strlen') ? mb_strlen($nome, 'UTF-8') : strlen($nome);
    if ($nameLength > 120) throw new RuntimeException('name_too_long');

    $whatsapp = array_key_exists('whatsapp', $_POST)
        ? (preg_replace('/\D+/', '', (string)$_POST['whatsapp']) ?: '')
        : (preg_replace('/\D+/', '', (string)($current['whatsapp'] ?? '')) ?: '');
    if (strlen($whatsapp) > 20) throw new RuntimeException('whatsapp_invalid');

    $oldPath = (string)($current['profile_image'] ?? '');
    $profilePath = $oldPath;
    $profileMime = (string)($current['profile_image_mime'] ?? '');
    $profileHash = (string)($current['profile_image_hash'] ?? '');
    $profileSize = (int)($current['profile_image_size'] ?? 0);
    $updatedAt = (int)($current['profile_updated_at'] ?? 0);
    $changedImage = false;

    $hasUpload = isset($_FILES['profile_image'])
        && is_array($_FILES['profile_image'])
        && (int)($_FILES['profile_image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;

    if ($hasUpload) {
        $stored = pp_store_image_meta($_FILES['profile_image'], 'api/uploads/profiles', 'profile_' . str_replace(':', '', $mac));
        $newStoredPath = (string)($stored['path'] ?? '');
        if ($newStoredPath === '') throw new RuntimeException('save_error');
        $profilePath = $newStoredPath;
        $profileMime = (string)($stored['mime'] ?? '');
        $profileHash = (string)($stored['sha256'] ?? '');
        $profileSize = (int)($stored['size'] ?? 0);
        $updatedAt = media_monotonic_version($updatedAt);
        $changedImage = true;
    } elseif (((string)($_POST['delete_profile_image'] ?? '')) === '1') {
        $profilePath = '';
        $profileMime = '';
        $profileHash = '';
        $profileSize = 0;
        $updatedAt = media_monotonic_version($updatedAt);
        $changedImage = true;
    }

    $db->beginTransaction();
    $up = $db->prepare('UPDATE usuarios SET nome_cliente=?, whatsapp=?, profile_image=?, profile_updated_at=?, profile_image_mime=?, profile_image_hash=?, profile_image_size=? WHERE mac=?');
    $up->execute([$nome, $whatsapp, $profilePath, $updatedAt, $profileMime, $profileHash, $profileSize, $mac]);
    $verify = $db->prepare('SELECT mac FROM usuarios WHERE mac=? LIMIT 1');
    $verify->execute([$mac]);
    if (!$verify->fetchColumn()) throw new RuntimeException('save_error');
    $db->commit();

    // Só apaga a imagem anterior depois que o banco confirmou a nova referência.
    if ($changedImage && $oldPath !== '' && $oldPath !== $profilePath) {
        pp_remove_uploaded_file($oldPath);
    }
    $newStoredPath = '';

    $read = $db->prepare('SELECT * FROM usuarios WHERE mac=? LIMIT 1');
    $read->execute([$mac]);
    $updated = $read->fetch(PDO::FETCH_ASSOC) ?: [];

    echo json_encode([
        'status' => 'ok',
        'msg' => 'saved',
        'request_id' => trim((string)($_POST['request_id'] ?? '')),
        'data' => array_merge([
            'username' => (string)($updated['username'] ?? ''),
            'nome_cliente' => (string)($updated['nome_cliente'] ?? ''),
            'whatsapp' => (string)($updated['whatsapp'] ?? ''),
            'mac' => (string)($updated['mac'] ?? $mac),
        ], pp_profile_payload($updated)),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    if (isset($db) && $db instanceof PDO && $db->inTransaction()) $db->rollBack();
    if ($newStoredPath !== '') pp_remove_uploaded_file($newStoredPath);
    $message = $e->getMessage() !== '' ? $e->getMessage() : 'save_error';
    $status = in_array($message, ['mac_invalid', 'user_not_found', 'name_too_long', 'whatsapp_invalid'], true) ? 422 : 500;
    http_response_code($status);
    error_log('[profile_update] ' . $message);
    echo json_encode(['status' => 'erro', 'msg' => $message], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
