<?php
include_once(__DIR__ . '/../vendor/autoload.php');

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

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

date_default_timezone_set('Asia/Ho_Chi_Minh');

if (!function_exists('DEMO_MODE')) {
    function DEMO_MODE()
    {
        return isset($_ENV['DEMO_MODE']) && strtolower((string)$_ENV['DEMO_MODE']) === 'true';
    }
}

if (!function_exists('IS_DEMO_BLOCK_REQUEST')) {
    function IS_DEMO_BLOCK_REQUEST()
    {
        $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
        return in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE']);
    }
}

if (!function_exists('DEMO_RESPONSE')) {
    function DEMO_RESPONSE($message = '⚠ Website đang ở chế độ DEMO, không thể thay đổi dữ liệu!')
    {
        if (!headers_sent()) {
            header('Content-Type: application/json; charset=utf-8');
        }

        echo json_encode([
            'status' => 'error',
            'msg'    => $message
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

class DB
{
    private $ketnoi = null;

    function connect()
    {
        if (!$this->ketnoi) {
            mysqli_report(MYSQLI_REPORT_OFF);

            $host = $_ENV['DB_HOST'] ?? 'localhost';
            $user = $_ENV['DB_USERNAME'] ?? '';
            $pass = $_ENV['DB_PASSWORD'] ?? '';
            $db   = $_ENV['DB_DATABASE'] ?? '';

            $this->ketnoi = mysqli_connect($host, $user, $pass, $db);

            if (!$this->ketnoi) {
                die(
                    "KẾT NỐI MYSQL THẤT BẠI<br>" .
                    "HOST: $host<br>" .
                    "USER: $user<br>" .
                    "DATABASE: $db<br>" .
                    "ERROR: " . mysqli_connect_error()
                );
            }

            mysqli_set_charset($this->ketnoi, "utf8mb4");
        }
    }

    function dis_connect()
    {
        if ($this->ketnoi) {
            mysqli_close($this->ketnoi);
            $this->ketnoi = null;
        }
    }

    private function isWriteQuery($sql)
    {
        $sql = trim($sql);
        return preg_match('/^(INSERT|UPDATE|DELETE|REPLACE|DROP|CREATE|ALTER|TRUNCATE)\s+/i', $sql);
    }

    private function blockIfDemoWrite($sql = '')
    {
        if (!DEMO_MODE()) {
            return;
        }

        // Chỉ chặn khi là request thay đổi dữ liệu
        if (!IS_DEMO_BLOCK_REQUEST()) {
            return;
        }

        if ($sql !== '' && $this->isWriteQuery($sql)) {
            DEMO_RESPONSE();
        }
    }

    function query($sql)
    {
        $this->connect();
        $this->blockIfDemoWrite($sql);
        return $this->ketnoi->query($sql);
    }

    function getUser($username)
    {
        $this->connect();

        $username = mysqli_real_escape_string($this->ketnoi, $username);

        $sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
        $result = $this->ketnoi->query($sql);

        if ($result && $result->num_rows > 0) {
            return $result->fetch_array(MYSQLI_ASSOC);
        }

        return false;
    }

    function site($data)
    {
        $this->connect();

        $data = mysqli_real_escape_string($this->ketnoi, $data);

        $sql = "SELECT * FROM settings WHERE name='$data' LIMIT 1";
        $result = $this->ketnoi->query($sql);

        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_array(MYSQLI_ASSOC);
            return $row['value'] ?? null;
        }

        return null;
    }

    function insert($table, $data)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $fields = '';
        $values = '';

        foreach ($data as $key => $value) {
            $fields .= ",`$key`";
            $values .= ",'" . mysqli_real_escape_string($this->ketnoi, $value) . "'";
        }

        $sql = "INSERT INTO `$table` (" . trim($fields, ',') . ") VALUES (" . trim($values, ',') . ")";
        return mysqli_query($this->ketnoi, $sql);
    }

    function update($table, $data, $where)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $sql = '';

        foreach ($data as $key => $value) {
            $sql .= "`$key`='" . mysqli_real_escape_string($this->ketnoi, $value) . "',";
        }

        $sql = "UPDATE `$table` SET " . trim($sql, ',') . " WHERE $where";
        return mysqli_query($this->ketnoi, $sql);
    }

    function remove($table, $where)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $sql = "DELETE FROM `$table` WHERE $where";
        return mysqli_query($this->ketnoi, $sql);
    }

    function cong($table, $data, $sotien, $where)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $sql = "UPDATE `$table` SET `$data` = `$data` + '$sotien' WHERE $where";
        return mysqli_query($this->ketnoi, $sql);
    }

    function tru($table, $data, $sotien, $where)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $sql = "UPDATE `$table` SET `$data` = `$data` - '$sotien' WHERE $where";
        return mysqli_query($this->ketnoi, $sql);
    }

    function get_row($sql)
    {
        $this->connect();
        $this->blockIfDemoWrite($sql);

        $result = mysqli_query($this->ketnoi, $sql);

        if (!$result) {
            die("Query lỗi: " . mysqli_error($this->ketnoi));
        }

        return mysqli_fetch_assoc($result);
    }

    function get_list($sql)
    {
        $this->connect();
        $this->blockIfDemoWrite($sql);

        $result = mysqli_query($this->ketnoi, $sql);

        if (!$result) {
            die("Query lỗi: " . mysqli_error($this->ketnoi));
        }

        $data = [];

        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }

        return $data;
    }

    function num_rows($sql)
    {
        $this->connect();
        $this->blockIfDemoWrite($sql);

        $result = mysqli_query($this->ketnoi, $sql);

        if (!$result) {
            die("Query lỗi: " . mysqli_error($this->ketnoi));
        }

        return mysqli_num_rows($result);
    }

    function update_quantity($table, $where)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $sql = "UPDATE `$table` SET soluong=soluong-1 WHERE $where";
        return mysqli_query($this->ketnoi, $sql);
    }

    function update_value($table, $data, $where, $limit)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $sql = '';

        foreach ($data as $key => $value) {
            $sql .= "`$key`='" . mysqli_real_escape_string($this->ketnoi, $value) . "',";
        }

        $sql = "UPDATE `$table` SET " . trim($sql, ',') . " WHERE $where LIMIT $limit";

        return mysqli_query($this->ketnoi, $sql);
    }

    function remove_favorite($table, $where, $where1)
    {
        $this->connect();

        if (DEMO_MODE() && IS_DEMO_BLOCK_REQUEST()) {
            DEMO_RESPONSE();
        }

        $sql = "DELETE FROM `$table` WHERE $where AND $where1";

        return mysqli_query($this->ketnoi, $sql);
    }
}