<?php
// ============================================================
//  db.php — Database Connection
//  Place this in: /admin/includes/db.php
//  Include on every page: require_once 'includes/db.php';
// ============================================================

// ── Configuration ────────────────────────────────────────────
define('DB_HOST',     'localhost');
define('DB_NAME',     'admin_panel_db');
define('DB_USER',     'root');         // ← Change to your DB username
define('DB_PASS',     '');             // ← Change to your DB password
define('DB_CHARSET',  'utf8mb4');
// ─────────────────────────────────────────────────────────────

// ── Session Config (set before any session_start()) ──────────
define('SESSION_LIFETIME', 3600);      // 1 hour
define('ADMIN_SESSION_KEY', 'admin_logged_in');
// ─────────────────────────────────────────────────────────────

/**
 * Returns a singleton PDO connection.
 * Usage anywhere: $pdo = db();
 */
function db(): PDO {
    static $pdo = null;

    if ($pdo === null) {
        $dsn = sprintf(
            'mysql:host=%s;dbname=%s;charset=%s',
            DB_HOST, DB_NAME, DB_CHARSET
        );

        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        try {
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            // In production: log the error, show a friendly page
            error_log('[DB ERROR] ' . $e->getMessage());
            die(json_encode([
                'error' => 'Database connection failed. Please try again later.'
            ]));
        }
    }

    return $pdo;
}


// ── Helper: Run a query and return all rows ───────────────────
function db_fetch_all(string $sql, array $params = []): array {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

// ── Helper: Run a query and return one row ────────────────────
function db_fetch_one(string $sql, array $params = []): ?array {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $row = $stmt->fetch();
    return $row ?: null;
}

// ── Helper: Run INSERT / UPDATE / DELETE, return affected rows ─
function db_execute(string $sql, array $params = []): int {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->rowCount();
}

// ── Helper: Get last inserted ID ─────────────────────────────
function db_last_id(): string {
    return db()->lastInsertId();
}
