<?php
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

require_student();

$page_title = 'لوحة المتدرب';

$student = current_student();
$student_id = (int)($student['id'] ?? 0);

$applications_count = 0;
$accepted_count = 0;
$certificates_count = 0;
$tickets_count = 0;

if (table_exists('course_applications')) {
    $result = $mysqli->query("SELECT COUNT(*) AS total FROM course_applications WHERE student_id = $student_id");
    if ($result) {
        $applications_count = (int)($result->fetch_assoc()['total'] ?? 0);
    }

    $result = $mysqli->query("SELECT COUNT(*) AS total FROM course_applications WHERE student_id = $student_id AND status = 'accepted'");
    if ($result) {
        $accepted_count = (int)($result->fetch_assoc()['total'] ?? 0);
    }
}

if (table_exists('certificates')) {
    $result = $mysqli->query("SELECT COUNT(*) AS total FROM certificates WHERE student_id = $student_id");
    if ($result) {
        $certificates_count = (int)($result->fetch_assoc()['total'] ?? 0);
    }
}

if (table_exists('support_tickets')) {
    $result = $mysqli->query("SELECT COUNT(*) AS total FROM support_tickets WHERE student_id = $student_id");
    if ($result) {
        $tickets_count = (int)($result->fetch_assoc()['total'] ?? 0);
    }
}

/*
|--------------------------------------------------------------------------
| آخر التقديمات
|--------------------------------------------------------------------------
*/
$applications = [];

if (table_exists('course_applications') && table_exists('courses')) {
    $stmt = $mysqli->prepare("
        SELECT 
            ca.*,
            c.title AS course_title,
            c.location,
            c.start_date
        FROM course_applications ca
        LEFT JOIN courses c ON c.id = ca.course_id
        WHERE ca.student_id = ?
        ORDER BY ca.created_at DESC, ca.id DESC
        LIMIT 5
    ");

    if ($stmt) {
        $stmt->bind_param('i', $student_id);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $applications[] = $row;
        }
    }
}

/*
|--------------------------------------------------------------------------
| دورات متاحة
|--------------------------------------------------------------------------
*/
$courses = [];

if (table_exists('courses')) {
    $result = $mysqli->query("
        SELECT *
        FROM courses
        WHERE status = 'published'
        ORDER BY created_at DESC, id DESC
        LIMIT 4
    ");

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $courses[] = $row;
        }
    }
}

/*
|--------------------------------------------------------------------------
| إعلانات
|--------------------------------------------------------------------------
*/
$announcements = [];

if (table_exists('announcements')) {
    $result = $mysqli->query("
        SELECT *
        FROM announcements
        WHERE status = 'published'
        ORDER BY published_at DESC, created_at DESC, id DESC
        LIMIT 4
    ");

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $announcements[] = $row;
        }
    }
}

include __DIR__ . '/includes/student_header.php';
?>

<section class="page-section">
    <div class="container">

        <div class="dashboard-hero">
            <h1>
                أهلاً <?= e($student['full_name'] ?? 'بك') ?>
            </h1>

            <p>
                من هنا يمكنك متابعة دوراتك، تقديماتك، شهاداتك، والإعلانات الخاصة بمنصة CORE Training Hub.
            </p>
        </div>

        <div class="row g-4 mb-4">

            <div class="col-lg-3 col-md-6">
                <div class="portal-card">
                    <div class="stat-icon">
                        <i class="bi bi-ui-checks"></i>
                    </div>

                    <div class="stat-title">تقديماتي</div>
                    <h2 class="stat-number"><?= (int)$applications_count ?></h2>
                </div>
            </div>

            <div class="col-lg-3 col-md-6">
                <div class="portal-card">
                    <div class="stat-icon">
                        <i class="bi bi-check2-circle"></i>
                    </div>

                    <div class="stat-title">الدورات المقبولة</div>
                    <h2 class="stat-number"><?= (int)$accepted_count ?></h2>
                </div>
            </div>

            <div class="col-lg-3 col-md-6">
                <div class="portal-card">
                    <div class="stat-icon">
                        <i class="bi bi-award"></i>
                    </div>

                    <div class="stat-title">شهاداتي</div>
                    <h2 class="stat-number"><?= (int)$certificates_count ?></h2>
                </div>
            </div>

            <div class="col-lg-3 col-md-6">
                <div class="portal-card">
                    <div class="stat-icon">
                        <i class="bi bi-ticket-detailed"></i>
                    </div>

                    <div class="stat-title">تذاكر الدعم</div>
                    <h2 class="stat-number"><?= (int)$tickets_count ?></h2>
                </div>
            </div>

        </div>

        <div class="row g-4">

            <div class="col-lg-8">

                <div class="portal-card mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
                        <h4 class="fw-black mb-0">آخر التقديمات</h4>

                        <a href="<?= url('my_courses.php') ?>" class="btn-soft">
                            عرض الكل
                        </a>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                            <tr>
                                <th>الدورة</th>
                                <th>المكان</th>
                                <th>الحالة</th>
                                <th>تاريخ التقديم</th>
                            </tr>
                            </thead>

                            <tbody>
                            <?php if (!empty($applications)): ?>
                                <?php foreach ($applications as $app): ?>
                                    <tr>
                                        <td>
                                            <strong><?= e($app['course_title'] ?? '-') ?></strong>
                                        </td>

                                        <td><?= e($app['location'] ?? '-') ?></td>

                                        <td>
                                            <?= status_badge($app['status'] ?? '') ?>
                                        </td>

                                        <td>
                                            <?php if (!empty($app['created_at'])): ?>
                                                <?= date('Y/m/d', strtotime($app['created_at'])) ?>
                                            <?php else: ?>
                                                -
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center py-4">
                                        لا توجد تقديمات حتى الآن.
                                    </td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="portal-card">
                    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
                        <h4 class="fw-black mb-0">دورات متاحة</h4>

                        <a href="<?= url('courses.php') ?>" class="btn-soft">
                            كل الدورات
                        </a>
                    </div>

                    <div class="row g-3">
                        <?php if (!empty($courses)): ?>
                            <?php foreach ($courses as $course): ?>
                                <div class="col-md-6">
                                    <div class="course-mini">
                                        <h5><?= e($course['title'] ?? '-') ?></h5>

                                        <p class="text-muted">
                                            <?= e(short_text($course['summary'] ?? $course['description'] ?? '', 100)) ?>
                                        </p>

                                        <?php if (!empty($course['start_date'])): ?>
                                            <div class="text-muted small mb-2">
                                                <i class="bi bi-calendar"></i>
                                                <?= date('Y/m/d', strtotime($course['start_date'])) ?>
                                            </div>
                                        <?php endif; ?>

                                        <?php if (!empty($course['location'])): ?>
                                            <div class="text-muted small mb-3">
                                                <i class="bi bi-geo-alt"></i>
                                                <?= e($course['location']) ?>
                                            </div>
                                        <?php endif; ?>

                                        <a href="<?= url('course_view.php?id=' . (int)$course['id']) ?>" class="btn-core btn-sm">
                                            التفاصيل
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="col-12 text-center text-muted py-4">
                                لا توجد دورات منشورة حاليًا.
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <div class="col-lg-4">

                <div class="portal-card">
                    <h4 class="fw-black mb-3">الإعلانات</h4>

                    <?php if (!empty($announcements)): ?>
                        <?php foreach ($announcements as $announcement): ?>
                            <div class="announcement mb-3">
                                <h5><?= e($announcement['title'] ?? '-') ?></h5>

                                <p class="text-muted mb-0">
                                    <?= e(short_text($announcement['body'] ?? '', 110)) ?>
                                </p>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="text-muted mb-0">
                            لا توجد إعلانات حاليًا.
                        </p>
                    <?php endif; ?>
                </div>

            </div>

        </div>

    </div>
</section>

<?php include __DIR__ . '/includes/student_footer.php'; ?>
/* =====================================================
   FIX CORE PORTAL LOGO SIZE
   يمنع الشعار من الظهور بحجمه الأصلي الكبير
===================================================== */

html,
body {
    width: 100%;
    overflow-x: hidden;
    background: #f5f8ff !important;
}

body > img,
body > a > img {
    max-width: 100% !important;
}

/* شعار النافبار */
.portal-navbar .navbar-brand {
    display: inline-flex !important;
    align-items: center !important;
    gap: 10px !important;
    max-width: max-content !important;
}

.portal-navbar .navbar-brand img {
    width: 54px !important;
    height: 54px !important;
    max-width: 54px !important;
    max-height: 54px !important;
    min-width: 54px !important;
    object-fit: contain !important;
    display: block !important;
}

.portal-navbar .navbar-brand span {
    font-size: 17px !important;
    font-weight: 900 !important;
    color: #0827b8 !important;
    white-space: nowrap !important;
}

/* منع أي صورة شعار من التمدد داخل الصفحة */
img[src*="core-logo"],
img[src*="CORE"],
img[src*="logo"] {
    max-width: 180px;
    height: auto;
}

/* لكن شعار الهيدر تحديدًا يبقى صغير */
.portal-navbar img[src*="core-logo"],
.portal-navbar img[src*="CORE"],
.portal-navbar img[src*="logo"] {
    width: 54px !important;
    height: 54px !important;
    max-width: 54px !important;
    max-height: 54px !important;
}

/* ترتيب محتوى الداشبورد */
.section {
    padding: 45px 0 !important;
}

.section .container {
    max-width: 1180px !important;
}

/* كروت الداشبورد */
.panel-card {
    background: #fff !important;
    border-radius: 28px !important;
    padding: 26px !important;
    box-shadow: 0 18px 55px rgba(8, 39, 184, 0.10) !important;
    border: 1px solid rgba(8, 39, 184, 0.10) !important;
}

/* الفوتر إذا يحتوي شعار */
footer img,
.portal-footer img {
    max-width: 90px !important;
    height: auto !important;
}

/* منع وجود شعار كخلفية ضخمة */
body,
.portal-navbar,
.section,
.container,
main,
footer {
    background-size: auto !important;
    background-repeat: no-repeat !important;
}