<?php
class DB {
    private $last_id = 0;

    public function dBCxn() {
        $pdo = null;
        try {
            $pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASSWORD);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // Force UTF-8 on this session — the DSN `charset=utf8mb4` param is silently ignored on
            // some WAMP builds of the MySQL Native Driver, causing multi-byte chars (·, →, etc.)
            // to double-encode via CP850. Explicit SET NAMES is the reliable belt-and-braces.
            $pdo->exec("SET NAMES utf8mb4");
        } catch (Exception $e) {
            echo '<h3>Database connection error. Please contact the administrator.</h3>';
            if (DEBUG) echo '<pre>' . $e->getMessage() . '</pre>';
        }
        return $pdo;
    }

    public function setLastId($last_id) { $this->last_id = $last_id; }
    public function getLastId() { return $this->last_id; }

    public function insertUpdate($sql, $arr_info) {
        $feedback = ["success" => 0, "last_id" => 0];
        $cx = $this->dBCxn();
        $stmt = $cx->prepare($sql);
        $ok = $stmt->execute($arr_info);
        if ($ok) {
            $feedback["success"] = $stmt->rowCount();
            $feedback["last_id"] = $cx->lastInsertId();
        }
        $cx = null;
        return $feedback;
    }

    public function mySelect($sql, $arr_info) {
        $re = null;
        $cx = $this->dBCxn();
        $stmt = $cx->prepare($sql);
        $ok = $stmt->execute($arr_info);
        if ($ok) {
            $re = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        $cx = null;
        return $re;
    }

    public static function setLimitSql($pg_no, $rows_per_pg) {
        return 'LIMIT ' . (($pg_no - 1) * $rows_per_pg) . ',' . $rows_per_pg;
    }
}
