<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/payments.php';
header('Content-Type: application/json');
start_session();
$u = $_SESSION['user'] ?? null;
if (!$u) { http_response_code(401); echo json_encode(['error'=>'unauthorized']); exit; }
$uid = (int)$u['id'];

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method === 'POST') {
  ensure_csrf();
  $action = $_POST['action'] ?? '';
  if ($action === 'create_intent') {
    $appId = (int)($_POST['application_id'] ?? 0);
    $amt = (float)($_POST['amount'] ?? 0);
    // Method is ignored, always bank
    // Verify app ownership
    $chk = $pdo->prepare("SELECT id FROM applications WHERE id=? AND user_id=?"); $chk->execute([$appId,$uid]); if(!$chk->fetch()){ echo json_encode(['error'=>'not_found']); exit; }
    $res = create_payment_intent($pdo, $uid, $appId, $amt);
    echo json_encode($res); exit;
  }
  if ($action === 'confirm') {
    $intent = (int)($_POST['intent_id'] ?? 0);
    $ref = sanitize_str($_POST['reference'] ?? ''); // User provided reference
    
    $receiptPath = null;
    if (!empty($_FILES['receipt']['tmp_name']) && $_FILES['receipt']['error'] === UPLOAD_ERR_OK) {
        $dir = __DIR__ . '/../uploads/receipts/';
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $ext = pathinfo($_FILES['receipt']['name'], PATHINFO_EXTENSION);
        $filename = 'receipt_' . $intent . '_' . time() . '.' . $ext;
        if (move_uploaded_file($_FILES['receipt']['tmp_name'], $dir . $filename)) {
            $receiptPath = url('uploads/receipts/' . $filename);
        }
    }

    $res = confirm_payment_intent($pdo, $intent, $uid, $ref, $receiptPath);
    echo json_encode($res); exit;
  }

}
if ($method === 'GET') {
  if (($_GET['export'] ?? '') === 'csv') {
    $rows = list_user_payments($pdo, $uid, $_GET['status'] ?? null, $_GET['method'] ?? null);
    $csv = export_payments_csv($rows);
    header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="payments.csv"');
    echo $csv; exit;
  }
  $rows = list_user_payments($pdo, $uid, $_GET['status'] ?? null, $_GET['method'] ?? null);
  echo json_encode(['payments'=>$rows]); exit;
}
http_response_code(405); echo json_encode(['error'=>'unsupported']);
