<?php
session_start();
header('Content-Type: application/json');
if (!defined('BASE_PATH')) define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/database/connection.php';

try {
  $db = Database::getInstance();
  $pdo = $db->getConnection();
  $clientId = isset($_SESSION['client_id']) ? (int)$_SESSION['client_id'] : 0;
  $accNum = trim($_GET['account_number'] ?? '');
  $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
  ) 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 $__) {}
  if ($clientId > 0) {
    $sel = $pdo->prepare("SELECT id, method, identifier, amount, currency, status, payment_method, channel, source, created_at, updated_at FROM payment_attempts WHERE client_id = ? ORDER BY id DESC LIMIT 100");
    $sel->execute([$clientId]);
  } else if ($accNum !== '') {
    $sel = $pdo->prepare("SELECT id, method, identifier, amount, currency, status, payment_method, channel, source, created_at, updated_at FROM payment_attempts WHERE account_number = ? ORDER BY id DESC LIMIT 100");
    $sel->execute([$accNum]);
  } else {
    $sel = $pdo->query("SELECT id, method, identifier, amount, currency, status, payment_method, channel, source, created_at, updated_at FROM payment_attempts ORDER BY id DESC LIMIT 50");
  }
  $rows = $sel->fetchAll(PDO::FETCH_ASSOC);
  echo json_encode(['success' => true, 'attempts' => $rows]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
