<?php
// ============================================================
// backend/api/payments/PaymentController.php
// ============================================================

class PaymentController {

    // POST /payments/verify
    // Used by frontend to verify any Paystack transaction before proceeding
    public function verify(): void {
        $body = $GLOBALS['body'];
        $ref  = trim($body['reference'] ?? '');

        if (!$ref) sendError('Payment reference required', 422);

        $ch = curl_init("https://api.paystack.co/transaction/verify/$ref");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . PAYSTACK_SECRET_KEY,
            ],
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $data = json_decode($response, true);

        if (!$data || !$data['status']) {
            sendError($data['message'] ?? 'Verification failed', 402);
        }

        $tx = $data['data'];
        sendSuccess([
            'reference' => $tx['reference'],
            'status'    => $tx['status'],
            'amount'    => $tx['amount'] / 100,
            'email'     => $tx['customer']['email'],
            'paid_at'   => $tx['paid_at'],
        ], 'Payment verified');
    }
}
