<?php
// includes/db.php - توابع دیتابیس

function executeQuery($sql, $params = []) {
    global $pdo;
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    } catch(PDOException $e) {
        return false;
    }
}

function fetchOne($sql, $params = []) {
    $stmt = executeQuery($sql, $params);
    return $stmt ? $stmt->fetch() : null;
}

function fetchAll($sql, $params = []) {
    $stmt = executeQuery($sql, $params);
    return $stmt ? $stmt->fetchAll() : [];
}

function fetchCount($sql, $params = []) {
    $stmt = executeQuery($sql, $params);
    return $stmt ? $stmt->rowCount() : 0;
}

function insertData($table, $data) {
    $fields = array_keys($data);
    $placeholders = array_map(function($f) { return ":$f"; }, $fields);
    $sql = "INSERT INTO $table (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $placeholders) . ")";
    $stmt = executeQuery($sql, $data);
    return $stmt ? $GLOBALS['pdo']->lastInsertId() : false;
}

function updateData($table, $data, $where, $whereParams = []) {
    $set = implode(', ', array_map(function($f) { return "$f = :$f"; }, array_keys($data)));
    $sql = "UPDATE $table SET $set WHERE $where";
    $params = array_merge($data, $whereParams);
    $stmt = executeQuery($sql, $params);
    return $stmt ? $stmt->rowCount() : false;
}

function deleteData($table, $where, $params = []) {
    $sql = "DELETE FROM $table WHERE $where";
    $stmt = executeQuery($sql, $params);
    return $stmt ? $stmt->rowCount() : false;
}
?>