<?php
// Admin: Reject 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;
  $reason = isset($input['reason']) ? trim((string)$input['reason']) : 'Application rejected';

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

  // 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;
    $upd = $pdo->prepare("UPDATE user_applications SET status='rejected', reviewed_at=NOW(), reviewed_by=?, admin_notes = ? WHERE id=?");
    $upd->execute([$adminId, $reason, (int)$app['id']]);
  } else {
    $upd = $pdo->prepare("UPDATE user_applications SET status='rejected', reviewed_at=NOW(), admin_notes = ? WHERE id=?");
    $upd->execute([$reason, (int)$app['id']]);
  }

  // Email user (best-effort)
  try {
    $mailerPath = __DIR__ . '/includes/Mailer.php';
    if (file_exists($mailerPath)) {
      require_once $mailerPath;
      if (class_exists('Mailer')) {
        $mailer = new Mailer();
        $html = '<h2>Application Declined</h2><p>Dear ' . htmlspecialchars($app['name'] ?: $app['username']) . ',</p>' .
                '<p>Your banking application has been <strong>declined</strong>.</p>' .
                '<p>Reason: ' . htmlspecialchars($reason) . '</p>';
        $text = "Application Declined\n\nReason: $reason";
        $mailer->sendEmail($app['email'], 'Your Application Status: Declined', $html, $text);
      }
    }
  } catch (Exception $e) { /* ignore */ }

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