<?php
// ============================================================
// backend/api/classes/ClassController.php
// ============================================================

class ClassController {

    private PDO $db;

    public function __construct() {
        $this->db = getDB();
    }

    // GET /classes
    public function index(): void {
        $stmt = $this->db->query(
            'SELECT c.*, 
                    (SELECT COUNT(*) FROM enrollments e WHERE e.class_id = c.id) AS enrolled
             FROM classes c
             WHERE c.status = "active"
             ORDER BY c.class_date ASC'
        );
        sendSuccess($stmt->fetchAll());
    }

    // GET /classes/{id}
    public function show(string $id): void {
        $stmt = $this->db->prepare(
            'SELECT c.*,
                    (SELECT COUNT(*) FROM enrollments e WHERE e.class_id = c.id) AS enrolled
             FROM classes c WHERE c.id = ?'
        );
        $stmt->execute([$id]);
        $class = $stmt->fetch();
        if (!$class) sendError('Class not found', 404);
        sendSuccess($class);
    }

    // POST /classes/enroll  — requires auth
    public function enroll(): void {
        $user    = requireAuth();
        $body    = $GLOBALS['body'];
        $classId = (int)($body['class_id']    ?? 0);
        $ref     = trim($body['payment_ref']  ?? '');

        if (!$classId || !$ref) sendError('class_id and payment_ref required', 422);

        // Verify payment reference with Paystack
        $verified = $this->verifyPaystackPayment($ref);
        if (!$verified['status']) sendError('Payment verification failed: ' . $verified['message'], 402);

        // Fetch class
        $stmt = $this->db->prepare('SELECT * FROM classes WHERE id = ?');
        $stmt->execute([$classId]);
        $class = $stmt->fetch();
        if (!$class) sendError('Class not found', 404);

        // Check already enrolled
        $stmt = $this->db->prepare('SELECT id FROM enrollments WHERE user_id = ? AND class_id = ?');
        $stmt->execute([$user['id'], $classId]);
        if ($stmt->fetch()) sendError('Already enrolled in this class', 409);

        // Save enrollment
        $stmt = $this->db->prepare(
            'INSERT INTO enrollments (user_id, class_id, payment_ref, amount_paid) VALUES (?, ?, ?, ?)'
        );
        $stmt->execute([$user['id'], $classId, $ref, $verified['amount']]);

        // Log payment
        $this->logPayment($user['id'], $ref, $verified['amount'], 'class', $classId);

        sendSuccess([
            'class'        => $class['title'],
            'meeting_link' => $class['meeting_link'],
        ], 'Successfully enrolled', 201);
    }

    // GET /classes/mine  — requires auth
    public function myClasses(): void {
        $user = requireAuth();
        $stmt = $this->db->prepare(
            'SELECT c.*, e.enrolled_at, e.payment_ref
             FROM enrollments e
             JOIN classes c ON c.id = e.class_id
             WHERE e.user_id = ?
             ORDER BY c.class_date DESC'
        );
        $stmt->execute([$user['id']]);
        sendSuccess($stmt->fetchAll());
    }

    // ---- private helpers ----

    private function verifyPaystackPayment(string $reference): array {
        $ch = curl_init("https://api.paystack.co/transaction/verify/$reference");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . PAYSTACK_SECRET_KEY,
                'Cache-Control: no-cache',
            ],
        ]);
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        if (!$data || !$data['status'] || $data['data']['status'] !== 'success') {
            return ['status' => false, 'message' => $data['message'] ?? 'Unknown error', 'amount' => 0];
        }
        return [
            'status'  => true,
            'message' => 'Verified',
            'amount'  => $data['data']['amount'] / 100, // Paystack returns kobo
        ];
    }

    private function logPayment(int $userId, string $ref, float $amount, string $type, int $relatedId): void {
        try {
            $stmt = $this->db->prepare(
                'INSERT INTO payments (user_id, reference, amount, type, related_id, status)
                 VALUES (?, ?, ?, ?, ?, "success")'
            );
            $stmt->execute([$userId, $ref, $amount, $type, $relatedId]);
        } catch (PDOException $e) {
            // duplicate ref — already logged, ignore silently
        }
    }
}
