<?php

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

    $amount = $_POST['amount'];
    $remark = $_POST['remark'];
    $status = $_POST['status'];
    $project = $_POST['project'];

    $id = $_GET['id'];

    $sql = "SELECT * FROM `add_expenses` WHERE id=$id";

    $expenseDetails = mysqli_query($link,$sql);
    while($row = mysqli_fetch_array($expenseDetails)){
        $oldamount = $row['amount'];
        $oldstatus = $row['status'];
        $oldproject = $row['project'];
    } 

    $sql = "SELECT * FROM `project` WHERE projectname='$oldproject'";
   
    $projectDetails = mysqli_query($link,$sql);
    while($row = mysqli_fetch_array($projectDetails)){
        $oldcost = $row['projectcost'];
        $oldbalance = $row['balance'];
        $advance = $row['advance'];
    }
    
    if($oldstatus=='credit'){
        $newcost = $oldcost - $oldamount;
        $newbalance = $newcost - $advance;
    }
    else{
        $newcost = $oldcost + $oldamount;
        $newbalance = $newcost - $advance;
    }

    $sql = "UPDATE `project` SET `projectcost`='$newcost',`balance`='$newbalance' WHERE projectname='$oldproject'";

    $result = mysqli_query($link,$sql);

    $sql = "UPDATE `add_expenses` SET `amount`='$amount',`remark`='$remark',`status`='$status', `project`='$project' WHERE id=$id";
    
    $result = mysqli_query($link,$sql);

    $sql = "SELECT * FROM `project` WHERE projectname='$project'";
    $projDetails = mysqli_query($link, $sql);
    while($row = mysqli_fetch_array($projDetails)){
        $oldcost = $row['projectcost'];
        $oldbalance = $row['balance'];
    }
    if($status=='credit'){
        $newcost = $oldcost + $amount;
        $newbalance = $oldbalance + $amount;
    }
    else{
        $newcost = $oldcost - $amount;
        $newbalance = $oldbalance - $amount;
    }
    $sql = "UPDATE `project` SET `projectcost`='$newcost',`balance`='$newbalance' WHERE projectname='$project'";
    $projectUpdate = $link->query($sql);
    if($result){
        header('Location:../allexpenses.php?status=1');
    }
    
?>