<?php
// admin_payments.php - Payment Details
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

session_start();

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

try {
    require 'db.php';
    require 'helpers.php';

    $adminName = (string)($_SESSION['admin_username'] ?? 'الإدارة العليا');
    $mysqli1->set_charset('utf8mb4');
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    // Check if payments table exists
    $tableCheck = $mysqli1->query("SHOW TABLES LIKE 'payments'");
    $payments_table_exists = $tableCheck->num_rows > 0;

    if (!$payments_table_exists) {
        throw new Exception('جدول المدفوعات غير موجود');
    }

    // Get payment statistics
    $stats_sql = "
        SELECT 
            COUNT(*) as total_payments,
            COUNT(DISTINCT student_id) as unique_students,
            SUM(payment_amount) as total_amount,
            AVG(payment_amount) as average_payment,
            MAX(payment_amount) as max_payment,
            MIN(payment_amount) as min_payment
        FROM payments
    ";
    $stats_result = $mysqli1->query($stats_sql);
    $payment_stats = $stats_result->fetch_assoc();
    $stats_result->close();

    // Get recent payments with student details
    $payments_sql = "
        SELECT 
            p.*,
            s.student_name,
            s.student_name_eng,
            c.name as college_name,
            p.created_at as payment_date
        FROM payments p
        LEFT JOIN students s ON p.student_id = s.student_id
        LEFT JOIN colleges c ON s.college_id = c.id
        ORDER BY p.created_at DESC
        LIMIT 100
    ";
    $payments_result = $mysqli1->query($payments_sql);
    $recent_payments = $payments_result->fetch_all(MYSQLI_ASSOC);
    $payments_result->close();

    $data_loaded = true;

} catch (Exception $e) {
    $error_message = $e->getMessage();
    $data_loaded = false;
    $payment_stats = [];
    $recent_payments = [];
}

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تفاصيل المدفوعات - الإدارة العليا</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --g-900: #1F3A2E;
            --g-700: #3E6B54;
            --purple-600: #8e44ad;
        }

        body {
            font-family: 'Cairo', system-ui, -apple-system, sans-serif;
            background: #f8f9fa;
            min-height: 100vh;
        }

        .dashboard-header {
            background: linear-gradient(135deg, var(--purple-600), #7d3c98);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            border-right: 4px solid var(--purple-600);
            text-align: center;
            margin-bottom: 1.5rem;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 800;
            color: var(--g-900);
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #6c757d;
            font-weight: 600;
        }

        .back-btn {
            background: var(--purple-600);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            font-weight: 700;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .payment-amount {
            font-weight: 700;
            color: #28a745;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="dashboard-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="h3 mb-2">تفاصيل المدفوعات</h1>
                    <p class="mb-0">إحصائيات وسجلات المدفوعات</p>
                </div>
                <div class="col-md-4 text-md-start">
                    <a href="admin_dashboard.php" class="back-btn">
                        <i class="fas fa-arrow-right"></i> العودة للوحة التحكم
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error_message) ?></div>
        <?php endif; ?>

        <?php if ($data_loaded): ?>
        <!-- Payment Statistics -->
        <div class="row mb-4">
            <div class="col-md-2 col-6">
                <div class="stat-card">
                    <div class="stat-number"><?= number_format($payment_stats['total_payments'] ?? 0) ?></div>
                    <div class="stat-label">إجمالي المعاملات</div>
                </div>
            </div>
            <div class="col-md-2 col-6">
                <div class="stat-card">
                    <div class="stat-number"><?= number_format($payment_stats['unique_students'] ?? 0) ?></div>
                    <div class="stat-label">طالب دفعوا</div>
                </div>
            </div>
            <div class="col-md-2 col-6">
                <div class="stat-card">
                    <div class="stat-number"><?= number_format($payment_stats['total_amount'] ?? 0) ?></div>
                    <div class="stat-label">إجمالي المبالغ</div>
                </div>
            </div>
            <div class="col-md-2 col-6">
                <div class="stat-card">
                    <div class="stat-number"><?= number_format($payment_stats['average_payment'] ?? 0, 2) ?></div>
                    <div class="stat-label">متوسط الدفعة</div>
                </div>
            </div>
            <div class="col-md-2 col-6">
                <div class="stat-card">
                    <div class="stat-number"><?= number_format($payment_stats['max_payment'] ?? 0, 2) ?></div>
                    <div class="stat-label">أعلى دفعة</div>
                </div>
            </div>
            <div class="col-md-2 col-6">
                <div class="stat-card">
                    <div class="stat-number"><?= number_format($payment_stats['min_payment'] ?? 0, 2) ?></div>
                    <div class="stat-label">أقل دفعة</div>
                </div>
            </div>
        </div>

        <!-- Recent Payments -->
        <div class="stat-card">
            <h4 class="mb-4">آخر المدفوعات</h4>
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>رقم المعاملة</th>
                            <th>الطالب</th>
                            <th>الكلية</th>
                            <th>المبلغ</th>
                            <th>تاريخ الدفع</th>
                            <th>الرقم الجامعي</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($recent_payments)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">
                                    لا توجد مدفوعات مسجلة
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($recent_payments as $payment): ?>
                                <tr>
                                    <td>#<?= htmlspecialchars($payment['id'] ?? '') ?></td>
                                    <td>
                                        <?php 
                                        $name = !empty($payment['student_name']) ? $payment['student_name'] : $payment['student_name_eng'];
                                        echo htmlspecialchars($name);
                                        ?>
                                    </td>
                                    <td><?= htmlspecialchars($payment['college_name']) ?></td>
                                    <td class="payment-amount"><?= number_format($payment['payment_amount'], 2) ?></td>
                                    <td>
                                        <?= !empty($payment['payment_date']) ? date('Y-m-d H:i', strtotime($payment['payment_date'])) : 'غير محدد' ?>
                                    </td>
                                    <td><strong><?= htmlspecialchars($payment['student_id']) ?></strong></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <?php include 'footer.php'; ?>
</body>
</html>