<?php
// create_initial_admin.php: One-time bootstrap to create the first admin user
// Security: Only allowed when there are ZERO rows in admins table.
// Usage: POST JSON { "username": "admin", "email": "admin@example.com", "name": "Admin", "password": "StrongPass123!" }

header('Content-Type: application/json');
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) { header('Access-Control-Allow-Origin: ' . $origin); }
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

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

function respond($ok, $payload = [], $code = 200) {
  http_response_code($code);
  echo json_encode(array_merge([ 'success' => $ok ], $payload));
  exit;
}

try {
  $pdo = Database::getInstance()->getConnection();

  // Ensure admins table exists (best-effort minimal columns)
  $pdo->exec("CREATE TABLE IF NOT EXISTS admins (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL UNIQUE,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE,
    status VARCHAR(20) DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

  $count = (int)$pdo->query("SELECT COUNT(*) FROM admins")->fetchColumn();
  if ($count > 0) {
    respond(false, [ 'error' => 'Admin already exists. This endpoint is disabled.' ], 403);
  }

  if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(false, [ 'error' => 'Method not allowed' ], 405);
  }

  $data = json_decode(file_get_contents('php://input'), true);
  if (!is_array($data)) { respond(false, [ 'error' => 'Invalid JSON body' ], 400); }

  $username = trim((string)($data['username'] ?? ''));
  $email = trim((string)($data['email'] ?? ''));
  $name = trim((string)($data['name'] ?? ''));
  $password = (string)($data['password'] ?? '');

  if ($username === '' || $email === '' || $name === '' || $password === '') {
    respond(false, [ 'error' => 'Missing required fields' ], 400);
  }
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    respond(false, [ 'error' => 'Invalid email format' ], 400);
  }

  // Detect existing columns in users/admins for compatibility
  $userCols = [];
  try { foreach ($pdo->query('SHOW COLUMNS FROM users') as $c) { $userCols[$c['Field']] = true; } } catch (Exception $e) {}
  $adminCols = [];
  try { foreach ($pdo->query('SHOW COLUMNS FROM admins') as $c) { $adminCols[$c['Field']] = true; } } catch (Exception $e) {}

  // Add password column to admins if missing (required for login verification)
  if (!isset($adminCols['password'])) {
    try {
      $pdo->exec("ALTER TABLE admins ADD COLUMN password VARCHAR(255) NULL AFTER email");
      // re-detect
      $adminCols = [];
      foreach ($pdo->query('SHOW COLUMNS FROM admins') as $c) { $adminCols[$c['Field']] = true; }
    } catch (Exception $e) { /* ignore if cannot alter */ }
  }

  // Ensure users table exists minimally if missing
  if (empty($userCols)) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(100) NOT NULL,
      username VARCHAR(100) NOT NULL UNIQUE,
      email VARCHAR(150) NOT NULL UNIQUE,
      password VARCHAR(255) NOT NULL,
      status VARCHAR(20) DEFAULT 'active',
      is_admin TINYINT(1) DEFAULT 0,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    // re-detect
    foreach ($pdo->query('SHOW COLUMNS FROM users') as $c) { $userCols[$c['Field']] = true; }
  }

  // Insert user dynamically based on available columns
  $hash = password_hash($password, PASSWORD_BCRYPT, [ 'cost' => 10 ]);
  $uCols = ['name','username','email','password'];
  $uVals = [$name, $username, $email, $hash];
  $extraMap = [
    'email_verified' => 1,
    'email_verification_token' => '',
    'status' => 'active',
    'kycStatus' => 'approved',
    'balance' => 0,
    'total_earned' => 0,
    'is_admin' => 1,
  ];
  foreach ($extraMap as $k => $v) { if (isset($userCols[$k])) { $uCols[] = $k; $uVals[] = $v; } }
  $placeholders = implode(',', array_fill(0, count($uCols), '?'));
  $stmt = $pdo->prepare('INSERT INTO users (' . implode(',', $uCols) . ') VALUES (' . $placeholders . ')');
  $stmt->execute($uVals);
  $userId = (int)$pdo->lastInsertId();

  // Insert admin entry dynamically
  $aCols = ['username','name','email'];
  $aVals = [$username, $name, $email];
  if (isset($adminCols['user_id'])) { $aCols[] = 'user_id'; $aVals[] = $userId; }
  if (isset($adminCols['password'])) { $aCols[] = 'password'; $aVals[] = $hash; }
  if (isset($adminCols['is_admin'])) { $aCols[] = 'is_admin'; $aVals[] = 1; }
  if (isset($adminCols['status'])) { $aCols[] = 'status'; $aVals[] = 'active'; }
  $placeA = implode(',', array_fill(0, count($aCols), '?'));
  $stmt = $pdo->prepare('INSERT INTO admins (' . implode(',', $aCols) . ') VALUES (' . $placeA . ')');
  $stmt->execute($aVals);

  respond(true, [ 'message' => 'Initial admin created', 'admin' => [ 'id' => $userId, 'username' => $username, 'email' => $email, 'name' => $name ] ]);
} catch (Exception $e) {
  respond(false, [ 'error' => 'Server error: ' . $e->getMessage() ], 500);
}
