<?php
// Big4pay IPN - Notificación de estado de pagos
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__, 2))); }
header('Content-Type: application/json; charset=utf-8');

try {
    $raw = file_get_contents('php://input');
    $json = json_decode($raw, true);
    if (!$json || !is_array($json)) { $json = $_POST ?: $_GET ?: []; }

    $event = [
        'received_at' => date('c'),
        'identifier' => $json['identifier'] ?? null,
        'status' => $json['status'] ?? ($json['payment_status'] ?? null),
        'transaction_id' => $json['transaction_id'] ?? null,
        'amount' => $json['amount'] ?? null,
        'currency' => $json['currency'] ?? null,
        'raw' => $json,
    ];

    $dir = dirname(__DIR__, 3) . '/tmp';
    if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
    $file = $dir . '/big4pay_ipn.log';
    @file_put_contents($file, json_encode($event) . PHP_EOL, FILE_APPEND | LOCK_EX);

    // Persistir intento y acreditar saldo si fue aprobado
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $pdo->exec("CREATE TABLE IF NOT EXISTS payment_attempts (
      id INT AUTO_INCREMENT PRIMARY KEY,
      client_id INT NULL,
      account_number VARCHAR(64) NULL,
      method VARCHAR(64) NOT NULL,
      identifier VARCHAR(64) NOT NULL,
      amount DECIMAL(18,6) NOT NULL,
      currency VARCHAR(8) NOT NULL,
      status VARCHAR(32) NOT NULL,
      payment_method VARCHAR(64) NULL,
      channel VARCHAR(32) NULL,
      external_transaction_id VARCHAR(128) NULL,
      source VARCHAR(32) NOT NULL,
      redirect_url VARCHAR(255) NULL,
      checkout_url VARCHAR(255) NULL,
      message TEXT NULL,
      raw_json JSON NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME NULL,
      UNIQUE KEY uniq_identifier (identifier)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    try { $pdo->exec("ALTER TABLE payment_attempts ADD COLUMN payment_method VARCHAR(64) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_attempts ADD COLUMN channel VARCHAR(32) NULL"); } catch (Throwable $__) {}

    $identifier = $event['identifier'];
    $status = strtolower($event['status'] ?? '');
    $amountVal = (float)($event['amount'] ?? 0);
    $currency = strtoupper($event['currency'] ?? 'USD');
    $extId = $event['transaction_id'] ?? null;

    if ($identifier) {
      $stmtSel = $pdo->prepare("SELECT id, client_id, account_number FROM payment_attempts WHERE identifier = ? LIMIT 1");
      $stmtSel->execute([$identifier]);
      $row = $stmtSel->fetch();
      if ($row) {
        $pmLabel = $json['payment_method'] ?? ($json['method_label'] ?? ($json['methodName'] ?? ''));
        $channel = strtolower($json['channel'] ?? ($json['category'] ?? ''));
        if (is_array($json['paymentMethod'] ?? null)) { $channel = $channel ?: strtolower($json['paymentMethod']['channel'] ?? ''); }
        if ($channel==='') $channel = null; else if (!in_array($channel,['online','cash'])) $channel = $channel ? 'online' : null;
        $stmtUp = $pdo->prepare("UPDATE payment_attempts SET status = ?, external_transaction_id = ?, payment_method = ?, channel = ?, raw_json = ?, updated_at = NOW() WHERE id = ?");
        $stmtUp->execute([$status ?: 'unknown', $extId, $pmLabel ?: null, $channel, json_encode($json), (int)$row['id']]);
        // Acreditar saldo si aprobado
        if (in_array($status, ['approved','paid','success'])) {
          $clientId = (int)($row['client_id'] ?? 0);
          $accNum = $row['account_number'] ?? '';
          if ($clientId > 0 && $accNum !== '') {
            // Actualizar cuenta del portal
            $stmtAcc = $pdo->prepare("UPDATE client_accounts SET balance = balance + ? WHERE client_id = ? AND account_number = ?");
            $stmtAcc->execute([$amountVal, $clientId, $accNum]);
            // Actualizar cuenta de trading
            $stmtTa = $pdo->prepare("UPDATE trading_accounts SET balance = balance + ?, equity = equity + ?, free_margin = free_margin + ?, updated_at = NOW() WHERE client_id = ? AND account_number = ?");
            $stmtTa->execute([$amountVal, $amountVal, $amountVal, $clientId, $accNum]);
          }
        }
      }
    }

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error IPN: ' . $e->getMessage()]);
}
?>
