<?php 
require_once('db_connection.php');

class Expense  
{
    private $db;

    function __construct($dbconn){
        $this->db = $dbconn;
    }

    // Function to create a new expense record
    public function createExpense($expense, $amount, $issuedBy, $issuedDate, $narration) {
        $query = "INSERT INTO `expenses` (`id`, `expense`, `ammount`, `issued_by`, `issued_date`, `naration`) VALUES (NULL, '$expense', '$amount', '$issuedBy', current_timestamp(), '$narration')";
        $currentBalance = $this->getBalance($amount);
       
         if($currentBalance[0]['balance'] >= $amount){
            $result = mysqli_query($this->db,$query);
         }else{
             return false;
         }
       
        if ($result) {
              $this->updateBalance($amount); 
            // Record created successfully
        } else {
            return false; // Failed to create record
        }
    }
     private function updateBalance($amount) {
 
        $query =   "UPDATE `cash_balance` SET `balance`= (balance - $amount) WHERE id=1";
        $result = mysqli_query($this->db, $query);
        

        if ($result) {
            return true; // Deposit created successfully
        } else {
            return false; // Failed to create deposit
        }
    }
    
      public function getBalance() {
 
        $query = "SELECT balance FROM cash_balance";
        $result = $this->db->query($query);
        
        return $result->fetch_all(MYSQLI_ASSOC); 
    }

    // Function to update an expense record
    public function updateExpense($id, $expense, $amount, $issuedBy, $issuedDate, $narration) {
        $query = "UPDATE expenses SET expense = ?, amount = ?, issued_by = ?, issued_date = ?, narration = ? WHERE id = ?";
        $stmt = $this->db->prepare($query);
        $stmt->bind_param("sdsssi", $expense, $amount, $issuedBy, $issuedDate, $narration, $id);
        
        return $stmt->execute(); // Return true if update was successful
    }

    // Function to delete an expense record
    public function deleteExpense($id) {
        $query = "DELETE FROM expenses WHERE id = ?";
        $stmt = $this->db->prepare($query);
        $stmt->bind_param("i", $id);
        
        return $stmt->execute(); // Return true if deletion was successful
    }

    // Function to fetch all expense records
    public function getAllExpenses() {
        $query = "SELECT * FROM expenses";
        $result = $this->db->query($query);
        
        return $result->fetch_all(MYSQLI_ASSOC); // Fetch all expenses as associative array
    }

    // Function to get a specific expense record by ID
    public function getExpenseById($id) {
        $query = "SELECT * FROM expenses WHERE id = ?";
        $stmt = $this->db->prepare($query);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        
        $result = $stmt->get_result();
        return $result->fetch_assoc(); // Fetch single expense record as associative array
    }
}
