<?php
// Admin-only endpoint to backfill users.profile_picture from user_profiles.account_photo_path
header('Content-Type: application/json');
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (!empty($allowed_origin)) { header("Access-Control-Allow-Origin: $allowed_origin"); }
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

if (!defined('TONSUI_LOADED')) { define('TONSUI_LOADED', true); }
require_once __DIR__ . '/session_init.php';
requireAdmin(true);
require_once __DIR__ . '/db.php';

function respond($ok, $msg, $data = null, $code = 200) {
  http_response_code($code);
  $res = ['success' => $ok, 'message' => $msg];
  if ($data !== null) { $res['data'] = $data; }
  echo json_encode($res);
  exit;
}

try {
  // Check needed schema elements
  $hasUsersPic = false; $hasProfilesTbl = false;
  try {
    $c = $pdo->query("SHOW COLUMNS FROM users LIKE 'profile_picture'");
    $hasUsersPic = $c && $c->rowCount() > 0;
  } catch (Throwable $e) { $hasUsersPic = false; }
  try {
    $t = $pdo->query("SHOW TABLES LIKE 'user_profiles'");
    $hasProfilesTbl = $t && $t->rowCount() > 0;
  } catch (Throwable $e) { $hasProfilesTbl = false; }

  if (!$hasUsersPic) {
    respond(false, "users.profile_picture column not found", null, 400);
  }
  if (!$hasProfilesTbl) {
    respond(false, "user_profiles table not found", null, 400);
  }

  $dryRun = isset($_GET['dry_run']) || (isset($_POST['dry_run']) && $_POST['dry_run']);

  // Count distinct users with a non-empty latest profile photo and empty user picture
  $countSql = "SELECT COUNT(*) AS cnt FROM (
      SELECT u.id
      FROM users u
      JOIN (
        SELECT x.user_id, x.account_photo_path
        FROM user_profiles x
        JOIN (
          SELECT user_id, MAX(id) AS max_id
          FROM user_profiles
          WHERE account_photo_path IS NOT NULL AND account_photo_path <> ''
          GROUP BY user_id
        ) m ON m.user_id = x.user_id AND m.max_id = x.id
      ) p ON p.user_id = u.id
      WHERE (u.profile_picture IS NULL OR u.profile_picture = '' OR u.profile_picture = '0')
    ) t";
  $cntStmt = $pdo->query($countSql);
  $countRow = $cntStmt->fetch(PDO::FETCH_ASSOC);
  $toUpdate = (int)($countRow['cnt'] ?? 0);

  if ($dryRun) {
    respond(true, 'Dry run - no updates performed', ['would_update' => $toUpdate]);
  }

  $pdo->beginTransaction();
  $updSql = "UPDATE users u
    JOIN (
      SELECT x.user_id, x.account_photo_path
      FROM user_profiles x
      JOIN (
        SELECT user_id, MAX(id) AS max_id
        FROM user_profiles
        WHERE account_photo_path IS NOT NULL AND account_photo_path <> ''
        GROUP BY user_id
      ) m ON m.user_id = x.user_id AND m.max_id = x.id
    ) p ON p.user_id = u.id
    SET u.profile_picture = p.account_photo_path
    WHERE (u.profile_picture IS NULL OR u.profile_picture = '' OR u.profile_picture = '0')";
  $affected = $pdo->exec($updSql);
  $pdo->commit();

  respond(true, 'Backfill complete', ['updated' => (int)$affected, 'candidates_before' => $toUpdate]);
} catch (Throwable $e) {
  if ($pdo && $pdo->inTransaction()) { $pdo->rollBack(); }
  respond(false, $e->getMessage(), null, 500);
}
