<?php
namespace App\Services;

class PaymentService {
    public function __construct(private \PDO $pdo) {}

    public function createAwaitingProofPayment(int $studentId, ?int $packageId, string $referenceNumber, string $notes = ''): int {
        $amount = 0.0;
        $currency = 'ZAR';
        if ($packageId) {
            $stmt = $this->pdo->prepare("SELECT price, currency FROM packages WHERE id = ? LIMIT 1");
            $stmt->execute([$packageId]);
            if ($package = $stmt->fetch()) {
                $amount = (float)$package['price'];
                $currency = $package['currency'] ?: 'ZAR';
            }
        }
        $this->pdo->prepare("INSERT INTO payments (student_id, package_id, amount, currency, status, reference_number, notes) VALUES (?, ?, ?, ?, 'awaiting_proof', ?, ?)")
            ->execute([$studentId, $packageId, $amount, $currency, $referenceNumber, $notes]);
        return (int)$this->pdo->lastInsertId();
    }

    public function approve(int $paymentId, int $userId): void {
        $this->pdo->prepare("UPDATE payments SET status = 'approved', approved_by = ?, approved_at = NOW() WHERE id = ?")->execute([$userId, $paymentId]);
    }

    public function activeBankingDetails(): array {
        return $this->pdo->query("SELECT * FROM banking_details WHERE is_active = 1 ORDER BY sort_order, id")->fetchAll();
    }
}
