<?php

include "dbconnect.php";
//	print_r($_REQUEST);
$formsubmit = isset($_REQUEST['submit']) ? $_REQUEST['submit'] : "";
$formUser = isset($_REQUEST['username']) ? $_REQUEST['username'] : "";
$formPass = isset($_REQUEST['password']) ? $_REQUEST['password'] : "";
if ($formsubmit == "Login") {
    //print("test");
    $result = query("select *from usercredential where username='******'");
    // print("select *from usercredential where username='******'");
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_object($result);
        $dbId = $row->id;
        $dbPass = $row->password;
        if ($dbPass == $formPass) {
            session_start();
            $_SESSION['loggedInpermission'] = "yes";
            $_SESSION['loggedUsername'] = $username;
            $_SESSION['loggedId'] = $username;
            URL_forward("dashboard.php", 0);
            exit;
        } else {
            URL_forward('index.php?error=invalid username or password', 0);
            exit;
        }
    } else {
        URL_forward('index.php?error=invalid username or password', 0);
    }
}
    $balance = abs($balance);
    $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : 0;
    $id = abs(filter_var($id, FILTER_VALIDATE_INT));
    $addedby = $_SESSION['loggedUsername'];
    if ($balance == "") {
        $error = "Please Enter Balance";
        header("location:add_balance.php?error={$error}&id={$id}");
        exit;
    } else {
        $date = date('Y-m-d');
        try {
            query("SET AUTOCOMMIT=0");
            query("START TRANSACTION");
            query("UPDATE usercredential SET    balance = balance+{$balance}\tWHERE id= '{$id}' ");
            query("INSERT INTO statement \n\t\t\t\t\t\t\t\t\t\t\tSET balance='{$balance}'\n\t\t\t\t\t\t\t\t\t\t\t,sdate  ='{$date}'\n\t\t\t\t\t\t\t\t\t\t\t,action ='add'\n\t\t\t\t\t\t\t\t\t\t\t,userid ='{$id}'\n\t\t\t\t\t\t\t\t\t\t\t,addedby  ='{$addedby}'\n\t\t\t\t\t\t\t\t\t\t\t");
            query("COMMIT");
            header("location:view.php?msg=Successfully Balance Added.");
            exit;
        } catch (Exception $e) {
            query("ROLLBACK");
            header("location:edit.php?error=problem:{$e}");
            exit;
        }
    }
}
//Logout
if ($action == "logoutUser") {
    $_SESSION = array();
    URL_forward("index.php", 0);
    exit;
}