<?php
session_start();
require_once '../config/database.php';
require_once '../includes/sidebar_layout.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Check if assignment ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: assignments.php');
    exit();
}

$assignment_id = $_GET['id'];

// Fetch assignment details
try {
    $stmt = $pdo->prepare("
        SELECT a.*, c.name as class_name, c.section as class_section, s.name as subject_name 
        FROM assignments a
        JOIN classes c ON a.class_id = c.id
        JOIN subjects s ON a.subject_id = s.id
        WHERE a.id = ?
    ");
    $stmt->execute([$assignment_id]);
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$assignment) {
        header('Location: assignments.php');
        exit();
    }
    
    // Fetch classes and subjects for dropdowns
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->query("SELECT id, name FROM subjects WHERE status = 'active' ORDER BY name");
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    error_log("Error fetching assignment: " . $e->getMessage());
    header('Location: assignments.php');
    exit();
}

// Handle form submission for updating assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $class_id = $_POST['class_id'] ?? '';
        $subject_id = $_POST['subject_id'] ?? '';
        $due_date = $_POST['due_date'] ?? '';
        $max_marks = $_POST['max_marks'] ?? 20;
        $instructions = $_POST['instructions'] ?? '';
        $status = $_POST['status'] ?? 'published';
        
        // Validate required fields
        if (empty($title) || empty($class_id) || empty($subject_id) || empty($due_date)) {
            $error_message = 'Title, class, subject, and due date are required';
        } else {
            // Update assignment in database
            $stmt = $pdo->prepare("
                UPDATE assignments 
                SET title = ?, description = ?, class_id = ?, subject_id = ?, due_date = ?, max_marks = ?, instructions = ?, status = ?
                WHERE id = ?
            ");
            
            $result = $stmt->execute([
                $title,
                $description,
                $class_id,
                $subject_id,
                $due_date,
                $max_marks,
                $instructions,
                $status,
                $assignment_id
            ]);
            
            if ($result) {
                $success_message = 'Assignment updated successfully';
                // Refresh assignment data
                $stmt = $pdo->prepare("
                    SELECT a.*, c.name as class_name, c.section as class_section, s.name as subject_name 
                    FROM assignments a
                    JOIN classes c ON a.class_id = c.id
                    JOIN subjects s ON a.subject_id = s.id
                    WHERE a.id = ?
                ");
                $stmt->execute([$assignment_id]);
                $assignment = $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                $error_message = 'Failed to update assignment';
            }
        }
    } catch (Exception $e) {
        error_log("Error updating assignment: " . $e->getMessage());
        $error_message = 'Error updating assignment: ' . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অ্যাসাইনমেন্ট সম্পাদনা - অনলাইন শিক্ষা</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .assignment-card {
            border-radius: 15px;
            overflow: hidden;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .assignment-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .assignment-header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 20px;
        }
        
        .assignment-body {
            padding: 20px;
        }
        
        .assignment-footer {
            background-color: #f8f9fa;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
        }
        
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-submitted {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-graded {
            background-color: #d1ecf1;
            color: #0c5460;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="sidebar-container">
        <?php echo renderSidebar('online_learning/assignments.php', $user_role, $user_name); ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-edit me-2"></i>
                    অ্যাসাইনমেন্ট সম্পাদনা
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / অনলাইন শিক্ষা / অ্যাসাইনমেন্ট / সম্পাদনা
                </p>
            </div>
            
            <!-- Content Body -->
            <div class="content-body">
                <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
                <?php endif; ?>
                
                <?php if (isset($success_message)): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-edit me-2"></i>
                                    অ্যাসাইনমেন্ট সম্পাদনা
                                </h5>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <div class="mb-3">
                                        <label class="form-label">অ্যাসাইনমেন্টের শিরোনাম</label>
                                        <input type="text" class="form-control" name="title" placeholder="অ্যাসাইনমেন্টের শিরোনাম লিখুন" value="<?php echo htmlspecialchars($assignment['title']); ?>" required>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">বিষয়</label>
                                                <select class="form-select" name="subject_id" required>
                                                    <option value="">বিষয় নির্বাচন করুন</option>
                                                    <?php foreach ($subjects as $subject): ?>
                                                        <option value="<?php echo $subject['id']; ?>" <?php echo ($subject['id'] == $assignment['subject_id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($subject['name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">ক্লাস</label>
                                                <select class="form-select" name="class_id" required>
                                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?php echo $class['id']; ?>" <?php echo ($class['id'] == $assignment['class_id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">বর্ণনা</label>
                                        <textarea class="form-control" name="description" rows="4" placeholder="অ্যাসাইনমেন্টের বর্ণনা লিখুন"><?php echo htmlspecialchars($assignment['description']); ?></textarea>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">জমা দেওয়ার শেষ তারিখ</label>
                                                <input type="datetime-local" class="form-control" name="due_date" value="<?php echo date('Y-m-d\TH:i', strtotime($assignment['due_date'])); ?>" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">মোট নম্বর</label>
                                                <input type="number" class="form-control" name="max_marks" placeholder="মোট নম্বর লিখুন" value="<?php echo htmlspecialchars($assignment['max_marks']); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">নির্দেশাবলী</label>
                                        <textarea class="form-control" name="instructions" rows="3" placeholder="ছাত্র-ছাত্রীদের জন্য নির্দেশাবলী"><?php echo htmlspecialchars($assignment['instructions']); ?></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">অবস্থা</label>
                                        <select class="form-select" name="status">
                                            <option value="draft" <?php echo ($assignment['status'] == 'draft') ? 'selected' : ''; ?>>খসড়া</option>
                                            <option value="published" <?php echo ($assignment['status'] == 'published') ? 'selected' : ''; ?>>প্রকাশিত</option>
                                            <option value="closed" <?php echo ($assignment['status'] == 'closed') ? 'selected' : ''; ?>>বন্ধ</option>
                                        </select>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save me-2"></i>
                                        হালনাগাদ করুন
                                    </button>
                                    <a href="assignments.php" class="btn btn-secondary">
                                        <i class="fas fa-arrow-left me-2"></i>
                                        ফিরে যান
                                    </a>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-info-circle me-2"></i>
                                    অ্যাসাইনমেন্ট তথ্য
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <strong>শিরোনাম:</strong>
                                    <p><?php echo htmlspecialchars($assignment['title']); ?></p>
                                </div>
                                
                                <div class="mb-3">
                                    <strong>বিষয়:</strong>
                                    <p><?php echo htmlspecialchars($assignment['subject_name']); ?></p>
                                </div>
                                
                                <div class="mb-3">
                                    <strong>ক্লাস:</strong>
                                    <p><?php echo htmlspecialchars($assignment['class_name'] . ' - ' . $assignment['class_section']); ?></p>
                                </div>
                                
                                <div class="mb-3">
                                    <strong>জমা দেওয়ার শেষ তারিখ:</strong>
                                    <p><?php echo date('d F, Y h:i A', strtotime($assignment['due_date'])); ?></p>
                                </div>
                                
                                <div class="mb-3">
                                    <strong>অবস্থা:</strong>
                                    <p>
                                        <?php 
                                        $status_text = '';
                                        $status_class = '';
                                        switch ($assignment['status']) {
                                            case 'draft':
                                                $status_text = 'খসড়া';
                                                $status_class = 'status-pending';
                                                break;
                                            case 'published':
                                                $status_text = 'প্রকাশিত';
                                                $status_class = 'status-pending';
                                                break;
                                            case 'closed':
                                                $status_text = 'বন্ধ';
                                                $status_class = 'status-graded';
                                                break;
                                        }
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                    </p>
                                </div>
                                
                                <div class="mb-3">
                                    <strong>তৈরির তারিখ:</strong>
                                    <p><?php echo date('d F, Y h:i A', strtotime($assignment['created_at'])); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>