<?php 
// Advanced Debugging & Config
ini_set('display_errors', 1); error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
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 Redirect Messages (Prevents Resubmission on Reload)
if(isset($_GET['msg'])) {
    if($_GET['msg'] == 'added') $success_msg = "New assignment posted successfully!";
    elseif($_GET['msg'] == 'updated') $success_msg = "Assignment updated successfully!";
    elseif($_GET['msg'] == 'deleted') $success_msg = "Assignment removed successfully!";
    elseif($_GET['msg'] == 'error') $error_msg = "Something went wrong! Please try again.";
}

// ==========================================
// 1. DELETE LOGIC (With Redirect Fix)
// ==========================================
if (isset($_GET['delete_id'])) {
    try {
        $pdo->prepare("DELETE FROM assignments WHERE id = ?")->execute([$_GET['delete_id']]);
        echo "<script>window.location.href='manage_assignments.php?msg=deleted';</script>"; exit;
    } catch (Exception $e) { 
        echo "<script>window.location.href='manage_assignments.php?msg=error';</script>"; exit; 
    }
}

// ==========================================
// 2. ADD / EDIT LOGIC (With Redirect Fix)
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $course_id = (int)$_POST['course_id'];
    $title = trim($_POST['title']);
    $desc = trim($_POST['description']);
    $deadline = $_POST['deadline'];

    try {
        if (isset($_POST['add_assignment'])) {
            $stmt = $pdo->prepare("INSERT INTO assignments (course_id, title, description, deadline) VALUES (?, ?, ?, ?)");
            $stmt->execute([$course_id, $title, $desc, $deadline]);
            echo "<script>window.location.href='manage_assignments.php?msg=added';</script>"; exit;
        } elseif (isset($_POST['edit_assignment'])) {
            $stmt = $pdo->prepare("UPDATE assignments SET course_id=?, title=?, description=?, deadline=? WHERE id=?");
            $stmt->execute([$course_id, $title, $desc, $deadline, $_POST['assignment_id']]);
            echo "<script>window.location.href='manage_assignments.php?msg=updated';</script>"; exit;
        }
    } catch (Exception $e) { 
        echo "<script>window.location.href='manage_assignments.php?msg=error';</script>"; exit; 
    }
}

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

// Data Fetching
$courses = $pdo->query("SELECT id, title FROM courses WHERE status='active'")->fetchAll(PDO::FETCH_ASSOC);
$assignments = $pdo->query("
    SELECT a.*, c.title as course_name, 
    (SELECT COUNT(*) FROM assignment_submissions WHERE assignment_id = a.id) as total_submissions
    FROM assignments a 
    JOIN courses c ON a.course_id = c.id 
    ORDER BY a.deadline DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<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 Menu */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 30px; 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 */
    .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; }
    
    /* Badges & Icons */
    .sub-count { background: #e0f2fe; color: #0369a1; padding: 6px 14px; border-radius: 50px; font-weight: 800; font-size: 11px; text-decoration: none; transition: 0.3s; display: inline-flex; align-items: center; border: 1px solid #bae6fd; }
    .sub-count:hover { background: #0369a1; color: #fff; transform: translateY(-2px); }
    .sub-count.has-subs { background: #ecfdf5; color: #059669; border-color: #a7f3d0; }
    .sub-count.has-subs:hover { background: #059669; color: #fff; }

    /* 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); }

    /* Modals & Inputs */
    .modal-content { border-radius: 24px; border: none; box-shadow: 0 20px 50px rgba(0,0,0,0.1); }
    .modal-header { border-bottom: 1px solid #f1f5f9; padding: 20px 30px; }
    .form-control, .form-select { border-radius: 12px; border: 2px solid #f1f5f9; padding: 12px 15px; font-size: 14px; background: #f8fafc; transition: 0.3s; }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }

    /* 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) */
    .assignment-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%; }
        .header-title { font-size: 1.2rem; }
    }
    @media (min-width: 992px) { #sidebarToggle { display: none !important; } }
</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-tasks me-2" style="color: var(--theme-gold);"></i> Assignments Desk</h4>
                <p class="text-muted fw-semibold mb-0 d-none d-md-block" style="font-size: 13px;">Create assignments and monitor student submissions</p>
            </div>
        </div>
        <button class="btn-theme shadow-sm mt-3 mt-md-0" data-bs-toggle="modal" data-bs-target="#addAssignmentModal">
            <i class="fas fa-plus-circle me-2"></i> Post Assignment
        </button>
    </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">Assignment Topic & Course</th>
                        <th>Deadline & Timing</th>
                        <th class="text-center">Submission Status</th>
                        <th class="text-end pe-4">Management</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($assignments)): foreach($assignments as $task): 
                        $is_late = strtotime($task['deadline']) < time();
                    ?>
                    <tr>
                        <td class="ps-4 py-3">
                            <div class="fw-bold text-dark mb-1" style="font-size: 15px;"><i class="fas fa-file-signature text-muted me-2"></i> <?= htmlspecialchars($task['title']) ?></div>
                            <span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill" style="font-size: 10px; padding: 4px 10px;">
                                <i class="fas fa-book me-1"></i> <?= htmlspecialchars($task['course_name']) ?>
                            </span>
                        </td>
                        <td>
                            <div class="fw-bold <?= $is_late ? 'text-danger' : 'text-dark' ?> mb-1" style="font-size: 14px;">
                                <i class="far fa-calendar-alt me-1"></i> <?= date('d M, Y', strtotime($task['deadline'])) ?>
                                <?php if($is_late): ?> <span class="badge bg-danger-subtle text-danger ms-1 border border-danger-subtle" style="font-size: 9px;">Overdue</span> <?php endif; ?>
                            </div>
                            <small class="text-muted fw-bold"><i class="far fa-clock me-1"></i> <?= date('h:i A', strtotime($task['deadline'])) ?></small>
                        </td>
                        <td class="text-center">
                            <a href="view_submissions.php?assignment_id=<?= $task['id'] ?>" class="sub-count <?= $task['total_submissions'] > 0 ? 'has-subs' : '' ?> shadow-sm">
                                <i class="fas fa-file-import me-1"></i> <?= $task['total_submissions'] ?> Submissions
                            </a>
                        </td>
                        <td class="text-end pe-4">
                            <button type="button" class="act-btn act-edit shadow-sm" title="Edit" onclick="editTask(<?= $task['id'] ?>, <?= $task['course_id'] ?>, '<?= htmlspecialchars(addslashes($task['title'])) ?>', '<?= htmlspecialchars(addslashes(preg_replace('/\r|\n/', '\\n', $task['description']))) ?>', '<?= date('Y-m-d\TH:i', strtotime($task['deadline'])) ?>')">
                                <i class="fas fa-pen"></i>
                            </button>
                            <a href="manage_assignments.php?delete_id=<?= $task['id'] ?>" class="act-btn act-delete shadow-sm" onclick="return confirm('Wait! This will delete all student submissions for this assignment too. Continue?')" title="Delete">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted fw-bold"><i class="fas fa-tasks fa-3x mb-3 opacity-25 d-block"></i> No active assignments found.</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($assignments)): foreach($assignments as $task): 
                $is_late = strtotime($task['deadline']) < time();
            ?>
            <div class="col-12">
                <div class="assignment-mobile-card p-3">
                    <div class="mb-3 pb-3 border-bottom">
                        <h6 class="fw-bold text-dark mb-2" style="font-size: 15px;"><i class="fas fa-file-signature text-primary me-2"></i> <?= htmlspecialchars($task['title']) ?></h6>
                        <span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill" style="font-size: 10px; padding: 4px 10px;">
                            <i class="fas fa-book me-1"></i> <?= htmlspecialchars($task['course_name']) ?>
                        </span>
                    </div>
                    
                    <div class="bg-light p-3 rounded-3 border mb-3">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-muted fw-bold text-uppercase" style="font-size: 10px;">Deadline</span>
                            <?php if($is_late): ?> <span class="badge bg-danger-subtle text-danger border border-danger-subtle" style="font-size: 9px;">Overdue</span> <?php endif; ?>
                        </div>
                        <div class="fw-bold <?= $is_late ? 'text-danger' : 'text-dark' ?>" style="font-size: 13px;">
                            <i class="far fa-calendar-alt me-1"></i> <?= date('d M, Y', strtotime($task['deadline'])) ?> &bull; <i class="far fa-clock ms-1"></i> <?= date('h:i A', strtotime($task['deadline'])) ?>
                        </div>
                    </div>

                    <a href="view_submissions.php?assignment_id=<?= $task['id'] ?>" class="btn w-100 mb-3 fw-bold shadow-sm <?= $task['total_submissions'] > 0 ? 'btn-success' : 'btn-outline-primary border-2 bg-light' ?>" style="font-size: 13px; border-radius: 10px;">
                        <i class="fas fa-file-import me-2"></i> View <?= $task['total_submissions'] ?> Submissions
                    </a>
                    
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-light border flex-grow-1 fw-bold text-success" style="font-size: 12px; padding: 10px;" onclick="editTask(<?= $task['id'] ?>, <?= $task['course_id'] ?>, '<?= htmlspecialchars(addslashes($task['title'])) ?>', '<?= htmlspecialchars(addslashes(preg_replace('/\r|\n/', '\\n', $task['description']))) ?>', '<?= date('Y-m-d\TH:i', strtotime($task['deadline'])) ?>')"><i class="fas fa-pen me-2"></i> Edit</button>
                        <a href="manage_assignments.php?delete_id=<?= $task['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-danger" style="font-size: 12px; padding: 10px;" onclick="return confirm('Delete this assignment completely?');"><i class="fas fa-trash-alt me-2"></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-tasks fa-3x text-muted opacity-25 mb-3 d-block"></i>
                    <h6 class="fw-bold text-muted">No assignments found!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<div class="modal fade" id="addAssignmentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <form action="manage_assignments.php" method="POST">
                <div class="modal-header bg-light">
                    <h5 class="fw-bold m-0 text-dark"><i class="fas fa-paper-plane text-success me-2"></i>Post New Assignment</h5>
                    <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4 row g-4">
                    <div class="col-md-7">
                        <label class="form-label small fw-bold text-uppercase text-muted">Targeted Course <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-book"></i></span>
                            <select name="course_id" class="form-select border-start-0 ps-0 fw-bold text-dark" required>
                                <option value="">-- Choose Course --</option>
                                <?php foreach($courses as $c): ?>
                                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['title']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label small fw-bold text-uppercase text-muted">Submission Deadline <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-calendar-alt"></i></span>
                            <input type="datetime-local" name="deadline" class="form-control border-start-0 ps-0 fw-bold" required>
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Assignment Headline <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-heading"></i></span>
                            <input type="text" name="title" class="form-control border-start-0 ps-0 fw-bold" placeholder="E.g. Write 10 Arabic Sentences" required>
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Description / Guidelines (Optional)</label>
                        <textarea name="description" class="form-control border-2 shadow-none p-3" rows="4" placeholder="Write any specific rules or instructions for students..."></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="add_assignment" class="btn btn-theme w-100 py-3 shadow-sm">PUBLISH ASSIGNMENT</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editAssignmentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <form action="manage_assignments.php" method="POST">
                <input type="hidden" name="assignment_id" id="edit_id">
                <div class="modal-header bg-light">
                    <h5 class="fw-bold m-0 text-dark"><i class="fas fa-pen-nib text-warning me-2"></i>Modify Assignment</h5>
                    <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4 row g-4">
                    <div class="col-md-7">
                        <label class="form-label small fw-bold text-uppercase text-muted">Targeted Course <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-book"></i></span>
                            <select name="course_id" id="edit_course" class="form-select border-start-0 ps-0 fw-bold text-dark" required>
                                <?php foreach($courses as $c): ?>
                                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['title']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label small fw-bold text-uppercase text-muted">New Deadline <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-calendar-alt"></i></span>
                            <input type="datetime-local" name="deadline" id="edit_deadline" class="form-control border-start-0 ps-0 fw-bold" required>
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Headline <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-heading"></i></span>
                            <input type="text" name="title" id="edit_title" class="form-control border-start-0 ps-0 fw-bold" required>
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Description</label>
                        <textarea name="description" id="edit_desc" class="form-control border-2 shadow-none p-3" rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="edit_assignment" class="btn btn-dark w-100 py-3 rounded-4 fw-bold shadow-sm" style="background: var(--theme-dark);">UPDATE ASSIGNMENT</button>
                </div>
            </form>
        </div>
    </div>
</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'); }
            });
        }
    });

    // Populate Edit Modal Function
    function editTask(id, course, title, desc, deadline) {
        document.getElementById('edit_id').value = id;
        document.getElementById('edit_course').value = course;
        document.getElementById('edit_title').value = title;
        document.getElementById('edit_desc').value = desc;
        document.getElementById('edit_deadline').value = deadline;
        
        new bootstrap.Modal(document.getElementById('editAssignmentModal')).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'; ?>