<?php
// src/Controllers/PaymentController.php

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../Helpers/Auth.php';

class PaymentController {
    public static function initiatePaystackTransaction(int $userId, string $courseId, string $email, int $amountInKobo): array {
        $db = Database::getConnection();

        // Verify course exists
        $stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
        $stmt->execute([$courseId]);
        $course = $stmt->fetch();

        if (!$course) {
            return ['success' => false, 'message' => 'Course not found.'];
        }

        $reference = 'DF_' . time() . '_' . rand(1000, 9999);

        // Check if Paystack API Key is configured
        if (strpos(PAYSTACK_SECRET_KEY, 'sk_test_demo') === 0 || strpos(PAYSTACK_SECRET_KEY, 'pk_test_demo') === 0) {
            // Simulated transaction for demo environment
            return [
                'success' => true,
                'simulated' => true,
                'reference' => $reference,
                'authorization_url' => APP_URL . '/api/paystack-verify.php?reference=' . $reference . '&course_id=' . $courseId . '&simulated=true',
                'access_code' => 'demo_access_code_' . rand(100, 999)
            ];
        }

        // Real Paystack cURL call
        $url = "https://api.paystack.co/transaction/initialize";
        $fields = [
            'email' => $email,
            'amount' => $amountInKobo,
            'reference' => $reference,
            'callback_url' => APP_URL . '/api/paystack-verify.php?course_id=' . $courseId,
            'metadata' => [
                'user_id' => $userId,
                'course_id' => $courseId,
                'custom_fields' => [
                    [
                        'display_name' => 'Course Title',
                        'variable_name' => 'course_title',
                        'value' => $course['title_en']
                    ]
                ]
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer " . PAYSTACK_SECRET_KEY,
            "Content-Type: application/json",
            "Cache-Control: no-cache"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) {
            return ['success' => false, 'message' => 'cURL Error: ' . $err];
        }

        $response = json_decode($result, true);

        if (isset($response['status']) && $response['status'] === true) {
            return [
                'success' => true,
                'simulated' => false,
                'authorization_url' => $response['data']['authorization_url'],
                'access_code' => $response['data']['access_code'],
                'reference' => $reference
            ];
        }

        return ['success' => false, 'message' => $response['message'] ?? 'Payment initialization failed.'];
    }

    public static function verifyAndEnroll(int $userId, string $courseId, string $reference): array {
        $db = Database::getConnection();

        // Verify if user already enrolled
        $stmtCheck = $db->prepare("SELECT id FROM enrollments WHERE user_id = ? AND course_id = ?");
        $stmtCheck->execute([$userId, $courseId]);
        if ($stmtCheck->fetch()) {
            return ['success' => true, 'message' => 'Student is already enrolled in this course.'];
        }

        // Add enrollment
        $stmtEnroll = $db->prepare("INSERT INTO enrollments (user_id, course_id, progress, status, payment_reference, completed_modules_json) VALUES (?, ?, 0, 'in_progress', ?, '[]')");
        $stmtEnroll->execute([$userId, $courseId, $reference]);

        return ['success' => true, 'message' => 'Payment verified! Enrollment successful.'];
    }
}
