<?php

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    function gohome( ){
        echo "<script>window.location.href='../../index.php';</script>";
        exit();
    }

    function json_response($success, $message, $code = null, $data = null, $debug = false, $log = false) {
        $response = [
            'success' => $success,
            'message' => $message
        ];

        if ($code) $response['code'] = $code;
        if ($data) $response['data'] = $data;

        if ($debug && isset($debug['error'])) {
            $response['debug'] = $debug['error'];
        }

        if ($log && isset($debug['error'])) {
            error_log('[APP ERROR] ' . $debug['error']);
        }

        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }

    function zeroVal($val) {
        return htmlspecialchars((string)$val); 
    }

    function queryDB($sql, $connection, $bind, $params, $to_array, $q_as = 's') {
        $stmt = $connection->prepare($sql);

        if (!$stmt) {
            die('Prepare failed: ' . $connection->error);
        }

        if ($bind == true) {
            // Ensure correct parameter binding
            $stmt->bind_param($params[0], ...$params[1]);
        }

        $success = $stmt->execute();
        $result = $stmt->get_result();

        $stmt->close();

        if ($to_array == true && $q_as == 's') {
            $arr = [];
            while ($row = $result->fetch_assoc()) {
                $arr[] = $row;
            }
            $result = $arr;
        }

        return ($q_as != 's') ? $success : $result;
    }

    function getInput($input) {
        if (is_int($input)) {
            return filter_var($input, FILTER_SANITIZE_NUMBER_INT);
        } elseif (is_float($input)) {
            return filter_var($input, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        } elseif (is_string($input)) {
            return filter_var(field($input), FILTER_SANITIZE_STRING);
        } elseif (is_array($input)) {
            return filter_var_array($input, FILTER_SANITIZE_STRING);
        } elseif (is_bool($input)) {
            return filter_var($input, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
        } elseif (is_string($input)) { 
            $formats = ['Y-m-d', 'd-m-Y', 'm/d/Y'];
            foreach ($formats as $format) {
                $dt = DateTime::createFromFormat($format, $input);
                if ($dt && $dt->format($format) === $input) {
                    return $dt->format('Y-m-d'); 
                }
            }
        }
        return false;          
    }

    function field($value, $default = '') {
        return htmlspecialchars($value ?? $default);
    }

    function input_date($dt) {
        return date("Y/m/d", strtotime($dt));
    }
    function db_date($dt) {
        return date("Y-m-d", strtotime($dt));
    }

 ?>
