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

$assignment_id = isset($_GET['assignment_id']) ? (int)$_GET['assignment_id'] : 0;
if (!$assignment_id) { header("Location: manage_assignments.php"); exit; }

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

// ==========================================
// 1. UPDATE GRADE & FEEDBACK (PHP Logic)
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_grade'])) {
    $submission_id = (int)$_POST['submission_id'];
    $marks = trim($_POST['marks']);
    $feedback = trim($_POST['feedback']);

    try {
        $stmt = $pdo->prepare("UPDATE assignment_submissions SET marks = ?, feedback = ?, status = 'graded' WHERE id = ?");
        if ($stmt->execute([$marks, $feedback, $submission_id])) {
            $success_msg = "Grade and feedback saved successfully!";
        } else {
            $error_msg = "Failed to update database.";
        }
    } catch (Exception $e) { 
        $error_msg = "Database Error: " . $e->getMessage(); 
    }
}

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

// Fetch Assignment Info
$assign_stmt = $pdo->prepare("SELECT a.*, c.title as course_name FROM assignments a JOIN courses c ON a.course_id = c.id WHERE a.id = ?");
$assign_stmt->execute([$assignment_id]);
$assignment = $assign_stmt->fetch(PDO::FETCH_ASSOC);

if (!$assignment) { die("<div class='p-5 text-center'><h4>Assignment record not found!</h4></div>"); }

// Fetch All Submissions for this assignment
$sub_stmt = $pdo->prepare("
    SELECT s.*, stu.name as student_name, stu.phone as student_phone 
    FROM assignment_submissions s 
    JOIN students stu ON s.student_id = stu.id 
    WHERE s.assignment_id = ? 
    ORDER BY s.submitted_at DESC
");
$sub_stmt->execute([$assignment_id]);
$submissions = $sub_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg: #f8fafc; --white: #ffffff; }
    .main-content { background-color: var(--bg); min-height: 100vh; padding: 25px; transition: 0.3s; }
    
    /* Premium Header Card */
    .dashboard-header { background: var(--white); padding: 25px 30px; border-radius: 20px; box-shadow: 0 4px 25px rgba(0,0,0,0.02); margin-bottom: 30px; border-left: 6px solid var(--theme-gold); }
    
    /* Submission Card Table */
    .table-card { background: var(--white); border-radius: 20px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.04); overflow: hidden; }
    .table thead th { background: #f8fafc; color: #64748b; font-weight: 800; font-size: 11px; text-transform: uppercase; padding: 20px 25px; border: none; letter-spacing: 0.5px; }
    .table tbody td { padding: 20px 25px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }

    /* Custom Status Badges */
    .status-badge { padding: 6px 14px; border-radius: 50px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.3px; display: inline-block; }
    .status-submitted { background: #eff6ff; color: #3b82f6; border: 1px solid #bfdbfe; }
    .status-graded { background: #ecfdf5; color: #10b981; border: 1px solid #a7f3d0; }

    /* Action Buttons */
    .btn-grade { background: var(--theme-green); color: white; border: none; padding: 8px 18px; border-radius: 10px; font-weight: 700; font-size: 13px; transition: 0.3s; }
    .btn-grade:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); }
    
    .btn-view-file { background: #f1f5f9; color: #475569; border: 1px solid #e2e8f0; padding: 6px 14px; border-radius: 8px; font-size: 12px; font-weight: 700; text-decoration: none; transition: 0.2s; }
    .btn-view-file:hover { background: #e2e8f0; color: var(--theme-dark); }

    #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(--theme-green); }
        .dashboard-header { padding: 20px; }
    }
</style>

<div class="main-content p-3 p-md-4">
    <div class="dashboard-header d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
            <div id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars"></i></div>
            <div>
                <h4 class="mb-0 fw-bold text-dark">Submission Review</h4>
                <p class="text-muted small fw-bold mb-0">
                    <span class="text-primary"><?= htmlspecialchars((string)$assignment['title']) ?></span> • <?= htmlspecialchars((string)$assignment['course_name']) ?>
                </p>
            </div>
        </div>
        <a href="manage_assignments.php" class="btn btn-outline-secondary rounded-pill px-4 fw-bold btn-sm shadow-sm">
            <i class="fas fa-arrow-left me-1"></i> BACK
        </a>
    </div>

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

    <div class="table-card">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th class="ps-4">Student Profile</th>
                        <th>Submission Date</th>
                        <th>Status</th>
                        <th>Evidence</th>
                        <th>Score</th>
                        <th class="text-end pe-4">Grading</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($submissions)): foreach($submissions as $sub): ?>
                    <tr>
                        <td class="ps-4">
                            <div class="fw-bold text-dark" style="font-size: 15px;"><?= htmlspecialchars((string)$sub['student_name']) ?></div>
                            <small class="text-muted fw-bold"><?= htmlspecialchars((string)$sub['student_phone']) ?></small>
                        </td>
                        <td>
                            <div class="small fw-bold text-dark"><?= date('d M, Y', strtotime($sub['submitted_at'])) ?></div>
                            <small class="text-muted"><?= date('h:i A', strtotime($sub['submitted_at'])) ?></small>
                        </td>
                        <td>
                            <span class="status-badge <?= $sub['status'] == 'graded' ? 'status-graded' : 'status-submitted' ?>">
                                <?= ucfirst((string)$sub['status']) ?>
                            </span>
                        </td>
                        <td>
                            <a href="../<?= htmlspecialchars((string)$sub['file_url']) ?>" target="_blank" class="btn-view-file">
                                <i class="fas fa-file-alt me-1 text-danger"></i> VIEW FILE
                            </a>
                        </td>
                        <td>
                            <div class="fw-bold <?= $sub['status'] == 'graded' ? 'text-success' : 'text-muted' ?>" style="font-size: 16px;">
                                <?= $sub['marks'] ?? '--' ?>
                            </div>
                        </td>
                        <td class="text-end pe-4">
                            <button class="btn-grade shadow-sm" onclick="openGradeModal('<?= $sub['id'] ?>', '<?= addslashes((string)$sub['student_name']) ?>', '<?= (string)$sub['marks'] ?>', '<?= addslashes((string)$sub['feedback']) ?>')">
                                <i class="fas fa-pen-nib me-1"></i> GRADE
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="6" class="text-center py-5 text-muted fw-bold">No submissions received yet for this assignment.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="gradeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px;">
            <form method="POST" action="view_submissions.php?assignment_id=<?= $assignment_id ?>">
                <div class="modal-header bg-light border-0" style="border-radius: 20px 20px 0 0;">
                    <h5 class="fw-bold m-0"><i class="fas fa-star text-warning me-2"></i>Evaluate Submission</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <input type="hidden" name="submission_id" id="modal_sub_id">
                    <div class="mb-4 text-center">
                        <p class="text-muted fw-bold mb-1 small text-uppercase">Student Name</p>
                        <h5 id="modal_student_name" class="fw-bold text-dark"></h5>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Score / Marks (e.g. 18/20)</label>
                        <input type="text" name="marks" id="modal_marks" class="form-control border-2 shadow-none py-2" placeholder="Enter score" required>
                    </div>
                    <div class="mb-0">
                        <label class="form-label small fw-bold">Feedback for Student</label>
                        <textarea name="feedback" id="modal_feedback" class="form-control border-2 shadow-none" rows="4" placeholder="Excellent work! Keep improving your Arabic..."></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="update_grade" class="btn btn-dark w-100 py-3 rounded-4 fw-bold shadow">PUBLISH GRADE</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

    // Modal Trigger Function
    function openGradeModal(id, name, marks, feedback) {
        document.getElementById('modal_sub_id').value = id;
        document.getElementById('modal_student_name').innerText = name;
        document.getElementById('modal_marks').value = marks;
        document.getElementById('modal_feedback').value = feedback;
        
        var myModal = new bootstrap.Modal(document.getElementById('gradeModal'));
        myModal.show();
    }
</script>

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