<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';
require_once __DIR__ . '/classes/CertificateGenerator.php';

$auth = new Auth();
if (!$auth->isLoggedIn() || !$auth->hasRole('student')) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();
$certificateGenerator = new CertificateGenerator();
$user = $auth->getCurrentUser();
$message = '';

// الحصول على معلومات الطالب
$student = $db->fetchOne(
    "SELECT s.* FROM students s WHERE s.user_id = ?",
    [$user['id']]
);

if (!$student) {
    header('Location: dashboard.php');
    exit;
}

// معالجة طلب شهادة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'request') {
    $certificate_type = $_POST['certificate_type'] ?? '';
    
    if (empty($certificate_type)) {
        $message = '<div class="alert alert-error">يرجى اختيار نوع الشهادة</div>';
    } else {
        try {
            $result = $certificateGenerator->createRequest($student['id'], $certificate_type);
            $message = '<div class="alert ' . ($result['success'] ? 'alert-success' : 'alert-error') . '">' 
                       . htmlspecialchars($result['message']) . '</div>';
        } catch (Exception $e) {
            $message = '<div class="alert alert-error">حدث خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>';
            error_log("Error creating certificate request: " . $e->getMessage());
        }
    }
}

// جلب طلبات الشهادات
try {
    $requests = $db->fetchAll(
        "SELECT * FROM certificate_requests 
         WHERE student_id = ? 
         ORDER BY request_date DESC",
        [$student['id']]
    );
} catch (Exception $e) {
    $requests = [];
    if (empty($message)) {
        $message = '<div class="alert alert-error">حدث خطأ في جلب البيانات: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// جلب الشهادات الصادرة
try {
    $certificates = $db->fetchAll(
        "SELECT c.*, cr.certificate_type 
         FROM certificates c
         JOIN certificate_requests cr ON c.certificate_request_id = cr.id
         WHERE c.student_id = ?
         ORDER BY c.issue_date DESC",
        [$student['id']]
    );
} catch (Exception $e) {
    $certificates = [];
    error_log("Error fetching certificates: " . $e->getMessage());
}

$certificate_types = [
    'detailed' => 'شهادة تفاصيل',
    'university' => 'شهادة جامعية',
    'transcript' => 'كشف درجات',
    'enrollment' => 'شهادة قيد',
    'graduation' => 'شهادة تخرج'
];

$status_labels = [
    'pending' => 'قيد الانتظار',
    'approved' => 'موافق عليها',
    'rejected' => 'مرفوضة',
    'issued' => 'صادرة'
];
?>
<!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 rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h2>طلب الشهادات</h2>
        </div>
        
        <?php echo $message; ?>
        
        <div class="card">
            <div class="card-header">
                <h3>تقديم طلب شهادة جديدة</h3>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="request">
                <div class="form-group">
                    <label>نوع الشهادة</label>
                    <select name="certificate_type" required>
                        <option value="">اختر نوع الشهادة</option>
                        <?php foreach ($certificate_types as $type => $label): ?>
                            <option value="<?php echo $type; ?>"><?php echo $label; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary">تقديم الطلب</button>
            </form>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h3>طلبات الشهادات</h3>
            </div>
            <?php if (!empty($requests)): ?>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>نوع الشهادة</th>
                                <th>تاريخ الطلب</th>
                                <th>الحالة</th>
                                <th>رقم الشهادة</th>
                                <th>تاريخ الإصدار</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($requests as $request): ?>
                                <tr>
                                    <td><?php echo $certificate_types[$request['certificate_type']] ?? $request['certificate_type'] ?? '-'; ?></td>
                                    <td><?php echo !empty($request['request_date']) ? date('Y-m-d', strtotime($request['request_date'])) : '-'; ?></td>
                                    <td><?php echo $status_labels[$request['status']] ?? $request['status'] ?? '-'; ?></td>
                                    <td><?php echo htmlspecialchars($request['certificate_number'] ?? '-'); ?></td>
                                    <td><?php echo !empty($request['issued_date']) ? date('Y-m-d', strtotime($request['issued_date'])) : '-'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p>لا توجد طلبات شهادات</p>
            <?php endif; ?>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h3>الشهادات الصادرة</h3>
            </div>
            <?php if (!empty($certificates)): ?>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>نوع الشهادة</th>
                                <th>رقم الشهادة</th>
                                <th>تاريخ الإصدار</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($certificates as $cert): ?>
                                <tr>
                                    <td><?php echo $certificate_types[$cert['certificate_type']] ?? $cert['certificate_type'] ?? '-'; ?></td>
                                    <td><?php echo htmlspecialchars($cert['certificate_number'] ?? '-'); ?></td>
                                    <td><?php echo !empty($cert['issue_date']) ? date('Y-m-d', strtotime($cert['issue_date'])) : '-'; ?></td>
                                    <td>
                                        <?php if (!empty($cert['id'])): ?>
                                            <a href="view_certificate.php?id=<?php echo $cert['id']; ?>" class="btn btn-primary">عرض</a>
                                        <?php else: ?>
                                            <span class="btn btn-secondary">-</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p>لا توجد شهادات صادرة</p>
            <?php endif; ?>
        </div>
    </div>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>

