<?php
include('includes/header.php'); // Include your database connection file

// Check if the user is logged in
session_start();
if (!isset($_SESSION['userID'])) {
    header('Location: login.php'); // Redirect to the login page if the user is not logged in
    exit();
}

// Get the logged-in user's ID
$userID = $_SESSION['userID'];

// Calculate the start and end dates for the previous month
$firstDayOfPreviousMonth = date('Y-m-01', strtotime('first day of previous month'));
$lastDayOfPreviousMonth = date('Y-m-t', strtotime('last day of previous month'));

// Query to calculate the total DL for the selected user and previous month
$query = "SELECT SUM(timesheet.hrs * users.employeeRate / 8) AS totalDL
          FROM timesheet
          INNER JOIN users ON timesheet.userID = users.userID
          WHERE timesheet.userID = '$userID'
          AND timesheet.tentryDate >= '$firstDayOfPreviousMonth'
          AND timesheet.tentryDate <= '$lastDayOfPreviousMonth'";

$result = mysqli_query($conn, $query);

if (!$result) {
    die("Query failed: " . mysqli_error($conn));
}

// Fetch the total DL value
$totalDL = 0;
if ($row = mysqli_fetch_assoc($result)) {
    $totalDL = $row['totalDL'];
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Total Direct Labour</title>
</head>
<body>
    <h1>Total Direct Labour for the Previous Month</h1>

    <!-- Display the total DL for the previous month -->
    <p>Total Direct Labour: <?php echo number_format($totalDL, 2); ?></p>
</body>
</html>