<?php
// create_admin_dev.php: Dev-only endpoint to create an admin at any time
// Security: restricted to local environment and localhost/127.0.0.1 requests.
// Usage: POST JSON { "username":"vizadmin","email":"admin@vizventuregroup.com","name":"Viz 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__ . '/includes/Env.php';
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 {
  // Restrict to local environment and localhost remote
  $env = TonEnv::get('ENVIRONMENT', 'local');
  $remote = $_SERVER['REMOTE_ADDR'] ?? '';
  if (!in_array($remote, ['127.0.0.1', '::1']) || strtolower($env) !== 'local') {
    respond(false, [ 'error' => 'Forbidden (dev only)' ], 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);
  }

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

  // Ensure admins table exists minimal
  $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");

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

  // Add admins.password if missing
  if (!isset($adminCols['password'])) {
    try {
      $pdo->exec("ALTER TABLE admins ADD COLUMN password VARCHAR(255) NULL AFTER email");
      $adminCols['password'] = true;
    } catch (Exception $e) {}
  }
  // Add admins.user_id if users table exists and column missing
  if (!isset($adminCols['user_id']) && !empty($userCols)) {
    try {
      $pdo->exec("ALTER TABLE admins ADD COLUMN user_id INT NULL AFTER id");
      $adminCols['user_id'] = true;
    } catch (Exception $e) {}
  }

  // 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");
    foreach ($pdo->query('SHOW COLUMNS FROM users') as $c) { $userCols[$c['Field']] = true; }
  }

  // Check existing by username/email in admins
  $exists = $pdo->prepare('SELECT id FROM admins WHERE username = ? OR email = ? LIMIT 1');
  $exists->execute([$username, $email]);
  if ($exists->fetch()) {
    respond(false, [ 'error' => 'Admin with this username or email already exists' ], 409);
  }

  $hash = password_hash($password, PASSWORD_BCRYPT, [ 'cost' => 10 ]);

  // Insert user (optional but helpful for relations)
  $uCols = ['name','username','email','password'];
  $uVals = [$name, $username, $email, $hash];
  if (isset($userCols['is_admin'])) { $uCols[] = 'is_admin'; $uVals[] = 1; }
  if (isset($userCols['status'])) { $uCols[] = 'status'; $uVals[] = 'active'; }
  $stmt = $pdo->prepare('INSERT INTO users (' . implode(',', $uCols) . ') VALUES (' . implode(',', array_fill(0, count($uCols), '?')) . ')');
  $stmt->execute($uVals);
  $userId = (int)$pdo->lastInsertId();

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

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