<?php
include("connection.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['id'];
    $title = $_POST['title'];
    $platform = $_POST['platform'];
    $url = $_POST['url'];
    $task_discription = $_POST['discription'];
    $assign_task = $_POST['assign_task'];

    // File upload directory
    $upload_dir = "uploads/";

    // Handle video file upload
    $video_file = $_FILES['video_file'];
    $video_file_path = '';
    if (!empty($video_file['name'])) {
        $video_file_name = $video_file['name'];
        $video_file_path = $upload_dir . $video_file_name;
        move_uploaded_file($video_file['tmp_name'], $video_file_path);
    }

    // Handle image file upload
    $image_file = $_FILES['image_file'];
    $image_file_path = '';
    if (!empty($image_file['name'])) {
        $image_file_name = $image_file['name'];
        $image_file_path = $upload_dir . $image_file_name;
        move_uploaded_file($image_file['tmp_name'], $image_file_path);
    }

    // Handle audio file upload
    $audio_file = $_FILES['audio_file'];
    $audio_file_path = '';
    if (!empty($audio_file['name'])) {
        $audio_file_name = $audio_file['name'];
        $audio_file_path = $upload_dir . $audio_file_name;
        move_uploaded_file($audio_file['tmp_name'], $audio_file_path);
    }

    // Handle PDF file upload
    $pdf_file = $_FILES['pdf_file'];
    $pdf_file_path = '';
    if (!empty($pdf_file['name'])) {
        $pdf_file_name = $pdf_file['name'];
        $pdf_file_path = $upload_dir . $pdf_file_name;
        move_uploaded_file($pdf_file['tmp_name'], $pdf_file_path);
    }

    // Update the task in the database
    $update_query = "UPDATE add_project SET
        title = '$title',
        platform = '$platform',
        url = '$url',
        task_discription = '$task_discription',
        assign_task = '$assign_task'";

    if (!empty($video_file_path)) {
        $update_query .= ", video = '$video_file_path'";
    }

    if (!empty($image_file_path)) {
        $update_query .= ", image = '$image_file_path'";
    }

    if (!empty($audio_file_path)) {
        $update_query .= ", audio = '$audio_file_path'";
    }

    if (!empty($pdf_file_path)) {
        $update_query .= ", pdf = '$pdf_file_path'";
    }

    $update_query .= " WHERE id = $id";

    if (mysqli_query($conn, $update_query)) {
        header("Location: view-all-projects.php?success=Project Updated successfully!!!!");
        exit(); // Exit to prevent further script execution
    } else {
        // Error occurred while updating
        echo "Error updating task: " . mysqli_error($conn);
    }

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