<?php include "../db.php"; ?>
<?php
$connection= new mysqli($dbhost,$dbusername,$dbpassword,$dbname);
if($_SERVER["REQUEST_METHOD"]=="POST" && isset($_POST["add_expense_btn"])){
    $title=$_POST["add_expense_title"];
    $date=$_POST["add_expense_date"];
    $covertdate=date("Y-m-d",strtotime($date));
    $entrydate=date("Y-m-d");
   $cost=$_POST["add_expense_cost"];
    
    if(empty($amount) && empty($date) && empty($title)  && empty($cost)){
        session_start();
        $_SESSION["expense_add_error"]="All Fields Are Required!!";
        header("Location: ../expenses.php");
        exit();
    }

    else{
        if (strpos($title, "'") !== false) {
    session_start();
    $_SESSION["expense_val_error"] = "Single quotes (') are not allowed in title.";
    header("Location: ../expenses.php");
    exit();
     }
        $addExpenseQuery="INSERT INTO expense (Title,Date,Entry_Date,Cost)
        VALUES ('$title','$covertdate','$entrydate','$cost')";
        $connection->query($addExpenseQuery);
        session_start();
        $_SESSION["expense_add_alert"]="Expense Added Successfully!!";
        header("Location: ../expenses.php");
        exit();
    }
}


if($_SERVER["REQUEST_METHOD"]=="POST" && isset($_POST["edit_expense_btn"])){
    $ID=$_POST["edit_expense_id"];
    $title=$_POST["edit_expense_title"];
    $date=$_POST["edit_expense_date"];
    $covertdate=date("Y-m-d",strtotime($date));
    $entrydate=date("Y-m-d");
   $cost=$_POST["edit_expense_cost"];
    
    if(empty($amount) && empty($date) && empty($title)  && empty($cost)){
        session_start();
        $_SESSION["expense_add_error"]="All Fields Are Required!!";
        header("Location: ../expenses.php");
        exit();
    }

    else{
        if (strpos($title, "'") !== false) {
    session_start();
    $_SESSION["expense_val_error"] = "Single quotes (') are not allowed in title.";
    header("Location: ../expenses.php");
    exit();
}
        $editExpenseQuery="UPDATE expense SET  Title='$title',Date='$covertdate',Entry_Date='$entrydate',Cost='$cost' WHERE ID='$ID'";
        $connection->query($editExpenseQuery);
        session_start();
        $_SESSION["expense_add_alert"]="Expense Added Successfully!!";
        header("Location: ../expenses.php");
        exit();
    }
}
if(isset($_POST["id"])){
    $id=$_POST["id"];
    $dltExpenseQuery="DELETE from expense WHERE ID='$id'";
    $connection->query($dltExpenseQuery);
}
?>