<?php
include('config.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{   
    $ID = $_POST["ID"];
    $sql_assign2 = mysqli_query($db, "SELECT * FROM requirements WHERE ID='$ID'");
        while($DB_ROW2 = mysqli_fetch_array($sql_assign2)) {
            $att_fl = $DB_ROW2["Attached_File"];
        }
    $title = $_POST["title"];
    $instructions = $_POST["instructions"];
    $due_date = $_POST['due_date'];
    $converted_due_date = date("m-d-Y", strtotime($due_date));
    $due_time = $_POST["due_time"];
    $converted_due_time = date("h:i A", strtotime($due_time));

    if(isset($_FILES['file']['name'])){
        $fileCount = count($_FILES['file']['name']);
    }
    else{
        $fileCount = 0;
    }

    if($converted_due_date == "01-01-1970" || $converted_due_date == ""){
        $converted_due_date = "None";
        $converted_due_time = "None";
    }
    if($instructions == ""){
        $instructions = "None";
    }

    // Get the current time adn date
    date_default_timezone_set('Asia/Manila');
    $date = date("m-d-Y");
    $time = date("h:i A");
    
    for($i=0;$i<$fileCount;$i++){
        $fileName = $_FILES['file']['name'][$i];
        if($fileName == ""){
            $fileName = "None";
        }
        if($fileName != $att_fl && $fileCount != 0){
        move_uploaded_file($_FILES['file']['tmp_name'][$i], 'attached_files/'.$fileName);
        }
    }

    if($fileCount >= 1){
        $a = "`Attached_File`='$fileName',";
    }
    else{
        $a = "";
    }
    $sql = "UPDATE requirements SET `Title`='$title', `Instructions`='$instructions', `Due_Date`='$converted_due_date', `Due_Time`='$converted_due_time', $a `Date_Posted`='$date', `Time_Posted`='$time' WHERE ID='$ID'";
        if (mysqli_query($db, $sql)){
            echo '<script>alert("Updated successfully!");</script>';
            echo '<script>document.location = "assignments.php"</script>';
        }else{
            echo mysqli_error($db);
        }
    
}
?>