<?php 
// Advanced Configuration
ini_set('display_errors', 1); error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
require_once 'db_connect.php';

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

$student_id = $_SESSION['student_id'] ?? null;
$assignment_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$student_id || !$assignment_id) { echo "<script>window.location.href='assignments.php';</script>"; exit; }

$success = false; $error = '';

// ==========================================
// 1. AUTHENTICATION: Check assignment & enrollment
// ==========================================
try {
    $stmt = $pdo->prepare("
        SELECT a.*, c.title as course_name 
        FROM assignments a 
        JOIN courses c ON a.course_id = c.id
        JOIN enrollments e ON a.course_id = e.course_id
        WHERE a.id = ? AND e.student_id = ? AND e.status = 'active'
    ");
    $stmt->execute([$assignment_id, $student_id]);
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$assignment) { die("<div class='p-5 text-center'><h4>Unauthorized access or assignment not found!</h4></div>"); }
} catch (PDOException $e) { $error = "Connection Lost."; }

// ==========================================
// 2. PROCESSING: Modern File Upload
// ==========================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['homework_file'])) {
    $file = $_FILES['homework_file'];
    $allowed_types = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
    $max_size = 5 * 1024 * 1024; // 5MB limit

    if ($file['error'] !== 0) {
        $error = "Please select a valid file.";
    } elseif (!in_array($file['type'], $allowed_types)) {
        $error = "Format error! Please upload PDF or Images (JPG/PNG).";
    } elseif ($file['size'] > $max_size) {
        $error = "File too large! Maximum limit is 5MB.";
    } else {
        $upload_dir = 'uploads/assignments/';
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }

        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $new_name = "sub_" . $student_id . "_" . $assignment_id . "_" . time() . "." . $ext;
        $dest = $upload_dir . $new_name;

        if (move_uploaded_file($file['tmp_name'], $dest)) {
            try {
                // Check if already submitted (if yes, overwrite file)
                $check = $pdo->prepare("SELECT id FROM assignment_submissions WHERE assignment_id = ? AND student_id = ?");
                $check->execute([$assignment_id, $student_id]);
                $existing = $check->fetch();

                if ($existing) {
                    $upd = $pdo->prepare("UPDATE assignment_submissions SET file_url = ?, submitted_at = NOW(), status = 'submitted' WHERE id = ?");
                    $upd->execute([$dest, $existing['id']]);
                } else {
                    $ins = $pdo->prepare("INSERT INTO assignment_submissions (assignment_id, student_id, file_url) VALUES (?, ?, ?)");
                    $ins->execute([$assignment_id, $student_id, $dest]);
                }
                $success = true;
            } catch (PDOException $e) { $error = "DB Sync Error."; }
        } else { $error = "Server storage error."; }
    }
}
?>

<style>
    :root { --primary: #064e3b; --accent: #d4af37; --bg: #f8fafc; }
    .main-content { background-color: var(--bg); min-height: 100vh; padding-bottom: 50px; }
    
    /* Upload Card UI */
    .glass-card { background: #fff; border-radius: 24px; padding: 40px; box-shadow: 0 15px 40px rgba(0,0,0,0.04); border: 1px solid rgba(0,0,0,0.05); max-width: 650px; margin: 0 auto; transition: 0.3s; }
    
    /* Modern Dropzone */
    .drop-zone { border: 2px dashed #cbd5e1; border-radius: 20px; padding: 40px 20px; text-align: center; cursor: pointer; background: #fdfdfd; transition: all 0.3s; }
    .drop-zone:hover, .drop-zone.active { border-color: var(--primary); background: #ecfdf5; }
    .drop-zone i { font-size: 50px; color: #94a3b8; margin-bottom: 15px; transition: 0.3s; }
    .drop-zone:hover i { color: var(--primary); transform: scale(1.1); }

    .btn-submit-modern { background: var(--primary); color: white; border: none; padding: 16px; border-radius: 16px; font-weight: 800; font-size: 16px; width: 100%; transition: 0.3s; box-shadow: 0 10px 20px rgba(6,78,59,0.15); }
    .btn-submit-modern:hover { background: #022c22; transform: translateY(-3px); box-shadow: 0 15px 30px rgba(6,78,59,0.25); color: var(--accent); }

    /* File Preview */
    #file-info { display: none; margin-top: 15px; padding: 10px; border-radius: 10px; background: #f1f5f9; font-weight: 700; color: var(--primary); font-size: 13px; }

    #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">
        <div id="sidebarToggle"><i class="fas fa-bars"></i></div>
        <a href="assignments.php" class="text-decoration-none text-muted fw-bold small"><i class="fas fa-arrow-left me-1"></i> BACK TO LIST</a>
    </div>

    <div class="glass-card">
        <?php if($success): ?>
            <div class="text-center py-5">
                <div class="mb-4">
                    <img src="https://cdn-icons-png.flaticon.com/512/5290/5290058.png" style="width: 100px;">
                </div>
                <h2 class="fw-bold text-dark">Submission Confirmed!</h2>
                <p class="text-muted mb-4">MashaAllah! Your assignment has been successfully uploaded for review.</p>
                <a href="assignments.php" class="btn btn-dark px-5 py-3 rounded-pill fw-bold">Return to Dashboard</a>
            </div>
        <?php else: ?>
            <div class="mb-4">
                <span class="badge bg-success-subtle text-success px-3 py-2 rounded-pill mb-2 border border-success-subtle">
                    <i class="fas fa-book-open me-1"></i> <?= htmlspecialchars($assignment['course_name']) ?>
                </span>
                <h3 class="fw-bold text-dark mb-2"><?= htmlspecialchars($assignment['title']) ?></h3>
                <p class="text-muted small"><?= nl2br(htmlspecialchars($assignment['description'] ?? 'No extra instructions provided.')) ?></p>
            </div>

            <?php if($error): ?>
                <div class="alert alert-danger border-0 rounded-4 fw-bold small mb-4 shadow-sm"><i class="fas fa-exclamation-circle me-2"></i> <?= $error ?></div>
            <?php endif; ?>

            <form action="" method="POST" enctype="multipart/form-data" id="uploadForm">
                <div class="mb-4">
                    <label for="fileInput" class="drop-zone" id="dropZone">
                        <i class="fas fa-cloud-arrow-up"></i>
                        <h5 class="fw-bold text-dark mb-1">Click or Drop File Here</h5>
                        <p class="text-muted small mb-0">Accepted: PDF, JPG, PNG (Max 5MB)</p>
                        <input type="file" name="homework_file" id="fileInput" hidden required accept=".pdf, .jpg, .jpeg, .png">
                        <div id="file-info"><i class="fas fa-file-alt me-2"></i> <span id="file-name"></span></div>
                    </label>
                </div>

                <button type="submit" class="btn-submit-modern" id="submitBtn">
                    <span id="btnText">UPLOAD & SUBMIT</span>
                    <span id="btnSpinner" class="spinner-border spinner-border-sm d-none"></span>
                </button>
            </form>
        <?php endif; ?>
    </div>
</div>

<script>
    // Modern File Input & UI Interaction
    const fileInput = document.getElementById('fileInput');
    const dropZone = document.getElementById('dropZone');
    const fileInfo = document.getElementById('file-info');
    const fileName = document.getElementById('file-name');
    const uploadForm = document.getElementById('uploadForm');
    const submitBtn = document.getElementById('submitBtn');

    fileInput.addEventListener('change', function() {
        if(this.files.length > 0) {
            fileInfo.style.display = 'block';
            fileName.innerText = this.files[0].name;
            dropZone.classList.add('active');
        }
    });

    // Drag & Drop Support
    ['dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, e => {
            e.preventDefault();
            if(eventName === 'dragover') dropZone.classList.add('active');
            else if(eventName === 'dragleave') dropZone.classList.remove('active');
            else {
                dropZone.classList.remove('active');
                fileInput.files = e.dataTransfer.files;
                fileInput.dispatchEvent(new Event('change'));
            }
        });
    });

    // Sidebar Toggle
    document.addEventListener("DOMContentLoaded", function() {
        document.getElementById('sidebarToggle')?.addEventListener('click', () => {
            document.getElementById('sidebarMenu').classList.toggle('active');
        });
    });

    // Submit Loading Effect
    uploadForm?.addEventListener('submit', () => {
        document.getElementById('btnText').innerText = "Uploading...";
        document.getElementById('btnSpinner').classList.remove('d-none');
        submitBtn.disabled = true;
    });
</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'; ?>