<?php
session_start();
// التحقق من تسجيل الدخول
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

require_once('../config/db.php');

// استدعاء الهيدر لتعريف دالة الترجمة والمتغيرات الأساسية (مثل $dir)
include('../includes/header.php'); 

// التحقق من وجود معرف الطالب
if (!isset($_GET['student_id'])) {
    die(__('error_student_id_missing'));
}

$student_id = (int) $_GET['student_id'];

// 1. جلب بيانات الطالب الأساسية
$student_stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
$student_stmt->execute([$student_id]);
$student = $student_stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die(__('error_student_not_found'));
}

// 2. العمليات الحسابية المتقدمة
$total_price_stmt = $conn->prepare("
    SELECT SUM(c.price) 
    FROM enrollments e
    JOIN courses c ON e.course_id = c.id
    WHERE e.student_id = ?
");
$total_price_stmt->execute([$student_id]);
$total_fees = $total_price_stmt->fetchColumn() ?? 0;

$total_paid_stmt = $conn->prepare("SELECT SUM(amount_paid) FROM payments WHERE student_id = ?");
$total_paid_stmt->execute([$student_id]);
$pure_paid = $total_paid_stmt->fetchColumn() ?? 0;

$total_discount_stmt = $conn->prepare("SELECT SUM(discount) FROM payments WHERE student_id = ?");
$total_discount_stmt->execute([$student_id]);
$total_discount = $total_discount_stmt->fetchColumn() ?? 0;

$remaining = $total_fees - ($pure_paid + $total_discount);
if ($remaining < 0) $remaining = 0;

$error = '';

// 3. معالجة طلب الدفع (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount_to_pay = floatval($_POST['amount']);

    if ($amount_to_pay <= 0) {
        $error = __('error_invalid_payment_amount');
    } elseif ($amount_to_pay > $remaining) {
        $error = __('error_amount_exceeds_remaining') . " ($remaining " . __('currency_symbol') . ")";
    } else {
        // API efawateercom logic
        $invoice_data = [
            "customer" => [
                "name"  => $student['full_name'],
                "phone" => $student['phone'],
                "email" => $student['email'] ?? 'info@academy.com'
            ],
            "order" => [
                "amount"      => $amount_to_pay,
                "currency"    => "JOD",
                "description" => __('payment_description_prefix') . " - " . $student['full_name'],
                "reference"   => "PAY-" . time() . "-" . $student_id
            ],
            "callback_url" => "https://yourdomain.com/payments/callback.php", 
            "cancel_url"   => "https://yourdomain.com/payments/pay.php?student_id=" . $student_id
        ];

        $ch = curl_init("https://api.efawateer.com/v1/invoices"); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer YOUR_API_KEY_HERE", 
            "Content-Type: application/json"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($invoice_data));

        $response = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $result = json_decode($response, true);

        if ($http_status == 200 && isset($result['payment_url'])) {
            $log_stmt = $conn->prepare("
                INSERT INTO efawateer_invoices (student_id, invoice_id, amount, status, created_at) 
                VALUES (?, ?, ?, 'pending', NOW())
            ");
            $log_stmt->execute([$student_id, $result['invoice_id'], $amount_to_pay]);

            header("Location: " . $result['payment_url']);
            exit;
        } else {
            $error = __('error_payment_gateway_connection') . ": " . ($result['message'] ?? __('technical_error'));
        }
    }
}
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;700;900&display=swap');
    body { font-family: 'Cairo', sans-serif; }
    input[type=number]::-webkit-inner-spin-button, 
    input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
</style>

<?php include('../includes/navbar.php'); ?>

<div class="container mx-auto px-4 py-12" dir="<?= $dir ?>">
    <div class="max-w-4xl mx-auto">
        
        <div class="mb-8 text-center">
            <h1 class="text-3xl font-bold text-gray-800"><?= __('online_payment_system_title') ?></h1>
            <p class="text-gray-500 mt-2"><?= __('institute_name') ?></p>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
            <div class="bg-white p-5 rounded-2xl shadow-sm border-b-4 border-blue-500">
                <span class="text-gray-400 text-xs block mb-1"><?= __('total_fees_label') ?></span>
                <span class="text-xl font-black text-gray-700"><?= number_format($total_fees, 2) ?></span>
                <span class="text-xs text-gray-400"><?= __('currency_symbol') ?></span>
            </div>
            
            <div class="bg-white p-5 rounded-2xl shadow-sm border-b-4 border-green-500">
                <span class="text-green-500 text-xs block mb-1"><?= __('pure_paid_label') ?></span>
                <span class="text-xl font-black text-green-600"><?= number_format($pure_paid, 2) ?></span>
                <span class="text-xs text-green-500"><?= __('currency_symbol') ?></span>
            </div>

            <div class="bg-white p-5 rounded-2xl shadow-sm border-b-4 border-orange-400">
                <span class="text-orange-500 text-xs block mb-1"><?= __('total_discount_label') ?></span>
                <span class="text-xl font-black text-orange-600"><?= number_format($total_discount, 2) ?></span>
                <span class="text-xs text-orange-500"><?= __('currency_symbol') ?></span>
            </div>

            <div class="bg-red-50 p-5 rounded-2xl shadow-sm border-b-4 border-red-500">
                <span class="text-red-500 text-xs block mb-1"><?= __('net_remaining_label') ?></span>
                <span class="text-xl font-black text-red-700"><?= number_format($remaining, 2) ?></span>
                <span class="text-xs text-red-500"><?= __('currency_symbol') ?></span>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div class="lg:col-span-2">
                <div class="bg-white rounded-3xl shadow-xl p-8 border border-gray-100">
                    <h3 class="text-xl font-bold mb-6 flex items-center">
                        <span class="bg-blue-100 text-blue-600 p-2 rounded-lg <?= $dir == 'rtl' ? 'ml-3' : 'mr-3' ?>">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                            </svg>
                        </span>
                        <?= __('create_new_payment_title') ?>
                    </h3>

                    <?php if ($error): ?>
                        <div class="bg-red-50 border-r-4 border-red-500 text-red-700 p-4 mb-6 rounded-md flex items-center">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                            </svg>
                            <?= $error ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST" class="space-y-6">
                        <div>
                            <label class="text-sm font-bold text-gray-600 mb-2 block"><?= __('amount_to_pay_label') ?>:</label>
                            <div class="relative">
                                <input type="number" name="amount" step="0.01" max="<?= $remaining ?>" value="<?= $remaining ?>" 
                                       class="w-full bg-gray-50 border-2 border-gray-100 rounded-2xl py-5 text-center text-3xl font-black text-blue-700 focus:bg-white focus:border-blue-500 focus:outline-none transition-all shadow-inner" required>
                                <span class="absolute <?= $dir == 'rtl' ? 'left-6' : 'right-6' ?> top-1/2 -translate-y-1/2 text-gray-400 font-bold"><?= __('currency_symbol') ?></span>
                            </div>
                        </div>

                        <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-5 rounded-2xl font-bold text-lg shadow-lg shadow-blue-200 transition-all transform hover:-translate-y-1 flex justify-center items-center group">
                            <?= __('confirm_payment_btn') ?>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 <?= $dir == 'rtl' ? 'mr-3 group-hover:translate-x-1' : 'ml-3 group-hover:-translate-x-1' ?> transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6" />
                            </svg>
                        </button>
                    </form>
                </div>
            </div>

            <div class="lg:col-span-1">
                <div class="bg-white rounded-3xl shadow-sm p-6 border border-gray-100">
                    <div class="text-center mb-6">
                        <div class="w-20 h-20 bg-blue-50 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-4 text-2xl font-bold">
                            <?= mb_substr($student['full_name'], 0, 1) ?>
                        </div>
                        <h4 class="font-bold text-lg"><?= htmlspecialchars($student['full_name']) ?></h4>
                        <span class="text-gray-400 text-sm"><?= __('registered_student_badge') ?></span>
                    </div>
                    
                    <div class="space-y-4 border-t pt-4">
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-400"><?= __('student_id_label') ?>:</span>
                            <span class="font-medium">#<?= $student_id ?></span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-400"><?= __('phone_label') ?>:</span>
                            <span class="font-medium"><?= htmlspecialchars($student['phone']) ?></span>
                        </div>
                    </div>

                    <div class="mt-8 bg-blue-50 rounded-2xl p-4">
                        <p class="text-[10px] text-blue-400 leading-relaxed text-center">
                            <?= __('payment_security_notice') ?>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include('../includes/footer.php'); ?>