<?php
// Admin: Approve user application
header('Content-Type: application/json');
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireAdmin(true);
require_once __DIR__ . '/db.php';

try {
  $input = json_decode(file_get_contents('php://input'), true) ?: [];
  $applicationId = isset($input['application_id']) ? (int)$input['application_id'] : 0;
  $userId = isset($input['user_id']) ? (int)$input['user_id'] : 0;
  $accountNumber = isset($input['account_number']) ? trim((string)$input['account_number']) : '';
  $startingBalance = isset($input['starting_balance']) ? (float)$input['starting_balance'] : null;
  $adminNotes = isset($input['admin_notes']) ? trim((string)$input['admin_notes']) : null;
  $accountCurrency = isset($input['account_currency']) ? strtoupper(trim((string)$input['account_currency'])) : 'EUR';
  if ($accountCurrency === '') { $accountCurrency = 'EUR'; }
  $accountType = isset($input['account_type']) ? trim((string)$input['account_type']) : null;

  if ($applicationId <= 0 && $userId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing application_id or user_id']);
    exit;
  }

  // Find application and user
  if ($applicationId > 0) {
    $stmt = $pdo->prepare("SELECT a.*, u.username, u.email, u.name, u.account_number FROM user_applications a JOIN users u ON a.user_id=u.id WHERE a.id=? LIMIT 1");
    $stmt->execute([$applicationId]);
  } else {
    $stmt = $pdo->prepare("SELECT a.*, u.username, u.email, u.name, u.account_number FROM user_applications a JOIN users u ON a.user_id=u.id WHERE a.user_id=? ORDER BY a.created_at DESC LIMIT 1");
    $stmt->execute([$userId]);
  }
  $app = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$app) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Application not found']);
    exit;
  }

  $userId = (int)$app['user_id'];

  $pdo->beginTransaction();

  // Ensure unique account number if provided or generate if missing
  $hasAccountNumberCol = false;
  try {
    $col = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_number'");
    $hasAccountNumberCol = $col && $col->rowCount() > 0;
  } catch (Exception $e) { $hasAccountNumberCol = false; }

  if ($hasAccountNumberCol) {
    if ($accountNumber === '' || strlen($accountNumber) < 6) {
      // Generate unique 12-digit
      $tries = 0; $generated = null;
      while ($tries++ < 8) {
        $candidate = strval(random_int(100000000000, 999999999999));
        $check = $pdo->prepare('SELECT id FROM users WHERE account_number=? LIMIT 1');
        $check->execute([$candidate]);
        if (!$check->fetch()) { $generated = $candidate; break; }
      }
      $accountNumber = $generated ?: (string)time();
    } else {
      // Ensure provided is unique
      $check = $pdo->prepare('SELECT id FROM users WHERE account_number=? AND id<>? LIMIT 1');
      $check->execute([$accountNumber, $userId]);
      if ($check->fetch()) {
        throw new Exception('Account number already in use');
      }
    }
  }

  // Update users table fields
  $sets = [];
  $params = [];
  if ($hasAccountNumberCol) { $sets[] = 'account_number=?'; $params[] = $accountNumber; }

  // Optional balance column
  $hasBalanceCol = false;
  try { $c=$pdo->query("SHOW COLUMNS FROM users LIKE 'balance'"); $hasBalanceCol = $c && $c->rowCount()>0; } catch (Exception $e) { $hasBalanceCol=false; }
  if ($hasBalanceCol && $startingBalance !== null) { $sets[] = 'balance=?'; $params[] = $startingBalance; }

  // Optional status/is_verified/kycStatus + profile_picture and account meta
  $hasIsVerified=false; $hasStatus=false; $hasKyc=false;
  $hasUserCurrency=false; $hasUserAccountType=false; $hasProfilePicture=false;
  try {
    $c=$pdo->query("SHOW COLUMNS FROM users");
    while($row=$c->fetch(PDO::FETCH_ASSOC)){
      $f=strtolower($row['Field']);
      if($f==='is_verified') $hasIsVerified=true;
      if($f==='status') $hasStatus=true;
      if($f==='kycstatus') $hasKyc=true;
      if($f==='account_currency') $hasUserCurrency=true;
      if($f==='account_type') $hasUserAccountType=true;
      if($f==='profile_picture') $hasProfilePicture=true;
    }
  } catch(Exception $e){}
  if ($hasIsVerified) { $sets[] = 'is_verified=1'; }
  if ($hasStatus) { $sets[] = "status='active'"; }
  if ($hasKyc) { $sets[] = "kycStatus='approved'"; }
  if ($hasUserCurrency) { $sets[] = 'account_currency=?'; $params[] = $accountCurrency; }
  if ($hasUserAccountType && $accountType !== null && $accountType !== '') { $sets[] = 'account_type=?'; $params[] = $accountType; }

  // If possible, propagate uploaded profile photo to users.profile_picture at approval time
  if ($hasProfilePicture) {
    try {
      $pf = $pdo->prepare("SELECT account_photo_path FROM user_profiles WHERE user_id=? ORDER BY id DESC LIMIT 1");
      $pf->execute([$userId]);
      $ph = $pf->fetch(PDO::FETCH_ASSOC);
      $pic = $ph && !empty($ph['account_photo_path']) ? trim((string)$ph['account_photo_path']) : '';
      if ($pic !== '') { $sets[] = 'profile_picture=?'; $params[] = $pic; }
    } catch (Exception $e) { /* ignore */ }
  }

  if (!empty($sets)) {
    $params[] = $userId;
    $sql = 'UPDATE users SET ' . implode(', ', $sets) . ' WHERE id=?';
    $upd = $pdo->prepare($sql);
    $upd->execute($params);
  }

  // Update user_profiles if available (for account_type or currency)
  $hasProfiles = false; $pfCols = [];
  try { $t=$pdo->query("SHOW TABLES LIKE 'user_profiles'"); $hasProfiles = $t && $t->rowCount()>0; } catch (Exception $e) { $hasProfiles=false; }
  if ($hasProfiles) {
    try {
      $colStmt = $pdo->query("SHOW COLUMNS FROM user_profiles");
      while ($cc = $colStmt->fetch(PDO::FETCH_ASSOC)) { $pfCols[strtolower($cc['Field'])] = true; }
      // ensure row exists
      $chk = $pdo->prepare('SELECT id FROM user_profiles WHERE user_id=? LIMIT 1');
      $chk->execute([$userId]);
      $exists = $chk->fetch(PDO::FETCH_ASSOC);
      $pfSets = [];$pfParams=[];
      if (!empty($pfCols['account_type']) && $accountType !== null && $accountType !== '') { $pfSets[] = 'account_type=?'; $pfParams[] = $accountType; }
      if (!empty($pfCols['account_currency'])) { $pfSets[] = 'account_currency=?'; $pfParams[] = $accountCurrency; }
      if (!empty($pfSets)) {
        if ($exists) {
          $pfParams[] = $userId;
          $pfSql = 'UPDATE user_profiles SET '.implode(', ', $pfSets).' WHERE user_id=?';
          $pdo->prepare($pfSql)->execute($pfParams);
        } else {
          // Insert minimal row
          $fields = ['user_id']; $place = ['?']; $vals = [$userId];
          if (!empty($pfCols['account_type']) && $accountType !== null && $accountType !== '') { $fields[]='account_type'; $place[]='?'; $vals[]=$accountType; }
          if (!empty($pfCols['account_currency'])) { $fields[]='account_currency'; $place[]='?'; $vals[]=$accountCurrency; }
          $pfIns = 'INSERT INTO user_profiles ('.implode(',',$fields).') VALUES ('.implode(',',$place).')';
          $pdo->prepare($pfIns)->execute($vals);
        }
      }
    } catch (Exception $e) { /* ignore */ }
  }

  // Update application status (include reviewed_by if column exists)
  $hasReviewedBy = false;
  try {
    $cols = $pdo->query("SHOW COLUMNS FROM user_applications LIKE 'reviewed_by'");
    $hasReviewedBy = $cols && $cols->rowCount() > 0;
  } catch (Exception $e) { $hasReviewedBy = false; }
  if ($hasReviewedBy) {
    $adminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : 1;
    $setApp = $pdo->prepare("UPDATE user_applications SET status='approved', reviewed_at=NOW(), reviewed_by=?, admin_notes = COALESCE(?, admin_notes) WHERE id=?");
    $setApp->execute([$adminId, $adminNotes, (int)$app['id']]);
  } else {
    $setApp = $pdo->prepare("UPDATE user_applications SET status='approved', reviewed_at=NOW(), admin_notes = COALESCE(?, admin_notes) WHERE id=?");
    $setApp->execute([$adminNotes, (int)$app['id']]);
  }

  $pdo->commit();

  // Send email notification (best-effort) via template
  try {
    require_once __DIR__ . '/email_helper.php';
    $base = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? '');
    $loginUrl = rtrim($base, '/') . '/login';
    // Resolve BIC/SWIFT from settings or environment
    $bicSwift = '';
    try {
      $tbl = $pdo->query("SHOW TABLES LIKE 'settings'");
      if ($tbl && $tbl->rowCount() > 0) {
        $q = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('bic_swift','bank_bic','swift_bic','bic')");
        while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
          $v = trim((string)($r['setting_value'] ?? ''));
          if ($v !== '') { $bicSwift = $v; break; }
        }
      }
    } catch (Exception $ie) { /* ignore */ }
    if ($bicSwift === '' && class_exists('TonEnv')) {
      $bicSwift = (string)(TonEnv::get('BIC_SWIFT', TonEnv::get('BANK_BIC_SWIFT', '')));
    }
    if ($bicSwift === '') { $bicSwift = 'FDFRFRPP'; }
    @sendEmail($pdo, $app['email'], 'applicationApproved', [
      'user_name' => ($app['name'] ?: $app['username']),
      'username' => $app['username'],
      'account_number' => ($accountNumber ?: ($app['account_number'] ?? '')),
      'login_link' => $loginUrl,
      'bic_swift' => $bicSwift,
    ]);
  } catch (Exception $e) { /* ignore */ }

  echo json_encode(['success' => true, 'message' => 'Application approved', 'account_number' => $accountNumber]);
} catch (Throwable $e) {
  if ($pdo && $pdo->inTransaction()) { $pdo->rollBack(); }
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
