<?php
// Admin: Resend application status email to user
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';
require_once __DIR__ . '/email_helper.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;

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

  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;
  }

  $status = strtolower($app['status'] ?? 'submitted');

  $to = $app['email'];
  $username = $app['username'];
  $displayName = $app['name'] ?: $username;

  $scheme = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://');
  $host = $_SERVER['HTTP_HOST'] ?? 'localhost:5173';
  $loginLink = $scheme . $host . '/login';

  $res = null;
  if ($status === 'approved') {
    $acct = $app['account_number'] ?: '';
    $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', '')));
    }
    $res = @sendEmail($pdo, $to, 'applicationApproved', [
      'user_name' => $displayName,
      'username' => $username,
      'account_number' => $acct,
      'login_link' => $loginLink,
      'bic_swift' => $bicSwift,
    ]);
  } elseif ($status === 'rejected') {
    $reason = trim((string)($app['admin_notes'] ?? ''));
    $res = @sendEmail($pdo, $to, 'kycRejected', [
      'user_name' => $displayName,
      'reason' => ($reason !== '' ? $reason : 'Not specified'),
    ]);
  } else {
    $res = @sendEmail($pdo, $to, 'applicationSubmitted', [
      'user_name' => $displayName,
      'username' => $username,
      'email' => $to,
    ]);
  }

  $ok = (is_array($res) && !empty($res['success']));
  if (!$ok) {
    $mailerPath = __DIR__ . '/includes/Mailer.php';
    if (file_exists($mailerPath)) {
      require_once $mailerPath;
      if (class_exists('Mailer')) {
        $mailer = new Mailer();
        if ($status === 'approved') {
          $acct = $app['account_number'] ?: '';
          $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) { }
          if ($bicSwift === '' && class_exists('TonEnv')) { $bicSwift = (string)(TonEnv::get('BIC_SWIFT', TonEnv::get('BANK_BIC_SWIFT', ''))); }
          $subject = 'Application Approved';
          $html = '<h2>Application Approved</h2>' .
                  '<p>Dear ' . htmlspecialchars($displayName) . ',</p>' .
                  '<p>Your banking application has been <strong>approved</strong>.</p>' .
                  '<p><strong>Username:</strong> ' . htmlspecialchars($username) . '<br/>' .
                  '<strong>Account Number:</strong> ' . htmlspecialchars($acct) . '<br/>' .
                  '<strong>BIC/SWIFT:</strong> ' . htmlspecialchars($bicSwift) . '</p>';
          $text = "Application Approved\n\nUsername: $username\nAccount Number: $acct\nBIC/SWIFT: $bicSwift";
        } elseif ($status === 'rejected') {
          $reason = trim((string)($app['admin_notes'] ?? ''));
          $subject = 'Your Application Status: Declined';
          $html = '<h2>Application Declined</h2><p>Dear ' . htmlspecialchars($displayName) . ',</p>' .
                  '<p>Your banking application has been <strong>declined</strong>.</p>' .
                  ($reason ? '<p>Reason: ' . htmlspecialchars($reason) . '</p>' : '');
          $text = "Application Declined" . ($reason ? "\nReason: $reason" : '');
        } else {
          $subject = 'Your Application Status: Submitted';
          $html = '<h2>Application Submitted</h2><p>Dear ' . htmlspecialchars($displayName) . ',</p>' .
                  '<p>Your banking application has been <strong>submitted</strong>. A bank representative will contact you to complete onboarding.</p>' .
                  '<p>Status: <strong>Submitted</strong></p>';
          $text = "Application Submitted\nStatus: Submitted";
        }
        @$mailer->sendEmail($to, $subject, $html, $text);
      }
    }
  }

  echo json_encode(['success' => true, 'message' => 'Email resent']);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
