<?php 

session_start(); 
    $u_uname = '';
    if (isset($_COOKIE['auth_token']))
    {
        $u_uname = $_COOKIE['auth_token'];
    }else{
        header("location:../login.php");
    }

    include('../include/connection.php');
?>
<?php
// Check if the request method is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if all required parameters are set
    if (isset($_POST['number'], $_POST['remark'], $_POST['status'], $_POST['projectRadio'])) {
        // Get the values of all parameters
        $amount = $_POST['number'];
        $remark = $_POST['remark'];
        $status = $_POST['status'];
        $projectFlag = $_POST['projectRadio'];

        // Initialize project variable
        $project = '';

        // Check if projectFlag is set and its value is 'project'
        if ($projectFlag == 'project' && isset($_POST['projectName'])) {
            $project = $_POST['projectName'];

            // Fetch project details
            $sql = "SELECT * FROM `project` WHERE projectname='$project'";
            $projDetails = mysqli_query($link, $sql);
            while($row = mysqli_fetch_array($projDetails)){
                $oldcost = $row['projectcost'];
                $oldbalance = $row['balance'];
            }
            // Update project cost and balance based on status
            if($status=='credit'){
                $newcost = $oldcost + $amount;
                $newbalance = $oldbalance + $amount;
            } else {
                $newcost = $oldcost - $amount;
                $newbalance = $oldbalance - $amount;
            }
            // Update project cost and balance
            $sql = "UPDATE `project` SET `projectcost`='$newcost',`balance`='$newbalance' WHERE projectname='$project'";
            $projectUpdate = $link->query($sql);
        } else {
            $project = "Other";
        }

        // Insert expense details into database
        $sql = "INSERT INTO `add_expenses`( `amount`, `remark`, `status`, `project`) VALUES ('$amount','$remark','$status', '$project')";

        if($link->query($sql) === TRUE) {
            // Redirect to a page after successful insertion
            header('Location:../addexpenses.php?status=1');
        } else {
            // Handle error if insertion fails
            echo "Error: " . $sql . "<br>" . $link->error;
        }
    } else {
        // If any required parameter is missing, show an error message
        header('Location:../addexpenses.php?status=2');
       
    }
} else {
    // If the request method is not POST, show an error message
    echo "Invalid request method";
}
?>
