<?php
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'cash_lending_db');

// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Check connection
if ($conn->connect_error) {
    error_log("DB connection failed: " . $conn->connect_error);
    http_response_code(503);
    die("Service temporarily unavailable. Please try again later.");
}

// Set charset to utf8
$conn->set_charset("utf8");

// Function to execute prepared statements
function executeQuery($conn, $sql, $params = array(), $types = "") {
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        error_log("DB prepare failed: " . $conn->error . " | SQL: " . $sql);
        http_response_code(500);
        die("A database error occurred. Please try again.");
    }
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    
    if (!$stmt->execute()) {
        error_log("DB execute failed: " . $stmt->error);
        http_response_code(500);
        die("A database error occurred. Please try again.");
    }
    
    return $stmt;
}

// Function to fetch all results
function fetchAll($conn, $sql, $params = array(), $types = "") {
    $stmt = executeQuery($conn, $sql, $params, $types);
    $result = $stmt->get_result();
    $data = array();
    
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    
    $stmt->close();
    return $data;
}

// Function to fetch single row
function fetchOne($conn, $sql, $params = array(), $types = "") {
    $stmt = executeQuery($conn, $sql, $params, $types);
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    return $data;
}

// Function to get count
function getCount($conn, $sql, $params = array(), $types = "") {
    $stmt = executeQuery($conn, $sql, $params, $types);
    $result = $stmt->get_result();
    $row = $result->fetch_row();
    $stmt->close();
    return $row[0];
}
?>
