<?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'));

// Define an array of excluded client IDs
$excludedClientIDs = array(27, 72, 436);

// Create a string of excluded client IDs for the SQL query
$excludedClientIDsString = implode(',', $excludedClientIDs);

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

$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'];
}

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

$DLresult = mysqli_query($conn, $DLquery);

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

// Fetch the total DL value
$totalcumDL = 0;
if ($row = mysqli_fetch_assoc($DLresult)) {
    $totalcumDL = $row['totalcumDL'];
}
?>
<div class="container">
    <div class="d-flex justify-content-end mt-2">
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#changePasswordModal">
            Change Password
        </button>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changePasswordModalLabel">Change Password</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm">
                    <div class="form-group">
                        <label for="currentPassword">Current Password</label>
                        <input type="password" class="form-control" id="currentPassword" name="currentPassword" required>
                    </div>
                    <div class="form-group">
                        <label for="newPassword">New Password</label>
                        <input type="password" class="form-control" id="newPassword" name="newPassword" required>
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">Confirm New Password</label>
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS and dependencies -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
$(document).ready(function() {
    $('#changePasswordForm').on('submit', function(event) {
        event.preventDefault(); // Prevent default form submission

        const formData = {
            currentPassword: $('#currentPassword').val(),
            newPassword: $('#newPassword').val(),
            confirmPassword: $('#confirmPassword').val()
        };

        $.ajax({
            url: 'change_password.php',
            type: 'POST',
            data: formData,
            success: function(response) {
                alert(response);
                $('#changePasswordModal').modal('hide'); // Hide the modal after form submission
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error:', textStatus, errorThrown);
            }
        });
    });
});
</script>

<h2>Welcome, <?php echo $_SESSION['fname']; ?>!</h2>

<!-- Display the Total MIS Income value -->
<div class="row align-middle text-center">
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
            <p class="text-sm mb-0 text-capitalize font-weight-bold">Cumulative Direct Labour</p>
            <h5 class="font-weight-bolder mb-0">
                ₹<?php echo number_format($totalcumDL, 2); ?>
            </h5>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card card-body p-4">
        <p class="text-sm mb-0 text-capitalize font-weight-bold">RGL Value for the Month</p>
            <h5 class="font-weight-bolder mb-0">
                ₹<?php echo number_format($totalDL, 2); ?>
            </h5>
        </div>
    </div>
<?php include('includes/footer.php'); ?>