<?php
require '../config/function.php';

if(isset($_POST['saveUser']))
{
    $fname = validate($_POST['fname']);
    $lname = validate($_POST['lname']);
    $email = validate($_POST['email']);
    $password = validate($_POST['password']);
    $role = validate($_POST['role']);
    $employeeRate = validate($_POST['employeeRate']);
    $joiningDate = validate($_POST['joiningDate']);
    $budgetedRGLq1 = validate($_POST['budgetedRGLq1']);
    $budgetedRGLq2 = validate($_POST['budgetedRGLq2']);
    $budgetedRGLq3 = validate($_POST['budgetedRGLq3']);
    $budgetedRGLq4 = validate($_POST['budgetedRGLq4']);
    $workingDays = validate($_POST['workingDays']);

    if($fname!=''||$lname!=''||$email!=''||$password!=''||$role!=''||$employeeRate!=''||$joiningDate!=''||$budgetedRGLq1!=''||$budgetedRGLq2!=''||$budgetedRGLq3!=''||$budgetedRGLq4!=''||$workingDays!='')
    {
        $query = "INSERT INTO users (fname,lname,email,password,role,employeeRate,joiningDate,budgetedRGLq1,budgetedRGLq2,budgetedRGLq3,budgetedRGLq4,workingDays) 
                VALUES ('$fname','$lname','$email','$password','$role','$employeeRate','$joiningDate','$budgetedRGLq1','$budgetedRGLq2','$budgetedRGLq3','$budgetedRGLq4','$workingDays')";
        $result = mysqli_query($conn, $query);

        if($result)
        {
            redirect('users.php','User Added Successfully');
        }
        else
        {
            redirect('users-create.php','Something Went Wrong');
        }
    }
    else
    {
        redirect('users-create.php','Please fill all the input fields');
    }
}

if(isset($_POST['updateUser']))
{
    $fname = validate($_POST['fname']);
    $lname = validate($_POST['lname']);
    $email = validate($_POST['email']);
    $password = validate($_POST['password']);
    $role = validate($_POST['role']);
    $employeeRate = validate($_POST['employeeRate']);
    $joiningDate = validate($_POST['joiningDate']);
    $budgetedRGLq1 = validate($_POST['budgetedRGLq1']);
    $budgetedRGLq2 = validate($_POST['budgetedRGLq2']);
    $budgetedRGLq3 = validate($_POST['budgetedRGLq3']);
    $budgetedRGLq4 = validate($_POST['budgetedRGLq4']);
    $workingDays = validate($_POST['workingDays']);
    $UID = validate($_POST['UID']);
    $users = getById('users',$UID);
    if($users['status']!=200){
        redirect('users-edit.php?userID='.$UID,'No such ID Found');
    }

    if($fname!=''||$lname!=''||$email!=''||$password!=''||$role!=''||$employeeRate!=''||$joiningDate!=''||$budgetedRGLq1!=''||$budgetedRGLq2!=''||$budgetedRGLq3!=''||$budgetedRGLq4!=''||$workingDays!='')
    {
        $query = "UPDATE users SET
                 fname='$fname',
                 lname='$lname',
                 email='$email',
                 password='$password',
                 role='$role',
                 employeeRate='$employeeRate',
                 joiningDate='$joiningDate',
                 budgetedRGLq1='$budgetedRGLq1',
                 budgetedRGLq2='$budgetedRGLq2',
                 budgetedRGLq3='$budgetedRGLq3',
                 budgetedRGLq4='$budgetedRGLq4',
                 workingDays='$workingDays'
                 WHERE userID='$UID' ";
        $result = mysqli_query($conn, $query);

        if($result)
        {
            redirect('users-edit.php?userID='.$UID,'User Updated Successfully');
        }
        else
        {
            redirect('users-create.php','Something Went Wrong');
        }
    }
    else
    {
        redirect('users-create.php','Please fill all the input fields');
    }
}



if(isset($_POST['saveClient']))
{
    $clientName = validate($_POST['clientName']);

    if($clientName!='')
    {
        $query = "INSERT INTO clients (clientName) 
                VALUES ('$clientName')";
        $result = mysqli_query($conn, $query);

        if($result)
        {
            redirect('clients.php','Client Added Successfully');
        }
        else
        {
            redirect('clients-create.php','Something Went Wrong');
        }
    }
    else
    {
        redirect('clients-create.php','Please fill all the input fields');
    }
}

if(isset($_POST['updateClient']))
{
    $clientName = validate($_POST['clientName']);
    $CID = validate($_POST['CID']);
    $clients = getBycId('clients',$CID);
    if($clients['status']!=200){
        redirect('clients-edit.php?clientID='.$CID,'No such ID Found');
    }

    if($clientName!='')
    {
        $query = "UPDATE clients SET
                 clientName='$clientName'
                 WHERE clientID='$CID' ";
        $result = mysqli_query($conn, $query);

        if($result)
        {
            redirect('clients-edit.php?clientID='.$CID,'Client Updated Successfully');
        }
        else
        {
            redirect('clients-edit.php?clientID='.$CID,'Something Went Wrong');
        }
    }
    else
    {
        redirect('clients-edit.php','Please fill all the input fields');
    }
}

if (isset($_POST['updateProject'])) {
    // Retrieve and validate form data
    $projectID = validate($_POST['projectID']);
    $projectName = validate($_POST['projectName']);
    $clientID = validate($_POST['clientID']);
    $contractValue = validate($_POST['contractValue']);

    // Update project details in the database
    $updateQuery = "UPDATE projects SET projectName = '$projectName', clientID = '$clientID', contractValue = '$contractValue' WHERE projectID = '$projectID'";
    $updateResult = mysqli_query($conn, $updateQuery);

    if ($updateResult) {
        // Project details updated successfully, redirect to projects.php
        redirect('projects.php', 'Project Updated Successfully');
    } else {
        // Something went wrong with the database query
        redirect("projects-edit.php?projectID=$projectID", 'Something Went Wrong');
    }
}




if(isset($_POST['saveProject']))
{
    $projectName = validate($_POST['projectName']);
    $clientID = validate($_POST['clientID']);
    $contractValue = validate($_POST['contractValue']);

    if($projectName!=''||$clientID!=''||$contractValue!='')
    {
        $query = "INSERT INTO projects (projectName, clientID, contractValue) VALUES ('$projectName', '$clientID','$contractValue')";;
        $result = mysqli_query($conn, $query);

        if($result)
        {
            redirect('projects.php','Project Added Successfully');
        }
        else
        {
            redirect('projects-create.php','Something Went Wrong');
        }
    }
    else
    {
        redirect('projects-create.php','Please fill all the input fields');
    }
}


if (isset($_POST['saveMilestone'])) {
    // Retrieve and validate form data
    $milestoneName = validate($_POST['milestoneName']);
    $milestoneValue = validate($_POST['milestoneValue']);
    $completionDate = !empty($_POST['completionDate']) ? $_POST['completionDate'] : '0000-00-00';
    $projectID = validate($_POST['projectID']);

    // Calculate the total of existing milestones
    $totalMilestoneValue = calculateSumMilestoneValues($projectID, $milestoneValue, $conn);

    // Retrieve the contract value for the project
    $contractValue = getContractValue($projectID, $conn);

    if ($totalMilestoneValue === false) {
        redirect('milestones-create.php?projectID=' . $projectID, 'Error calculating milestone values.');
    } elseif ($contractValue === false) {
        redirect('milestones-create.php?projectID=' . $projectID, 'Error retrieving contract value.');
    } elseif ($totalMilestoneValue > $contractValue) {
        redirect('milestones-create.php?projectID=' . $projectID, 'Total milestone value exceeds the contract value.');
    } else {
        // Insert milestone data into the database
        $query = "INSERT INTO milestones (milestoneName, milestoneValue, completionDate, projectID) 
                  VALUES ('$milestoneName', '$milestoneValue', '$completionDate', '$projectID')";

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

        if ($result) {
            redirect('milestones-view.php?projectID=' . $projectID, 'Milestone Added Successfully');
        } else {
            redirect('milestones-create.php?projectID=' . $projectID, 'Something Went Wrong');
        }
    }
}



if(isset($_POST['saveTimesheet']))
{
    $tentryDate = validate($_POST['tenrtyDate']);
    $clientID = validate($_POST['clientID']);
    $projectID = validate($_POST['projectID']);
    $milestoneID = validate($_POST['milestoneID']);
    $hrs = validate($_POST['hrs']);
    $descp = validate($_POST['descp']);

    if($tentryDate!=''||$clientID!=''||$projectID!=''||$milestoneID!=''||$hrs!=''||$descp!='')
    {
        $query = "INSERT INTO timesheet (tenrtyDate, clientID, projectID,milestoneID, hrs,descp) VALUES ('$tentryDate', '$clientID','$projectID','$milestoneID', '$hrs','$descp')";
        $result = mysqli_query($conn, $query);

        if($result)
        {
            redirect('timesheet-view.php','Timesheet Added Successfully');
        }
        else
        {
            redirect('timesheet.php','Something Went Wrong');
        }
    }
    else
    {
        redirect('timesheet.php','Please fill all the input fields');
    }
}


if (isset($_POST['updateNCMilestone'])) {
    if (isset($_POST['ncmilestoneID'], $_POST['milestone'], $_POST['expectedAmt'], $_POST['expectedDateBilling'], $_POST['contractID'])) {
        // Retrieve form data
        $ncmilestoneID = validate($_POST['ncmilestoneID']);
        $milestone = validate($_POST['milestone']);
        $expectedAmt = validate($_POST['expectedAmt']);
        $expectedDateBilling = validate($_POST['expectedDateBilling']);
        $contractID = validate($_POST['contractID']);

        // Fetch the current milestone details to get the old value
        $oldQuery = "SELECT expectedAmt FROM ncmilestones WHERE ncmilestoneID = '$ncmilestoneID'";
        $oldResult = mysqli_query($conn, $oldQuery);
        if (!$oldResult) {
            redirect('ncmilestones-edit.php?ncmilestoneID=' . $ncmilestoneID . '&contractID=' . $contractID, 'Error fetching old milestone amount.');
        }
        $oldRow = mysqli_fetch_assoc($oldResult);
        $oldAmt = $oldRow['expectedAmt'];

        // Fetch the current total of ncmilestones.expectedAmt for the given contractID
        $totalQuery = "SELECT SUM(expectedAmt) AS totalExpectedAmt FROM ncmilestones WHERE contractID = '$contractID'";
        $totalResult = mysqli_query($conn, $totalQuery);
        if (!$totalResult) {
            redirect('ncmilestones-edit.php?ncmilestoneID=' . $ncmilestoneID . '&contractID=' . $contractID, 'Error fetching total expected amount.');
        }
        $totalRow = mysqli_fetch_assoc($totalResult);
        $currentTotal = $totalRow['totalExpectedAmt'] - $oldAmt; // Subtract old amount

        // Retrieve the contract amount for the specified contractID
        $contractQuery = "SELECT contractAmt FROM contracts WHERE contractID = '$contractID'";
        $contractResult = mysqli_query($conn, $contractQuery);
        if (!$contractResult) {
            redirect('ncmilestones-edit.php?ncmilestoneID=' . $ncmilestoneID . '&contractID=' . $contractID, 'Error fetching contract amount.');
        }
        $contractRow = mysqli_fetch_assoc($contractResult);
        $contractAmt = $contractRow['contractAmt'];

        // Calculate the new total expected amount including the updated milestone
        $newTotal = $currentTotal + $expectedAmt;

        if ($newTotal > $contractAmt) {
            // Output an error message if the total exceeds the contract amount
            $_SESSION['error_message'] = "Total milestone amount exceeds the contract amount.";
            header('Location: ncmilestones-edit.php?ncmilestoneID=' . $ncmilestoneID . '&contractID=' . $contractID);
            exit();
        } else {
            // Update the milestone in the database
            $query = "UPDATE ncmilestones SET 
                milestone = '$milestone',
                expectedAmt = '$expectedAmt',
                expectedDateBilling = '$expectedDateBilling'
                WHERE ncmilestoneID = '$ncmilestoneID'";

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

            if ($result) {
                // Check if a new milestone is needed
                $remainingAmount = $contractAmt - $newTotal;
                if ($remainingAmount > 0) {
                    // Create a new milestone with the remaining amount
                    $newMilestoneName = 'Full Contract';
                    $insertQuery = "INSERT INTO ncmilestones (contractID, milestone, expectedAmt, expectedDateBilling)
                                    VALUES ('$contractID', '$newMilestoneName', '$remainingAmount', '$expectedDateBilling')";

                    $insertResult = mysqli_query($conn, $insertQuery);
                    if (!$insertResult) {
                        redirect('ncmilestones-edit.php?ncmilestoneID=' . $ncmilestoneID . '&contractID=' . $contractID, 'Milestone updated, but failed to add "Full Contract" milestone.');
                    }
                }
                // Set session message and redirect
                $_SESSION['success_message'] = "Milestone updated successfully.";
                header('Location: contracts-view.php?contractID=' . $contractID);
                exit(); // Ensure that you exit after sending the redirection
            } else {
                // Handle the case where the update query failed
                $_SESSION['error_message'] = "Error updating milestone: " . mysqli_error($conn);
                header('Location: ncmilestones-edit.php?ncmilestoneID=' . $ncmilestoneID . '&contractID=' . $contractID);
                exit();
            }
        }
    } else {
        redirect('ncmilestones-edit.php?ncmilestoneID=' . $_POST['ncmilestoneID'] . '&contractID=' . $_POST['contractID'], 'All fields are required.');
    }
}


if (isset($_POST['updateMilestone'])) {
    if (isset($_POST['milestoneID'], $_POST['milestoneName'], $_POST['milestoneValue'], $_POST['completionDate'])) {
        $milestoneID = validate($_POST['milestoneID']);
        $milestoneName = validate($_POST['milestoneName']);
        $milestoneValue = validate($_POST['milestoneValue']);
        $completionDate = !empty($_POST['completionDate']) ? validate($_POST['completionDate']) : '0000-00-00';

        // Fetch the projectID from the milestone
        $queryProjectID = "SELECT projectID, milestoneValue FROM milestones WHERE milestoneID = '$milestoneID'";
        $resultProjectID = mysqli_query($conn, $queryProjectID);

        if (!$resultProjectID) {
            redirect('milestones-edit.php?milestoneID=' . $milestoneID, 'Error fetching milestone details.');
        }

        $rowProjectID = mysqli_fetch_assoc($resultProjectID);
        $projectID = $rowProjectID['projectID'];
        $currentMilestoneValue = $rowProjectID['milestoneValue'];

        // Calculate the total milestone value after update
        $totalMilestoneValue = calculateSumMilestoneValues($projectID, $milestoneValue - $currentMilestoneValue, $conn);

        // Retrieve the contract value for the project
        $contractValue = getContractValue($projectID, $conn);

        if ($totalMilestoneValue === false) {
            redirect('milestones-edit.php?milestoneID=' . $milestoneID, 'Error calculating total milestone values.');
        } elseif ($contractValue === false) {
            redirect('milestones-edit.php?milestoneID=' . $milestoneID, 'Error retrieving contract value.');
        } elseif ($totalMilestoneValue > $contractValue) {
            redirect('milestones-edit.php?milestoneID=' . $milestoneID, 'Total milestone value exceeds the contract value.');
        } else {
            // Update the milestone in the database
            $updateQuery = "UPDATE milestones SET 
                milestoneName = '$milestoneName',
                milestoneValue = '$milestoneValue',
                completionDate = '$completionDate'
                WHERE milestoneID = '$milestoneID'";

            $updateResult = mysqli_query($conn, $updateQuery);

            if ($updateResult) {
                // Check if a new milestone is needed
                $remainingAmount = $contractValue - $totalMilestoneValue;
                if ($remainingAmount > 0) {
                    // Create a new milestone with the remaining amount
                    $newMilestoneName = 'Full Contract';
                    $insertQuery = "INSERT INTO milestones (projectID, milestoneName, milestoneValue, completionDate)
                                    VALUES ('$projectID', '$newMilestoneName', '$remainingAmount', '$completionDate')";

                    $insertResult = mysqli_query($conn, $insertQuery);
                    if (!$insertResult) {
                        redirect('milestones-edit.php?milestoneID=' . $milestoneID, 'Milestone updated, but failed to add "Full Contract" milestone.');
                    }
                }
                redirect('milestones-view.php?projectID=' . $projectID, 'Milestone Updated Successfully');
            } else {
                redirect('milestones-edit.php?milestoneID=' . $milestoneID, 'Failed to update milestone.');
            }
        }
    } else {
        redirect('milestones-edit.php?milestoneID=' . $_POST['milestoneID'], 'All fields except Completion Date are required.');
    }
}
?>