<?php
require_once 'config/session.php';
require_once 'config/database.php';
require_once 'config/functions.php';
checkLogin();

$database = new Database();
$conn = $database->getConnection();
$currentUser = getCurrentUser();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_assignment'])) {
    // Validate and sanitize input
    $id_mapel = sanitizeInput($_POST['id_mapel']);
    $judul_tugas = sanitizeInput($_POST['judul_tugas']);
    $deskripsi = sanitizeInput($_POST['deskripsi']);
    $tanggal_mulai = sanitizeInput($_POST['tanggal_mulai']);
    $tanggal_selesai = sanitizeInput($_POST['tanggal_selesai']);
    $jenis = sanitizeInput($_POST['jenis']);
    
    // Validate required fields
    if (empty($id_mapel) || empty($judul_tugas) || empty($tanggal_mulai) || empty($tanggal_selesai) || empty($jenis)) {
        $error = "Semua field wajib diisi!";
    } elseif ($tanggal_selesai < $tanggal_mulai) {
        $error = "Tanggal selesai harus setelah tanggal mulai!";
    } elseif (empty($currentUser['id_kelas'])) {
        $error = "Anda belum memiliki kelas yang ditugaskan. Silakan hubungi administrator.";
    } else {
        try {
            // Insert assignment into database
            $query = "INSERT INTO tugas (id_guru, id_mapel, id_kelas, judul_tugas, deskripsi, tanggal_mulai, tanggal_selesai, jenis) 
                      VALUES (:id_guru, :id_mapel, :id_kelas, :judul_tugas, :deskripsi, :tanggal_mulai, :tanggal_selesai, :jenis)";
            
            $stmt = $conn->prepare($query);
            $stmt->bindParam(':id_guru', $currentUser['id_guru']);
            $stmt->bindParam(':id_mapel', $id_mapel);
            $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
            $stmt->bindParam(':judul_tugas', $judul_tugas);
            $stmt->bindParam(':deskripsi', $deskripsi);
            $stmt->bindParam(':tanggal_mulai', $tanggal_mulai);
            $stmt->bindParam(':tanggal_selesai', $tanggal_selesai);
            $stmt->bindParam(':jenis', $jenis);
            
            if ($stmt->execute()) {
                $success = "Tugas berhasil ditambahkan!";
                // Refresh the page to show the new assignment
                header("Location: tugas.php");
                exit();
            } else {
                $error = "Gagal menambahkan tugas. Silakan coba lagi.";
            }
        } catch (PDOException $e) {
            $error = "Terjadi kesalahan: " . $e->getMessage();
        }
    }
}

// Get subjects
$query = "SELECT * FROM mata_pelajaran ORDER BY nama_mapel ASC";
$stmt = $conn->prepare($query);
$stmt->execute();
$subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get assignments
$assignments = [];
if ($currentUser['id_kelas']) {
    $query = "SELECT t.*, m.nama_mapel, m.kode_mapel 
              FROM tugas t 
              JOIN mata_pelajaran m ON t.id_mapel = m.id_mapel 
              WHERE t.id_kelas = :id_kelas 
              ORDER BY t.tanggal_mulai DESC";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':id_kelas', $currentUser['id_kelas']);
    $stmt->execute();
    $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tugas - Sistem Guru Kelas SD</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-50">
    <!-- Navigation -->
    <?php require_once 'includes/navbar.php'; ?>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Error/Success Messages -->
        <?php if (isset($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?= $error ?></span>
            </div>
        <?php endif; ?>
        
        <?php if (isset($success)): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?= $success ?></span>
            </div>
        <?php endif; ?>

        <!-- Header -->
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-800">Tugas Siswa</h1>
            <button onclick="openModal()" class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition">
                <i class="fas fa-plus mr-2"></i>Tambah Tugas
            </button>
        </div>

        <!-- Add Assignment Modal -->
        <div id="addModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full">
            <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Tambah Tugas Baru</h3>
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="add_assignment" value="1">
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Mata Pelajaran</label>
                                <select name="id_mapel" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    <option value="">Pilih Mata Pelajaran</option>
                                    <?php foreach ($subjects as $subject): ?>
                                        <option value="<?= $subject['id_mapel'] ?>"><?= htmlspecialchars($subject['nama_mapel']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Judul Tugas</label>
                                <input type="text" name="judul_tugas" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-gray-700">Deskripsi</label>
                                <textarea name="deskripsi" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Tanggal Mulai</label>
                                <input type="date" name="tanggal_mulai" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Tanggal Selesai</label>
                                <input type="date" name="tanggal_selesai" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Jenis Tugas</label>
                                <select name="jenis" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    <option value="harian">Harian</option>
                                    <option value="mingguan">Mingguan</option>
                                    <option value="bulanan">Bulanan</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4">
                            <button type="button" onclick="closeModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                                Batal
                            </button>
                            <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700">
                                Simpan
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Assignments List -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Daftar Tugas</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Mata Pelajaran</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Judul Tugas</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Mulai</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Selesai</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Jenis</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($assignments as $index => $assignment): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= $index + 1 ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= htmlspecialchars($assignment['nama_mapel']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?= htmlspecialchars($assignment['judul_tugas']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= formatDate($assignment['tanggal_mulai']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= formatDate($assignment['tanggal_selesai']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?= ucfirst($assignment['jenis']) ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <a href="detail_tugas.php?id=<?= $assignment['id_tugas'] ?>" class="text-indigo-600 hover:text-indigo-900 mr-2">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="edit_tugas.php?id=<?= $assignment['id_tugas'] ?>" class="text-green-600 hover:text-green-900 mr-2">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <button onclick="deleteAssignment(<?= $assignment['id_tugas'] ?>)" class="text-red-600 hover:text-red-900">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        function openModal() {
            document.getElementById('addModal').classList.remove('hidden');
        }
        
        function closeModal() {
            document.getElementById('addModal').classList.add('hidden');
        }
        
        function deleteAssignment(id) {
            if (confirm('Apakah Anda yakin ingin menghapus tugas ini?')) {
                window.location.href = 'delete_tugas.php?id=' + id;
            }
        }
    </script>
</body>
</html>
