<?php
/**
 * GET /api/profile/me.php
 * Works for ANY account type - personal, business, or admin.
 *
 * Account type is not the same thing as profile shape: an admin account
 * was always originally created as either personal or business (via
 * self-registration, then promoted), so its real profile data still lives
 * in whichever of personal_profiles/business_profiles was created at
 * signup - never both, and never neither. This looks up whichever one
 * actually has a row, instead of assuming based on account_type (the old
 * version assumed non-personal === business, which 404'd for every admin
 * account that started out personal - the common case).
 */

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

$userId = require_login();
$type = current_account_type();

$pdo = Database::connect();

$stmt = $pdo->prepare('
    SELECT u.email, u.phone,
           COALESCE(pp.full_name, bp.business_name) AS full_name,
           bp.business_name,
           COALESCE(pp.address, bp.address) AS address,
           COALESCE(pp.city, bp.city) AS city,
           COALESCE(pp.country, bp.country) AS country,
           COALESCE(pp.latitude, bp.latitude) AS latitude,
           COALESCE(pp.longitude, bp.longitude) AS longitude,
           (pp.user_id IS NOT NULL) AS has_personal_profile,
           (bp.user_id IS NOT NULL) AS has_business_profile
    FROM users u
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    WHERE u.id = ?
');
$stmt->execute([$userId]);
$profile = $stmt->fetch();

if (!$profile) {
    send_error('Profile not found.', 404);
}

$profile['has_personal_profile'] = (bool) $profile['has_personal_profile'];
$profile['has_business_profile'] = (bool) $profile['has_business_profile'];

send_json(true, 'OK', ['profile' => $profile, 'account_type' => $type]);
