<?php 
// 1. Include partials
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once '../db_connect.php'; 

// Admin Security Check
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit; }

$success_msg = ''; $error_msg = '';

// Handle Messages
if(isset($_GET['msg'])) {
    if($_GET['msg'] == 'deleted') $success_msg = "Result has been deleted successfully.";
    elseif($_GET['msg'] == 'updated') $success_msg = "Result information updated successfully!";
    elseif($_GET['msg'] == 'error') $error_msg = "Something went wrong! Please try again.";
}

// 2. Pagination Settings
$limit = 50; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// 3. Delete Logic (Fixed with Redirect)
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    
    try {
        // Fetch image path for deletion
        $stmt = $pdo->prepare("SELECT details_json FROM results WHERE id = ?");
        $stmt->execute([$delete_id]);
        $res_to_del = $stmt->fetch();
        
        if ($res_to_del) {
            $del_details = json_decode($res_to_del['details_json'], true);
            if (!empty($del_details['student_photo']) && file_exists('../' . $del_details['student_photo'])) {
                unlink('../' . $del_details['student_photo']); 
            }
        }
        
        $pdo->prepare("DELETE FROM results WHERE id = ?")->execute([$delete_id]);
        echo "<script>window.location.href='manage_results.php?msg=deleted';</script>";
        exit;
    } catch (Exception $e) {
        echo "<script>window.location.href='manage_results.php?msg=error';</script>";
        exit;
    }
}

include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// 4. Fetch Data from Database
$total_rows = $pdo->query("SELECT COUNT(*) FROM results")->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$stmt = $pdo->prepare("SELECT * FROM results ORDER BY id DESC LIMIT $offset, $limit");
$stmt->execute();
$results = $stmt->fetchAll();

$sn = $offset + 1;
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }

    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    
    /* Header & Mobile Toggle */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }
    
    .btn-theme { background: var(--theme-green); color: #fff; border-radius: 12px; padding: 12px 24px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
    .btn-theme:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 15px rgba(6, 78, 59, 0.2); }

    /* Desktop Table Styles */
    .desktop-table-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .table thead th { background-color: #f1f5f9; color: #64748b; font-size: 11px; text-transform: uppercase; font-weight: 800; padding: 18px 20px; border: none; letter-spacing: 0.5px; }
    .table tbody tr:hover { background-color: #f8fafc; }
    .table td { padding: 15px 20px; vertical-align: middle; font-size: 14px; color: #334155; border-bottom: 1px solid #f1f5f9; }
    
    /* Avatar & Result Labels */
    .student-avatar { width: 45px; height: 50px; object-fit: cover; border-radius: 10px; border: 2px solid #fff; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
    .badge-gpa { background: rgba(212, 175, 55, 0.15); color: var(--theme-green); font-weight: 800; padding: 6px 14px; border-radius: 50px; font-size: 13px; border: 1px solid rgba(212, 175, 55, 0.4); display: inline-block; }

    /* Action Buttons */
    .act-btn { width: 34px; height: 34px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; transition: 0.3s; margin: 0 3px; text-decoration: none; cursor: pointer; border: none; }
    .act-edit { background: #f1f5f9; color: var(--theme-green); }
    .act-edit:hover { background: var(--theme-green); color: #fff; transform: translateY(-2px); }
    .act-delete { background: #fef2f2; color: #ef4444; }
    .act-delete:hover { background: #ef4444; color: #fff; transform: translateY(-2px); }

    /* Pagination */
    .pagination .page-item.active .page-link { background-color: var(--theme-green); border-color: var(--theme-green); color: #fff; }
    .pagination .page-link { color: var(--theme-green); font-weight: 600; border-radius: 8px !important; margin: 0 3px; border: 1px solid #e2e8f0; }

    /* Animations */
    .fade-up { animation: fadeInUp 0.4s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }

    /* 📱 Mobile Specific Styles (Card View) */
    .result-mobile-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; transition: 0.3s; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .header-top { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        .dashboard-header .btn-theme { width: 100%; }
        #sidebarToggle { display: inline-flex !important; }
        .header-title { font-size: 1.2rem; }
    }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="header-top">
            <button id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars fs-5"></i></button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title"><i class="fas fa-graduation-cap me-2" style="color: var(--theme-gold);"></i> Result Management</h4>
                <p class="text-muted small fw-bold mb-0 d-none d-md-block">Manage and publish student academic performance</p>
            </div>
        </div>
        <a href="add_result.php" class="btn-theme shadow-sm mt-3 mt-md-0">
            <i class="fas fa-plus-circle me-2"></i> Add New Result
        </a>
    </div>

    <?php if($success_msg): ?> 
        <div class="alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #10b981 !important;">
            <i class="fas fa-check-circle me-3 fa-2x text-success"></i> 
            <div><strong class="d-block text-success">Success!</strong><span class="text-muted small"><?= $success_msg ?></span></div>
        </div>
    <?php endif; ?>
    <?php if($error_msg): ?> 
        <div class="alert alert-danger d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #ef4444 !important;">
            <i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> 
            <div><strong class="d-block text-danger">Error!</strong><span class="text-muted small"><?= $error_msg ?></span></div>
        </div>
    <?php endif; ?>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.1s;">
        <div class="table-responsive">
            <table class="table align-middle mb-0 border-0">
                <thead>
                    <tr>
                        <th class="ps-4">No.</th>
                        <th>Student Photo</th>
                        <th>Reg & Roll</th>
                        <th>Name & Father's Name</th>
                        <th>Course & Session</th>
                        <th>GPA</th>
                        <th class="text-center pe-4">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($results)): foreach($results as $res): 
                        $details = json_decode($res['details_json'], true);
                        $photo_path = (!empty($details['student_photo'])) ? '../' . $details['student_photo'] : '../assets/images/default_student.png';
                    ?>
                    <tr>
                        <td class="ps-4 text-muted fw-bold"><?= str_pad($sn++, 2, "0", STR_PAD_LEFT); ?>.</td>
                        <td>
                            <img src="<?= htmlspecialchars($photo_path) ?>" class="student-avatar shadow-sm" onerror="this.src='../assets/images/default_student.png'" alt="Student">
                        </td>
                        <td>
                            <div class="fw-bold text-dark mb-0"><?= htmlspecialchars($res['regi_no']); ?></div>
                            <small class="badge bg-light text-muted border px-2 py-1" style="font-size: 10px;">ROLL: <?= htmlspecialchars($details['Roll'] ?? 'N/A'); ?></small>
                        </td>
                        <td>
                            <div class="fw-bold text-dark mb-1" style="font-size: 15px;"><?= htmlspecialchars($details['Name'] ?? 'N/A'); ?></div>
                            <small class="text-muted fw-bold"><i class="fas fa-user-friends me-1 text-primary"></i> <?= htmlspecialchars($details['Father\'s Name'] ?? 'N/A'); ?></small>
                        </td>
                        <td>
                            <div class="fw-bold text-dark mb-1" style="font-size: 13px;"><?= htmlspecialchars(mb_strimwidth($res['class_name'], 0, 35, "...")); ?></div>
                            <small class="text-muted fw-bold"><i class="far fa-calendar-alt me-1 text-warning"></i> Session: <?= htmlspecialchars($res['passing_year']); ?></small>
                        </td>
                        <td>
                            <span class="badge-gpa shadow-sm"><?= htmlspecialchars($res['gpa']); ?></span>
                        </td>
                        <td class="text-center pe-4">
                            <a href="edit_result.php?id=<?= $res['id']; ?>" class="act-btn act-edit shadow-sm" title="Edit"><i class="fas fa-pen-nib"></i></a>
                            <a href="manage_results.php?delete_id=<?= $res['id']; ?>" class="act-btn act-delete shadow-sm" onclick="return confirm('Permanently delete this result?')" title="Delete"><i class="fas fa-trash-alt"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="7" class="text-center py-5 text-muted fw-bold"><i class="fas fa-file-invoice fa-3x mb-3 opacity-25 d-block"></i> No results published yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.1s;">
        <div class="row g-3">
            <?php if(!empty($results)): foreach($results as $res): 
                $details = json_decode($res['details_json'], true);
                $photo_path = (!empty($details['student_photo'])) ? '../' . $details['student_photo'] : '../assets/images/default_student.png';
            ?>
            <div class="col-12">
                <div class="result-mobile-card p-3">
                    <div class="d-flex align-items-center gap-3 mb-3 pb-3 border-bottom">
                        <img src="<?= htmlspecialchars($photo_path) ?>" class="student-avatar shadow-sm" style="width: 55px; height: 60px;" onerror="this.src='../assets/images/default_student.png'">
                        <div class="w-100">
                            <div class="d-flex justify-content-between align-items-start">
                                <h6 class="fw-bold text-dark mb-1" style="font-size: 15px;"><?= htmlspecialchars($details['Name'] ?? 'N/A'); ?></h6>
                                <span class="badge-gpa py-1 px-2" style="font-size: 11px;"><?= htmlspecialchars($res['gpa']); ?></span>
                            </div>
                            <small class="text-muted fw-bold" style="font-size: 11px;">REG: <?= htmlspecialchars($res['regi_no']); ?> &bull; ROLL: <?= htmlspecialchars($details['Roll'] ?? 'N/A'); ?></small>
                        </div>
                    </div>
                    
                    <div class="bg-light p-3 rounded-3 border mb-3">
                        <div class="mb-2 d-flex align-items-center">
                            <i class="fas fa-book-reader text-success me-2" style="width: 15px;"></i>
                            <span class="text-dark fw-bold" style="font-size: 12px;"><?= htmlspecialchars($res['class_name']); ?></span>
                        </div>
                        <div class="d-flex align-items-center">
                            <i class="far fa-calendar-check text-warning me-2" style="width: 15px;"></i>
                            <span class="text-muted fw-bold" style="font-size: 12px;">Session/Year: <?= htmlspecialchars($res['passing_year']); ?></span>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <a href="edit_result.php?id=<?= $res['id']; ?>" class="btn btn-light border flex-grow-1 fw-bold text-success" style="font-size: 12px; padding: 10px;"><i class="fas fa-pen-nib me-1"></i> Edit</a>
                        <a href="manage_results.php?delete_id=<?= $res['id']; ?>" class="btn btn-light border flex-grow-1 fw-bold text-danger" style="font-size: 12px; padding: 10px;" onclick="return confirm('Delete this result?');"><i class="fas fa-trash-alt me-1"></i> Delete</a>
                    </div>
                </div>
            </div>
            <?php endforeach; else: ?>
                <div class="col-12 text-center py-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-file-invoice fa-3x text-muted opacity-25 mb-3 d-block"></i>
                    <h6 class="fw-bold text-muted">No results found!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if($total_pages > 1): ?>
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mt-4 px-2 fade-up">
        <div class="text-muted small fw-bold mb-3 mb-md-0">
            Total Results: <span class="text-dark"><?= $total_rows ?></span>
        </div>
        <nav>
            <ul class="pagination mb-0 shadow-sm rounded-3">
                <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                    <a class="page-link" href="?page=<?= $page - 1 ?>"><i class="fas fa-chevron-left"></i></a>
                </li>
                <li class="page-item active"><a class="page-link" href="#"><?= $page ?></a></li>
                <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                    <a class="page-link" href="?page=<?= $page + 1 ?>"><i class="fas fa-chevron-right"></i></a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>

</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Sidebar Toggle for Mobile
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar') || document.getElementById('sidebarMenu');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/footer.php'; ?>