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

if($_SERVER["REQUEST_METHOD"] == "POST")
{   
    $ID = $_POST["ID"];
    $ass_code = $_POST["ass_code"];
    $profile_pic = $_POST['profile_pic'];
    $my_username = $_POST['my_username'];
    $my_email = $_POST['my_email'];
    $fileCount = count($_FILES['file']['name']);
    $dept = $_SESSION['dept_sess'];

    // Get the current time adn date
    date_default_timezone_set('Asia/Manila');
    $date = date("m/d/Y");
    $time = date("h:i A");
    
    $sql_highest_ID = "SELECT * FROM tasks ORDER BY Code DESC LIMIT 0, 1";
    if($heighest_row = $db->query($sql_highest_ID)){
        if($heighest_row->num_rows > 0){
            while($mem_row = $heighest_row->fetch_array()){
                $code = $mem_row['Code'];
                $code += 1;
            }
        }
        else{
            $code = 1;
        }
    }
    

    for($i=0;$i<$fileCount;$i++){
        $fileName = $_FILES['file']['name'][$i];
        $sql = "INSERT INTO tasks (`Code`, `Assignment_Code`, `Profile_Picture`, `Username`, `Email`, `File_Link`, `File_Status`, `Date_Submitted`, `Time`, `Notif_Status`, `Department`) VALUES ('$code', '$ass_code', '$profile_pic', '$my_username', '$my_email', '$fileName', 'pending', '$date', '$time', 'unread', '$dept')";
        if (mysqli_query($db, $sql)){
            echo '<script>alert("Submitted successfully!");</script>';
            echo '<script>document.location = "view_assignment.php?ID='.$ID.'"</script>';
        }else{
            echo mysqli_error($db);
        }
        move_uploaded_file($_FILES['file']['tmp_name'][$i], '../submitted_files/'.$fileName);
    }
    
}
?>