<?php 
// Advanced Debugging & Configuration
ini_set('display_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');

require_once 'db_connect.php';

// ==========================================
// 🛠️ DATABASE AUTO-PATCHER (Safe Execution)
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `assignments` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `course_id` int(11) NOT NULL,
        `title` varchar(255) NOT NULL,
        `description` text DEFAULT NULL,
        `deadline` datetime NOT NULL,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `assignment_submissions` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `assignment_id` int(11) NOT NULL,
        `student_id` int(11) NOT NULL,
        `file_url` varchar(255) DEFAULT NULL,
        `submitted_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        `status` enum('submitted','graded') DEFAULT 'submitted',
        `marks` varchar(20) DEFAULT NULL,
        `feedback` text DEFAULT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(PDOException $e) {}

include 'includes/user_header.php'; 
if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 

$student_id = $_SESSION['student_id'] ?? null;
if (!$student_id) { echo "<script>window.location.href='login.php';</script>"; exit; }

// ==========================================
// ⚙️ SMART DATA FETCHING
// ==========================================
$assignments = [];
try {
    $stmt = $pdo->prepare("
        SELECT 
            a.*, 
            c.title as course_name, 
            s.id as sub_id, 
            s.status as sub_status, 
            s.marks, 
            s.feedback, 
            s.file_url 
        FROM assignments a
        JOIN courses c ON a.course_id = c.id
        JOIN enrollments e ON a.course_id = e.course_id
        LEFT JOIN assignment_submissions s ON a.id = s.assignment_id AND s.student_id = ?
        WHERE e.student_id = ? AND e.status = 'active'
        ORDER BY a.deadline ASC
    ");
    $stmt->execute([$student_id, $student_id]);
    $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $error = "System Busy."; }
?>

<style>
    :root { --primary: #064e3b; --accent: #d4af37; --bg: #f3f4f6; --white: #ffffff; }
    .main-content { background-color: var(--bg); min-height: 100vh; padding-bottom: 50px; }
    
    /* Modern Card UI */
    .assignment-card { background: var(--white); border-radius: 20px; border: none; padding: 25px; box-shadow: 0 10px 25px rgba(0,0,0,0.03); transition: all 0.3s ease; margin-bottom: 20px; position: relative; border-left: 5px solid transparent; }
    .assignment-card:hover { transform: translateY(-5px); box-shadow: 0 15px 35px rgba(0,0,0,0.08); }
    .card-pending { border-left-color: var(--accent); }
    .card-completed { border-left-color: #10b981; }
    .card-overdue { border-left-color: #ef4444; background: #fff8f8; }

    /* Custom Badges */
    .status-badge { font-size: 10px; font-weight: 800; text-transform: uppercase; padding: 6px 14px; border-radius: 50px; letter-spacing: 0.5px; }
    .badge-pending { background: #fffbeb; color: #d97706; }
    .badge-submitted { background: #ecfdf5; color: #059669; }
    .badge-overdue { background: #fef2f2; color: #dc2626; animation: pulse 2s infinite; }
    @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.6; } 100% { opacity: 1; } }

    /* Tab Customization */
    .custom-nav-pills .nav-link { color: #64748b; font-weight: 700; border-radius: 12px; padding: 12px 25px; transition: 0.3s; border: 1px solid #e2e8f0; background: #fff; margin-right: 10px; }
    .custom-nav-pills .nav-link.active { background: var(--primary) !important; color: #fff !important; border-color: var(--primary); box-shadow: 0 8px 20px rgba(6, 78, 59, 0.2); }

    /* Button Styling */
    .btn-action { background: var(--primary); color: white; border-radius: 12px; padding: 10px 22px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; text-decoration: none; font-size: 14px; }
    .btn-action:hover { background: #022c22; color: var(--accent); transform: scale(1.05); }
    
    .feedback-bubble { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 15px; padding: 15px; margin-top: 15px; font-style: italic; color: #475569; position: relative; }
    .feedback-bubble::before { content: '“'; font-size: 40px; color: #cbd5e1; position: absolute; left: 10px; top: -10px; }

    #sidebarToggle { display: none; }
    @media (max-width: 991.98px) {
        #sidebarToggle { display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #fff; border: 1px solid #ddd; border-radius: 10px; margin-right: 15px; cursor: pointer; color: var(--primary); }
    }
</style>

<div class="main-content p-3 p-md-5">
    <div class="d-flex align-items-center mb-5 fade-up">
        <div>
            <h2 class="fw-bold text-dark mb-1">Learning Track</h2>
            <p class="text-muted fw-semibold mb-0"><i class="fas fa-graduation-cap me-2 text-warning"></i> Manage your assignments and grades</p>
        </div>
    </div>

    <ul class="nav nav-pills custom-nav-pills mb-4 fade-up" id="pills-tab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="pending-tab" data-bs-toggle="pill" data-bs-target="#pills-pending" type="button" role="tab">
                <i class="fas fa-clock me-2"></i>To Do Tasks
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="completed-tab" data-bs-toggle="pill" data-bs-target="#pills-completed" type="button" role="tab">
                <i class="fas fa-check-circle me-2"></i>Finished
            </button>
        </li>
    </ul>

    <div class="tab-content mt-4" id="pills-tabContent">
        
        <div class="tab-pane fade show active" id="pills-pending" role="tabpanel">
            <?php 
            $pending_count = 0;
            foreach($assignments as $task): 
                if($task['sub_id'] == null): 
                    $pending_count++;
                    $is_overdue = strtotime($task['deadline']) < time();
            ?>
                <div class="assignment-card <?= $is_overdue ? 'card-overdue' : 'card-pending' ?> fade-up">
                    <div class="row align-items-center">
                        <div class="col-lg-7">
                            <span class="badge bg-light text-primary border mb-2 px-3 py-2 rounded-pill shadow-sm" style="font-size: 11px;">
                                <i class="fas fa-layer-group me-1"></i> <?= htmlspecialchars((string)$task['course_name']) ?>
                            </span>
                            <h4 class="fw-bold text-dark mt-2 mb-3"><?= htmlspecialchars((string)$task['title']) ?></h4>
                            <div class="d-flex gap-4">
                                <small class="text-muted fw-bold"><i class="far fa-calendar-alt me-1 text-primary"></i> Last Date: <?= date('d M, Y', strtotime($task['deadline'])) ?></small>
                                <small class="text-muted fw-bold"><i class="far fa-clock me-1 text-primary"></i> <?= date('h:i A', strtotime($task['deadline'])) ?></small>
                            </div>
                        </div>
                        <div class="col-lg-5 text-lg-end mt-4 mt-lg-0">
                            <span class="status-badge <?= $is_overdue ? 'badge-overdue' : 'badge-pending' ?> d-inline-block mb-3">
                                <?= $is_overdue ? '⚠️ Time Expired' : '⌛ In Progress' ?>
                            </span><br>
                            <a href="submit_assignment.php?id=<?= $task['id'] ?>" class="btn-action shadow-lg">
                                Submit Homework <i class="fas fa-arrow-right ms-2"></i>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endif; endforeach; ?>
            <?php if($pending_count == 0): ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm">
                    <img src="https://cdn-icons-png.flaticon.com/512/4436/4436481.png" style="width: 80px; opacity: 0.5;" class="mb-3">
                    <h5 class="fw-bold text-muted">No pending assignments. Great job!</h5>
                </div>
            <?php endif; ?>
        </div>

        <div class="tab-pane fade" id="pills-completed" role="tabpanel">
            <?php 
            $done_count = 0;
            foreach($assignments as $task): 
                if($task['sub_id'] != null): 
                    $done_count++;
            ?>
                <div class="assignment-card card-completed fade-up">
                    <div class="row">
                        <div class="col-md-8">
                            <span class="badge bg-success-subtle text-success mb-2 px-3 py-2 rounded-pill border border-success-subtle">
                                <i class="fas fa-check-double me-1"></i> Submitted Successfully
                            </span>
                            <h4 class="fw-bold text-dark mt-2"><?= htmlspecialchars((string)$task['title']) ?></h4>
                            <p class="text-muted small fw-bold mb-0">Course: <?= htmlspecialchars((string)$task['course_name']) ?></p>

                            <?php if($task['sub_status'] == 'graded' && !empty($task['feedback'])): ?>
                                <div class="feedback-bubble mt-3">
                                    <?= htmlspecialchars((string)$task['feedback']) ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-4 text-md-end mt-4 mt-md-0 d-flex flex-column justify-content-center align-items-md-end">
                            <?php if($task['sub_status'] == 'graded'): ?>
                                <div class="bg-light p-3 rounded-4 border text-center shadow-sm" style="min-width: 120px;">
                                    <small class="text-uppercase fw-bold text-muted" style="font-size: 10px;">Final Score</small>
                                    <h2 class="fw-bold text-success mb-0"><?= htmlspecialchars((string)$task['marks']) ?></h2>
                                </div>
                            <?php else: ?>
                                <span class="status-badge badge-pending mb-3">🕒 Under Review</span>
                                <a href="<?= htmlspecialchars((string)$task['file_url']) ?>" target="_blank" class="btn btn-outline-dark btn-sm rounded-pill px-4">
                                    <i class="fas fa-file-download me-2"></i> View My Work
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endif; endforeach; ?>
            <?php if($done_count == 0): ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm">
                    <h5 class="fw-bold text-muted">You haven't submitted anything yet.</h5>
                </div>
            <?php endif; ?>
        </div>

    </div>
</div>

<script>
    // Modern Sidebar Toggle Functionality
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebarMenu');
        if (toggleBtn && sidebar) {
            toggleBtn.addEventListener('click', () => 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/user_footer.php'; ?>