<?php
/**
 * GET /api/profile/get
 *
 * Returns full profile + summary stats for the logged-in publisher.
 */

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

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

$pdo = db();
$stmt = $pdo->prepare("
    SELECT id, uuid, name, email, phone, country_code, country, profile_pic,
           company_name, credits, email_verified, phone_verified,
           last_login_at, created_at
    FROM publisher_user
    WHERE id = ? LIMIT 1
");
$stmt->execute([$pid]);
$p = $stmt->fetch();

if (!$p) jsonError('Profile not found.', 404);

// Quick stats
$stats = $pdo->prepare("
    SELECT
      SUM(CASE WHEN status_admin > 0 THEN 1 ELSE 0 END) AS total_campaigns,
      SUM(CASE WHEN status_admin IN (2, 4, 6) THEN 1 ELSE 0 END) AS active_campaigns,
      SUM(CASE WHEN status_admin = 7 THEN 1 ELSE 0 END) AS completed_campaigns
    FROM pub_purchase_history
    WHERE publisher_id = ?
");
$stats->execute([$pid]);
$st = $stats->fetch() ?: [];

$initials = strtoupper(mb_substr($p['name'], 0, 1));

jsonSuccess('OK', [
    'profile' => [
        'id'             => (int)$p['id'],
        'uuid'           => $p['uuid'],
        'name'           => $p['name'],
        'email'          => $p['email'],
        'phone'          => $p['phone'],
        'country_code'   => $p['country_code'],
        'country'        => $p['country'],
        'profile_pic'    => $p['profile_pic'],
        'initials'       => $initials,
        'company_name'   => $p['company_name'],
        'credits'        => (float)$p['credits'],
        'email_verified' => (bool)$p['email_verified'],
        'phone_verified' => (bool)$p['phone_verified'],
        'last_login_at'  => $p['last_login_at'],
        'created_at'     => $p['created_at'],
        'member_since'   => date('M Y', strtotime((string)$p['created_at'])),
    ],
    'stats' => [
        'total_campaigns'     => (int)($st['total_campaigns'] ?? 0),
        'active_campaigns'    => (int)($st['active_campaigns'] ?? 0),
        'completed_campaigns' => (int)($st['completed_campaigns'] ?? 0),
    ],
]);
