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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $userID = $_SESSION['userID'];

    // Extract all the submitted fields as arrays
    $tentryDates = $_POST['tentryDate'];
    $clients = $_POST['client'];
    $projects = $_POST['project'];
    $milestones = $_POST['milestone'];
    $hours = $_POST['hrs'];
    $descriptions = $_POST['descp'];

    // Create a prepared statement
    $insertQuery = "INSERT INTO timesheet (userID, clientID, projectID, milestoneID, tentryDate, hrs, descp, leaveDays) VALUES (?, ?, ?, ?, ?, ?, ?, 0)";
    
    // Prepare the statement
    $stmt = mysqli_prepare($conn, $insertQuery);

    if (!$stmt) {
        // Error occurred while preparing the statement
        echo "Error: " . mysqli_error($conn);
    } else {
        // Bind parameters and insert data using a loop
        foreach ($tentryDates as $key => $tentryDate) {
            $clientID = $clients[$key];
            $projectID = $projects[$key];
            $milestoneID = $milestones[$key];
            $hrs = $hours[$key];
            $descp = $descriptions[$key];

            // Bind parameters
            mysqli_stmt_bind_param($stmt, "iiissds", $userID, $clientID, $projectID, $milestoneID, $tentryDate, $hrs, $descp);

            // Execute the statement
            if (!mysqli_stmt_execute($stmt)) {
                // Error occurred, handle accordingly (e.g., log the error)
                echo "Error: " . mysqli_error($conn);
            }
        }

        // Close the statement
        mysqli_stmt_close($stmt);

        // Close the database connection
        mysqli_close($conn);

        // Redirect to the timesheet page or display a success message
        header('Location: timesheet.php');
    }
}
?>