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

class CashDeposit {
    private $db;

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

    // Function to create a new cash deposit
    public function createDeposit($amount, $depositedBy, $narration, $depositDate) {
 
        $query =   "INSERT INTO `cash_deposits` (`cash_id`, `ammount`, `deposited_by`, `narration`, `deposit_date`) VALUES (NULL, '$amount', '$depositedBy', '$narration', '$depositDate')";
        $result = mysqli_query($this->db, $query);
        

        if ($result) {
            $this->updateBalance($amount); // Deposit created successfully
        } else {
            return false; // Failed to create deposit
        }
    }
     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
        }
    }
  

    // Function to update a cash deposit record
    public function updateDeposit($id, $amount, $depositedBy, $narration, $depositDate) {
        $query = "UPDATE cash_deposits SET amount = ?, deposited_by = ?, narration = ?, deposit_date = ? WHERE cash_id = ?";
        $stmt = mysqli_prepare($this->db, $query);
        mysqli_stmt_bind_param($stmt, "dsssi", $amount, $depositedBy, $narration, $depositDate, $id);

        return mysqli_stmt_execute($stmt); // Return true if update was successful
    }

    // Function to delete a cash deposit by its ID
    public function deleteDeposit($id) {
        $query = "DELETE FROM cash_deposits WHERE cash_id = ?";
        $stmt = mysqli_prepare($this->db, $query);
        mysqli_stmt_bind_param($stmt, "i", $id);

        return mysqli_stmt_execute($stmt); // Return true if deletion was successful
    }

    // Function to fetch all cash deposits
    public function getAllDeposits() {
        $query = "SELECT * FROM cash_deposits JOIN `users` ON `users`.id = `cash_deposits`.`deposited_by`  ";
        $result = mysqli_query($this->db, $query);

        return mysqli_fetch_all($result, MYSQLI_ASSOC); // Fetch all deposits as associative array
    }

    // Function to get a specific cash deposit by ID
    public function getDepositById($id) {
        $query = "SELECT * FROM cash_deposits WHERE cash_id = ?";
        $stmt = mysqli_prepare($this->db, $query);
        mysqli_stmt_bind_param($stmt, "i", $id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        return mysqli_fetch_assoc($result); // Fetch single deposit as associative array
    }
}
