﻿﻿??????????????
﻿﻿??????????????
<?php
   include('session.php');  // Admin session check
?>

<?php
include 'connection.php';  // Adjust path if needed

$edit_mode = false;
$task_data = [];
$existing_files = [];

// Handle edit: Load task data if edit_id is set
if (isset($_GET['edit_id'])) {
    $edit_id = (int)$_GET['edit_id'];
    $edit_mode = true;
    
    // Fetch task details
    $sql = "SELECT * FROM tasks WHERE id = ? AND created_by = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $edit_id, $_SESSION['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $task_data = $result->fetch_assoc();
        
        // Fetch existing files
        $file_sql = "SELECT * FROM task_files WHERE task_id = ?";
        $stmt_file = $conn->prepare($file_sql);
        $stmt_file->bind_param("i", $edit_id);
        $stmt_file->execute();
        $existing_files = $stmt_file->get_result()->fetch_all(MYSQLI_ASSOC);
    } else {
        echo "<script>alert('Task not found or access denied!'); window.location='task_assignment.php';</script>";
        exit;
    }
}

// Handle task creation/update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_task'])) {
    $task_no = mysqli_real_escape_string($conn, $_POST['task_no']);
    $task_name = mysqli_real_escape_string($conn, $_POST['task_name']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $course = mysqli_real_escape_string($conn, $_POST['course']);
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $full_marks = (int)$_POST['full_marks'];
    $status = $_POST['status'];
    $created_by = $_SESSION['id'];
    
    if ($edit_mode) {
        $task_id = (int)$_POST['edit_id'];
        // Update task
        $update_sql = "UPDATE tasks SET task_no=?, task_name=?, description=?, course=?, start_date=?, end_date=?, full_marks=?, status=? WHERE id=? AND created_by=?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("ssssssisii", $task_no, $task_name, $description, $course, $start_date, $end_date, $full_marks, $status, $task_id, $created_by);
        if ($stmt->execute()) {
            // Handle file removals
            if (isset($_POST['remove_files'])) {
                foreach ($_POST['remove_files'] as $file_id) {
                    $file_id = (int)$file_id;
                    $del_sql = "SELECT file_path FROM task_files WHERE id=? AND task_id=?";
                    $stmt_del = $conn->prepare($del_sql);
                    $stmt_del->bind_param("ii", $file_id, $task_id);
                    $stmt_del->execute();
                    $file_row = $stmt_del->get_result()->fetch_assoc();
                    if ($file_row && file_exists($file_row['file_path'])) {
                        unlink($file_row['file_path']);
                    }
                    $del_sql = "DELETE FROM task_files WHERE id=? AND task_id=?";
                    $stmt_del = $conn->prepare($del_sql);
                    $stmt_del->bind_param("ii", $file_id, $task_id);
                    $stmt_del->execute();
                }
            }
            // Handle new file uploads
            $upload_dir = '../uploads/tasks/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            $allowed_types = ['pdf', 'doc', 'docx', 'jpg', 'png'];
            $max_size = 10 * 1024 * 1024;
            
            if (isset($_FILES['task_files'])) {
                foreach ($_FILES['task_files']['name'] as $key => $file_name) {
                    $file_tmp = $_FILES['task_files']['tmp_name'][$key];
                    $file_size = $_FILES['task_files']['size'][$key];
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    
                    if (in_array($file_ext, $allowed_types) && $file_size <= $max_size && !empty($file_name)) {
                        $new_name = $task_id . '_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                        $file_path = $upload_dir . $new_name;
                        if (move_uploaded_file($file_tmp, $file_path)) {
                            $file_insert = "INSERT INTO task_files (task_id, file_name, file_path, file_type) VALUES (?, ?, ?, ?)";
                            $stmt_file = $conn->prepare($file_insert);
                            $stmt_file->bind_param("isss", $task_id, $file_name, $file_path, $file_ext);
                            $stmt_file->execute();
                        }
                    }
                }
            }
            echo "<script>alert('Task updated successfully!'); window.location='task_assignment.php';</script>";
        } else {
            echo "<script>alert('Error updating task!');</script>";
        }
    } else {
        // Check if task_no is unique
        $check_sql = "SELECT id FROM tasks WHERE task_no = ?";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param("s", $task_no);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            echo "<script>alert('Task No already exists!');</script>";
        } else {
            // Insert new task
            $insert_sql = "INSERT INTO tasks (task_no, task_name, description, course, start_date, end_date, full_marks, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("ssssssisi", $task_no, $task_name, $description, $course, $start_date, $end_date, $full_marks, $status, $created_by);
            if ($stmt->execute()) {
                $task_id = $stmt->insert_id;
                
                // Handle file uploads for new task
                $upload_dir = '../uploads/tasks/';
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
                $allowed_types = ['pdf', 'doc', 'docx', 'jpg', 'png'];
                $max_size = 10 * 1024 * 1024;
                
                if (isset($_FILES['task_files'])) {
                    foreach ($_FILES['task_files']['name'] as $key => $file_name) {
                        $file_tmp = $_FILES['task_files']['tmp_name'][$key];
                        $file_size = $_FILES['task_files']['size'][$key];
                        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                        
                        if (in_array($file_ext, $allowed_types) && $file_size <= $max_size && !empty($file_name)) {
                            $new_name = $task_id . '_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                            $file_path = $upload_dir . $new_name;
                            if (move_uploaded_file($file_tmp, $file_path)) {
                                $file_insert = "INSERT INTO task_files (task_id, file_name, file_path, file_type) VALUES (?, ?, ?, ?)";
                                $stmt_file = $conn->prepare($file_insert);
                                $stmt_file->bind_param("isss", $task_id, $file_name, $file_path, $file_ext);
                                $stmt_file->execute();
                            }
                        }
                    }
                }
                echo "<script>alert('Task created successfully!'); window.location='task_assignment.php';</script>";
            } else {
                echo "<script>alert('Error creating task!');</script>";
            }
        }
    }
}

// Handle delete (soft delete)
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    $created_by = $_SESSION['id'];  // Store for debugging
    
    // Debug: Check if session ID is set
    if (!isset($created_by) || empty($created_by)) {
        echo "<script>alert('Session error: User ID not set. Cannot delete.'); window.location='task_assignment.php';</script>";
        exit;
    }
    
    $delete_sql = "UPDATE tasks SET status = 'deleted' WHERE id = ? AND created_by = ?";
    $stmt = $conn->prepare($delete_sql);
    if (!$stmt) {
        echo "<script>alert('Prepare failed: " . $conn->error . "'); window.location='task_assignment.php';</script>";
        exit;
    }
    $stmt->bind_param("ii", $delete_id, $created_by);
    
    if ($stmt->execute()) {
        // Success: Check affected rows to confirm update
        if ($stmt->affected_rows > 0) {
            echo "<script>alert('Task deleted successfully!'); window.location='task_assignment.php';</script>";
        } else {
            echo "<script>alert('No rows affected. Task may not exist or you lack permission. Check created_by match.'); window.location='task_assignment.php';</script>";
        }
    } else {
        echo "<script>alert('Error deleting task: " . $stmt->error . "'); window.location='task_assignment.php';</script>";
    }
    $stmt->close();
}

// Fetch courses for dropdown
$course_sql = "SELECT DISTINCT course FROM students";
$course_result = $conn->query($course_sql);

// Fetch tasks for table
$sql = "SELECT * FROM tasks WHERE status != 'deleted' ORDER BY created_at ASC";
$result = $conn->query($sql);
$a = 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Task Assignment | Admin</title>
    <!-- Favicon icon -->
    <link rel="icon" type="image/png" href="../images/logo-wide.png">
    <!-- Base Styling  -->
    <link rel="stylesheet" href="assets/main/css/fonts.css">
    <link rel="stylesheet" href="assets/main/css/style.css">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <style>
    .btn { background-color: red; border: none; color: white; padding: 5px 5px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; border-radius: 20px; }
    .green { background-color: #199319; }
    .red { background-color: red; }
    .file-input { margin-bottom: 10px; }
    .existing-file { margin: 5px 0; }
    /* Modern button styles */
    .btn-modern {
        border-radius: 8px;
        padding: 10px 20px;
        font-size: 16px;
        font-weight: 500;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .btn-modern:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }
    .btn-add {
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        font-size: 20px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        margin-left: 10px;
        transition: background-color 0.3s ease;
    }
    .btn-add:hover {
        background-color: #0056b3;
    }
    .btn-delete {
        background-color: #dc3545;
        color: white;
        border: none;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        font-size: 14px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        margin-left: 10px;
        transition: background-color 0.3s ease;
    }
    .btn-delete:hover {
        background-color: #c82333;
    }
    .file-row {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    .file-row .form-control {
        flex: 1;
    }
    /* Modern table styles */
    #example1 {
        border-collapse: collapse;
        width: 100%;
        margin-top: 20px;
    }
    #example1 thead th {
        background-color: #f8f9fa;
        color: #495057;
        font-weight: 600;
        padding: 12px;
        border-bottom: 2px solid #dee2e6;
        text-align: left;
    }
    #example1 tbody td {
        padding: 12px;
        border-bottom: 1px solid #dee2e6;
    }
    #example1 tbody tr:hover {
        background-color: #f1f3f4;
    }
    #example1 tbody tr:nth-child(even) {
        background-color: #f8f9fa;
    }
    </style>
</head>

<body>
    <div id="main-wrapper" class="show">
        <?php include "sidebar.php"; ?>
        <?php include "header.php"; ?>

        <div class="content-body">
            <div class="warper container-fluid">
                <div class="new-patients main_container">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title"><?php echo $edit_mode ? 'Edit Task' : 'Create Task'; ?></h4>
                                </div>
                                <div class="card-body">
                                    <form method="POST" enctype="multipart/form-data">
                                        <input type="hidden" name="edit_id" value="<?php echo $edit_mode ? $task_data['id'] : ''; ?>">
                                        
                                        <!-- Task No and Task Name in a single row -->
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Task No</label>
                                                    <input type="text" name="task_no" class="form-control" value="<?php echo $edit_mode ? $task_data['task_no'] : ''; ?>" required>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Task Name</label>
                                                    <input type="text" name="task_name" class="form-control" value="<?php echo $edit_mode ? $task_data['task_name'] : ''; ?>" required>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Description in a single row -->
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <label>Description</label>
                                                    <textarea name="description" class="form-control"><?php echo $edit_mode ? $task_data['description'] : ''; ?></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Course and Full Marks in a single row -->
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Course</label>
                                                    <select name="course" class="form-control" required>
                                                        <option value="">Select Course</option>
                                                        <?php 
                                                        $course_result->data_seek(0); // Reset pointer
                                                        while ($row = $course_result->fetch_assoc()) { 
                                                            $selected = ($edit_mode && $task_data['course'] == $row['course']) ? 'selected' : '';
                                                        ?>
                                                            <option value="<?php echo $row['course']; ?>" <?php echo $selected; ?>><?php echo $row['course']; ?></option>
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Full Marks</label>
                                                    <input type="number" name="full_marks" class="form-control" value="<?php echo $edit_mode ? $task_data['full_marks'] : ''; ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Start Date and End Date in a single row -->
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Start Date</label>
                                                    <input type="date" name="start_date" class="form-control" value="<?php echo $edit_mode ? $task_data['start_date'] : ''; ?>">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>End Date</label>
                                                    <input type="date" name="end_date" class="form-control" value="<?php echo $edit_mode ? $task_data['end_date'] : ''; ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Status and Upload File in a single row -->
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Status</label>
                                                    <select name="status" class="form-control">
                                                        <option value="draft" <?php echo ($edit_mode && $task_data['status'] == 'draft') ? 'selected' : ''; ?>>Draft</option>
                                                        <option value="active" <?php echo ($edit_mode && $task_data['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                                                        <option value="published" <?php echo ($edit_mode && $task_data['status'] == 'published') ? 'selected' : ''; ?>>Published</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label><?php echo $edit_mode ? 'Add More Files' : 'Upload Files'; ?></label>
                                                    <div id="file-container">
                                                        <div class="file-row">
                                                            <input type="file" name="task_files[]" class="form-control file-input" accept=".pdf,.doc,.docx,.jpg,.png">
                                                            <button type="button" class="btn-delete remove-file">×</button>
                                                        </div>
                                                    </div>
                                                    <button type="button" id="add-file" class="btn-add">+</button>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <?php if ($edit_mode && !empty($existing_files)) { ?>
                                        <div class="form-group">
                                            <label>Existing Files (Check to Remove)</label>
                                            <?php foreach ($existing_files as $file) { ?>
                                                <div class="existing-file">
                                                    <input type="checkbox" name="remove_files[]" value="<?php echo $file['id']; ?>"> <?php echo $file['file_name']; ?>
                                                </div>
                                            <?php } ?>
                                        </div>
                                        <?php } ?>
                                        
                                        <button type="submit" name="submit_task" class="btn green btn-modern"><?php echo $edit_mode ? 'Update Task' : 'Create Task'; ?></button>
                                        <?php if ($edit_mode) { ?><a href="task_assignment.php" class="btn red btn-modern">Cancel Edit</a><?php } ?>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-12">
                            <div class="card shadow">
                                <div class="card-header">
                                    <h4 class="card-title">Tasks</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="example1" class="display nowrap">
                                            <thead>
                                                <tr>
                                                    <th>SL No</th>
                                                    <th>Task No</th>
                                                    <th>Task Name</th>
                                                    <th>Course</th>
                                                    <th>Start Date</th>
                                                    <th>End Date</th>
                                                    <th>Full Marks</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($rows = $result->fetch_assoc()) { ?>
                                                <tr>
                                                    <td><?php echo ++$a; ?></td>
                                                    <td><?php echo $rows['task_no']; ?></td>
                                                    <td><?php echo $rows['task_name']; ?></td>
                                                    <td><?php echo $rows['course']; ?></td>
                                                    <td><?php echo $rows['start_date']; ?></td>
                                                    <td><?php echo $rows['end_date']; ?></td>
                                                    <td><?php echo $rows['full_marks']; ?></td>
                                                    <td><?php echo $rows['status']; ?></td>
                                                    <td>
                                                        <a href="?edit_id=<?php echo $rows['id']; ?>" class="btn green btn-modern">Edit</a>
                                                        <a href="?delete_id=<?php echo $rows['id']; ?>" class="btn red btn-modern" onclick="return confirm('Delete?')">Delete</a>
                                                    </td>
                                                </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php include('footer.php'); ?>
    </div>

    <script>
    $(document).ready(function() {
        $('#add-file').click(function() {
            $('#file-container').append('<div class="file-row"><input type="file" name="task_files[]" class="form-control file-input" accept=".pdf,.doc,.docx,.jpg,.png"><button type="button" class="btn-delete remove-file">×</button></div>');
        });
        
        $(document).on('click', '.remove-file', function() {
            $(this).closest('.file-row').remove();
        });
    });

    </script>

    <!-- (Rest of JS from template remains the same) -->
    <script src="assets/plugins/popper/popper.min.js"></script>
    <script src="assets/plugins/bootstrap/js/bootstrap.js"></script>
    <script src="assets/plugins/moment/moment.min.js"></script>
    <script src="assets/plugins/daterangepicker/daterangepicker.min.js"></script>
    <script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
    <script src="assets/js/init-tdatatable.js"></script>
    <script src="assets/plugins/chart/chart/Chart.min.js"></script>
    <script src="assets/js/charts-custom.js"></script>
    <script src="assets/js/toggleFullScreen.js"></script>
    <script src="assets/js/main.js"></script>
</body>

</html>