<?php
/**
 * Database Helper Functions
 */

// Only start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!function_exists('db_begin_transaction')) {
    function db_begin_transaction() {
        global $db;
        if (isset($db) && $db instanceof mysqli) {
            $db->begin_transaction();
        } else {
            // Fallback to procedural style
            $connection = get_db_connection();
            mysqli_begin_transaction($connection);
        }
    }
}

if (!function_exists('db_commit')) {
    function db_commit() {
        global $db;
        if (isset($db) && $db instanceof mysqli) {
            $db->commit();
        } else {
            $connection = get_db_connection();
            mysqli_commit($connection);
        }
    }
}

if (!function_exists('db_rollback')) {
    function db_rollback() {
        global $db;
        if (isset($db) && $db instanceof mysqli) {
            $db->rollback();
        } else {
            $connection = get_db_connection();
            mysqli_rollback($connection);
        }
    }
}

if (!function_exists('db_query')) {
    function db_query($sql, $params = []) {
        $connection = get_db_connection();
        
        if (empty($params)) {
            $result = mysqli_query($connection, $sql);
            if ($result === false) {
                error_log("DB Query Error: " . mysqli_error($connection) . " in query: " . $sql);
                return false;
            }
            return $result;
        }
        
        // Prepare statement for parameterized queries
        $stmt = mysqli_prepare($connection, $sql);
        if ($stmt === false) {
            error_log("DB Prepare Error: " . mysqli_error($connection) . " in query: " . $sql);
            return false;
        }
        
        // Bind parameters if any
        if (!empty($params)) {
            $types = '';
            $bindParams = [];
            
            foreach ($params as $param) {
                if (is_int($param)) {
                    $types .= 'i';
                } elseif (is_float($param)) {
                    $types .= 'd';
                } elseif (is_string($param)) {
                    $types .= 's';
                } else {
                    $types .= 'b';
                }
                $bindParams[] = $param;
            }
            
            // Create an array of references for bind_param
            $bindParamsRef = [];
            $bindParamsRef[] = $types;
            foreach ($bindParams as $key => $value) {
                $bindParamsRef[] = &$bindParams[$key];
            }
            
            // Call bind_param with dynamic parameters
            call_user_func_array([$stmt, 'bind_param'], $bindParamsRef);
        }
        
        $executed = mysqli_stmt_execute($stmt);
        if (!$executed) {
            error_log("DB Execute Error: " . mysqli_stmt_error($stmt));
            mysqli_stmt_close($stmt);
            return false;
        }
        
        $result = mysqli_stmt_get_result($stmt);
        mysqli_stmt_close($stmt);
        
        return $result;
    }
}

if (!function_exists('db_fetch_all')) {
    function db_fetch_all($sql, $params = []) {
        $result = db_query($sql, $params);
        if ($result === false) {
            return [];
        }
        
        $rows = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $rows[] = $row;
        }
        mysqli_free_result($result);
        
        return $rows;
    }
}

if (!function_exists('db_fetch_one')) {
    function db_fetch_one($sql, $params = []) {
        $result = db_query($sql, $params);
        if ($result === false) {
            return null;
        }
        
        $row = mysqli_fetch_assoc($result);
        mysqli_free_result($result);
        
        return $row ?: null;
    }
}

if (!function_exists('db_fetch_value')) {
    function db_fetch_value($sql, $params = []) {
        $result = db_query($sql, $params);
        if ($result === false) {
            return null;
        }
        
        $row = mysqli_fetch_array($result);
        mysqli_free_result($result);
        
        return $row ? $row[0] : null;
    }
}

if (!function_exists('db_insert')) {
    function db_insert($table, $data) {
        $connection = get_db_connection();
        
        $columns = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));
        
        $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
        
        $stmt = mysqli_prepare($connection, $sql);
        if ($stmt === false) {
            error_log("DB Insert Prepare Error: " . mysqli_error($connection));
            return false;
        }
        
        $types = '';
        $values = [];
        $bindParams = [];
        $bindParams[] = $stmt;
        
        foreach ($data as $key => $value) {
            if (is_int($value)) {
                $types .= 'i';
            } elseif (is_float($value)) {
                $types .= 'd';
            } elseif (is_string($value)) {
                $types .= 's';
            } else {
                $types .= 'b';
            }
            $values[] = $value;
            $bindParams[] = &$values[count($values)-1];
        }
        
        // Prepend types to bindParams
        array_splice($bindParams, 1, 0, [$types]);
        
        // Call bind_param with dynamic parameters
        call_user_func_array('mysqli_stmt_bind_param', $bindParams);
        
        $executed = mysqli_stmt_execute($stmt);
        if (!$executed) {
            error_log("DB Insert Execute Error: " . mysqli_stmt_error($stmt));
            mysqli_stmt_close($stmt);
            return false;
        }
        
        $insert_id = mysqli_insert_id($connection);
        mysqli_stmt_close($stmt);
        
        return $insert_id;
    }
}

if (!function_exists('db_update')) {
    function db_update($table, $data, $where, $where_params = []) {
        $connection = get_db_connection();
        
        $set_clause = implode(' = ?, ', array_keys($data)) . ' = ?';
        
        $sql = "UPDATE {$table} SET {$set_clause} WHERE {$where}";
        
        $stmt = mysqli_prepare($connection, $sql);
        if ($stmt === false) {
            error_log("DB Update Prepare Error: " . mysqli_error($connection));
            return false;
        }
        
        // Build types string
        $types = '';
        $params = [];
        $bindParams = [];
        $bindParams[] = $stmt;
        
        foreach ($data as $value) {
            if (is_int($value)) {
                $types .= 'i';
            } elseif (is_float($value)) {
                $types .= 'd';
            } elseif (is_string($value)) {
                $types .= 's';
            } else {
                $types .= 'b';
            }
            $params[] = $value;
            $bindParams[] = &$params[count($params)-1];
        }
        
        foreach ($where_params as $value) {
            if (is_int($value)) {
                $types .= 'i';
            } elseif (is_float($value)) {
                $types .= 'd';
            } elseif (is_string($value)) {
                $types .= 's';
            } else {
                $types .= 'b';
            }
            $params[] = $value;
            $bindParams[] = &$params[count($params)-1];
        }
        
        // Prepend types to bindParams
        array_splice($bindParams, 1, 0, [$types]);
        
        // Call bind_param with dynamic parameters
        call_user_func_array('mysqli_stmt_bind_param', $bindParams);
        
        $executed = mysqli_stmt_execute($stmt);
        if (!$executed) {
            error_log("DB Update Execute Error: " . mysqli_stmt_error($stmt));
            mysqli_stmt_close($stmt);
            return false;
        }
        
        $affected_rows = mysqli_stmt_affected_rows($stmt);
        mysqli_stmt_close($stmt);
        
        return $affected_rows;
    }
}

if (!function_exists('get_db_connection')) {
    function get_db_connection() {
        static $connection = null;
        
        if ($connection === null) {
            // Try to get from global variable first
            global $db;
            if (isset($db) && $db instanceof mysqli) {
                return $db;
            }
            
            // Otherwise create new connection
            $host = defined('DB_HOST') ? DB_HOST : 'localhost';
            $user = defined('DB_USER') ? DB_USER : 'root';
            $pass = defined('DB_PASS') ? DB_PASS : '';
            $name = defined('DB_NAME') ? DB_NAME : 'ruhondo_hms';
            $port = defined('DB_PORT') ? DB_PORT : 3306;
            
            $connection = mysqli_connect($host, $user, $pass, $name, $port);
            
            if (mysqli_connect_errno()) {
                error_log("Database connection failed: " . mysqli_connect_error());
                die("Database connection failed. Please check your configuration.");
            }
            
            mysqli_set_charset($connection, "utf8mb4");
        }
        
        return $connection;
    }
}

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 2);
    }
}

if (!function_exists('generate_quotation_number')) {
    function generate_quotation_number() {
        $year = date('Y');
        $month = date('m');
        $prefix = "Q-{$year}{$month}";
        
        $last = db_fetch_value("
            SELECT quotation_number FROM quotations 
            WHERE quotation_number LIKE ? 
            ORDER BY quotation_id DESC LIMIT 1
        ", [$prefix . '%']);
        
        if ($last) {
            $lastNum = intval(substr($last, -4));
            $newNum = $lastNum + 1;
        } else {
            $newNum = 1;
        }
        
        return $prefix . str_pad($newNum, 4, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('log_activity')) {
    function log_activity($user_id, $action, $module, $record_id, $description) {
        // Implement if you have activity logging
        // This is optional
        return true;
    }
}

if (!function_exists('has_permission')) {
    function has_permission($permission) {
        // Implement your permission checking logic
        // For now, return true for development
        return true;
    }
}

if (!function_exists('current_user')) {
    function current_user() {
        // Check if user is logged in from session
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        if (isset($_SESSION['user_id'])) {
            return [
                'user_id' => $_SESSION['user_id'],
                'username' => $_SESSION['username'] ?? 'User',
                'first_name' => $_SESSION['first_name'] ?? 'User',
                'last_name' => $_SESSION['last_name'] ?? '',
                'email' => $_SESSION['email'] ?? ''
            ];
        }
        
        // Return dummy user for development
        return [
            'user_id' => 1,
            'username' => 'admin',
            'first_name' => 'Admin',
            'last_name' => 'User',
            'email' => 'admin@example.com'
        ];
    }
}

if (!function_exists('require_auth')) {
    function require_auth() {
        // Check if session is already started
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        // Check if user is logged in
        if (!isset($_SESSION['user_id'])) {
            // For development, we'll allow access without login
            // In production, you would redirect to login page
            // header("Location: /HMSPOS/public/login.php");
            // exit;
            return true;
        }
        
        return true;
    }
}

// Add this function to check if a session is active
if (!function_exists('is_session_active')) {
    function is_session_active() {
        return session_status() === PHP_SESSION_ACTIVE;
    }
}