<?php
session_start();
include('connection.php');

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data and sanitize it
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $group = mysqli_real_escape_string($conn, $_POST['group']);
    $platform = mysqli_real_escape_string($conn, $_POST['platefrom']); // Typo: should be 'platform' instead of 'platefrom'
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $url = mysqli_real_escape_string($conn, $_POST['url']);
    $pdf = mysqli_real_escape_string($conn, $_POST['pdf']);
    $audio = mysqli_real_escape_string($conn, $_POST['audio']);
    $video = mysqli_real_escape_string($conn, $_POST['video']);
    $image = mysqli_real_escape_string($conn, $_POST['image']);
    $msg = mysqli_real_escape_string($conn, $_POST['msg']);
    $emp_id = $_SESSION['emp_id'];
    $currentDateTime = date('Y-m-d H:i:s');

    // Check if a record with the same title and employee_id already exists
    $checkQuery = "SELECT * FROM update_all_task WHERE title = '$title' AND employee_id = '$emp_id'";
    $checkResult = $conn->query($checkQuery);

    if ($checkResult->num_rows > 0) {

        // echo "Duplicate entry: This task already exists.";
        header("Location: user_active_task.php?error=This task already exists!!!");

    } else {
        // Create an SQL insert query
        $sql = "INSERT INTO update_all_task (title, `group`, platefrom, description, url, pdf, audio, video, image, `msg`, employee_id, datetime)
        VALUES ('$title', '$group', '$platform', '$description', '$url', '$pdf', '$audio', '$video', '$image', 'done', '$emp_id', '$currentDateTime')";

        // Execute the query
        if ($conn->query($sql) === TRUE) {

            // echo "Record inserted successfully!";
            header("Location:user_active_task.php?success = Record inserted successfully!!!");

        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    }

    // Close the database connection
    $conn->close();
}
?>