<?php
// =============================================================
//  GET  /api/v1/profile/me   — same payload as auth/me.php (kept here too
//                              so /profile/* is a self-contained module).
//  PUT  /api/v1/profile/me   — update self-editable fields. Deliberately
//                              narrow: phone number only. Email, names,
//                              and role/scope fields are admin-managed
//                              (app/edit_user.php etc.) — a self-service
//                              endpoint that let a student rewrite their
//                              own email would break the very account-
//                              lookup uniqueness account_helpers.php's
//                              checkGlobalDuplicate() exists to protect.
//
//  Body (PUT): { "phone": "0244000000" }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../auth/_helpers.php';
require_once __DIR__ . '/../../../include/account_helpers.php';

$account = api_authenticate();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    Api::success(['user' => api_build_profile($conn, $account)]);
}

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $body  = Api::body();
    if (!array_key_exists('phone', $body)) {
        Api::error(422, 'ValidationError', 'phone is required');
    }
    $phone = trim((string)$body['phone']);
    if ($phone === '') {
        Api::error(422, 'ValidationError', 'phone cannot be empty');
    }

    $dup = checkGlobalDuplicate($conn, 'phone', $phone, $account->getTable(), $account->getId());
    if ($dup) {
        Api::error(409, 'DuplicatePhone', 'This phone number is already in use by another account.');
    }

    $table = $account->getTable();
    $id    = $account->getId();
    $stmt  = $conn->prepare("UPDATE `{$table}` SET phone = ? WHERE id = ?");
    $stmt->bind_param('si', $phone, $id);
    $stmt->execute();
    $stmt->close();

    $refreshed = $account_repo->findById($table, $id);
    Api::success(['user' => api_build_profile($conn, $refreshed)]);
}

Api::error(405, 'MethodNotAllowed', 'Use GET or PUT');
