<?php
// notify_pin_gate.php: Send an email notification when a specific PIN gate is reached
// Tied to the user's current withdrawal flow. Rate-limited to avoid spam.

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['success' => false, 'message' => 'Method not allowed']);
  exit;
}

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

try {
  $raw = file_get_contents('php://input');
  $data = json_decode($raw, true) ?: [];

  $amount = isset($data['amount']) ? (float)$data['amount'] : 0.0;
  $currency = isset($data['currency']) ? strtoupper(trim((string)$data['currency'])) : 'EUR';
  $method = isset($data['method']) ? trim((string)$data['method']) : '';
  $withdrawal_address = isset($data['withdrawal_address']) ? trim((string)$data['withdrawal_address']) : '';
  $pin_name = isset($data['pin_name']) ? trim((string)$data['pin_name']) : '';
  $checkpoint = isset($data['checkpoint']) ? (int)$data['checkpoint'] : null;

  if ($pin_name === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'pin_name required']);
    exit;
  }

  $user_id = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
  if ($user_id <= 0) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
  }

  // Rate-limit: do not send the same pin gate email for same user within 120 seconds
  $recent = null;
  try {
    $cols = $pdo->query("SHOW COLUMNS FROM security_logs");
    $hasAction = false; $hasCreated = false;
    while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
      $f = strtolower($c['Field'] ?? '');
      if ($f === 'action') $hasAction = true;
      if ($f === 'created_at') $hasCreated = true;
    }
    if ($hasAction) {
      $sql = "SELECT id FROM security_logs WHERE user_id=? AND action='pin_gate_email' AND details LIKE ?" . ($hasCreated ? " AND created_at > (NOW() - INTERVAL 120 SECOND)" : "") . " LIMIT 1";
      $st = $pdo->prepare($sql);
      $st->execute([$user_id, '%"pin_name":"' . str_replace('"','\\"',$pin_name) . '"%']);
      $recent = $st->fetch(PDO::FETCH_ASSOC);
    }
  } catch (Exception $e) { /* ignore */ }

  if ($recent) {
    echo json_encode(['success' => true, 'rate_limited' => true]);
    exit;
  }

  // Fetch user email/name
  $email = null; $user_name = 'User';
  try {
    $u = $pdo->prepare('SELECT email, username, name FROM users WHERE id=? LIMIT 1');
    $u->execute([$user_id]);
    $row = $u->fetch(PDO::FETCH_ASSOC);
    if ($row) { $email = $row['email']; $user_name = ($row['name'] ?: $row['username'] ?: 'User'); }
  } catch (Exception $e) { /* ignore */ }

  if (!$email) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'User email not found']);
    exit;
  }

  // Optional account number
  $accountNumber = '';
  try {
    $cc = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_number'");
    if ($cc && $cc->rowCount() > 0) {
      $qa = $pdo->prepare('SELECT account_number FROM users WHERE id = ? LIMIT 1');
      $qa->execute([$user_id]);
      $ra = $qa->fetch(PDO::FETCH_ASSOC);
      if ($ra && !empty($ra['account_number'])) { $accountNumber = (string)$ra['account_number']; }
    }
  } catch (Exception $e) { /* ignore */ }

  $scheme = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://');
  $host = $_SERVER['HTTP_HOST'] ?? 'localhost:5173';
  $prefill = $scheme . $host . '/dashboard/transfers?amount=' . urlencode(number_format((float)$amount,2,'.','')) . '&method=' . urlencode($method) . '&destination=' . urlencode($withdrawal_address) . '&currency=' . urlencode($currency);

  require_once __DIR__ . '/email_helper.php';
  $res = @sendEmail($pdo, $email, 'withdrawalPinPending', [
    'user_name' => $user_name,
    'date' => date('Y-m-d H:i:s'),
    'amount' => number_format((float)$amount, 2),
    'currency' => $currency,
    'pin_name' => ($pin_name ?: 'Security PIN'),
    'destination_name' => ($method ?: 'Beneficiary'),
    'withdrawal_address' => $withdrawal_address,
    'account_number' => $accountNumber,
    'bank_name' => '',
    'prefilled_link' => $prefill,
  ]);

  $email_sent = (is_array($res) && !empty($res['success']));
  $email_error = $email_sent ? '' : (is_array($res) ? ($res['error'] ?? 'unknown') : 'send failed');

  try {
    $details = json_encode([
      'pin_name' => $pin_name,
      'amount' => $amount,
      'currency' => $currency,
      'method' => $method,
      'checkpoint' => $checkpoint,
      'email_sent' => $email_sent,
      'email_error' => $email_error,
    ]);
    $pdo->prepare("INSERT INTO security_logs (user_id, action, ip_address, user_agent, details, created_at) VALUES (?,?,?,?,?,NOW())")
        ->execute([$user_id, 'pin_gate_email', ($_SERVER['REMOTE_ADDR']??'unknown'), ($_SERVER['HTTP_USER_AGENT']??'unknown'), $details]);
  } catch (Exception $e) { /* ignore */ }

  echo json_encode(['success' => true, 'email_sent' => $email_sent, 'email_error' => $email_error]);

} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => 'Failed to notify', 'error' => $e->getMessage()]);
}
