<?php

namespace App\Database;

class Database
{
    private $pdo;
    private $host ; // یا IP سرور دیتابیس
    private $dbname ; // نام دیتابیس
    private $user ; // نام کاربری دیتابیس
    private $password ; // پسورد دیتابیس

    public function __construct()
    {
        $this->host = $_ENV['DB_HOST'];
        $this->dbname = $_ENV['DB_NAME'];
        $this->user = $_ENV['DB_USERNAME'];
        $this->password = $_ENV['DB_PASSWORD'];
        $dsn = "mysql:host={$this->host};dbname={$this->dbname};charset=utf8";
        try {
            $this->pdo = new \PDO($dsn, $this->user, $this->password);
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch (\PDOException $e) {
            die("Connection failed: " . $e->getMessage());
        }
    }

    public function query($sql, $params = [])
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    public function select($sql, $params = [])
    {
        $stmt = $this->query($sql, $params);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    public function find($sql, $params = [])
    {
        $stmt = $this->select($sql, $params);
        return $stmt ;
    }

    public function insert($table, $data)
    {
        $fields = implode(", ", array_keys($data));
        $placeholders = ":" . implode(", :", array_keys($data));
        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        $this->query($sql, $data);
        return $this->pdo->lastInsertId();
    }

    public function update($table, $data, $where)
    {
        $set = "";
        foreach ($data as $key => $value) {
            $set .= "$key = :$key, ";
        }
        $set = rtrim($set, ", ");
        $sql = "UPDATE $table SET $set WHERE $where";
        $this->query($sql, $data);
    }

    public function delete($table, $where)
    {
        $sql = "DELETE FROM $table WHERE $where";
        $this->query($sql);
    }
}


// استفاده از کلاس
//$db = new Database();
//
//// درج داده
//$data = ['name' => 'John Doe', 'email' => 'john@example.com'];
//$lastInsertId = $db->insert('users', $data);
//
//// انتخاب داده
//$users = $db->select('SELECT * FROM users');
//
//// به‌روزرسانی داده
//$updateData = ['email' => 'john.doe@example.com'];
//$db->update('users', $updateData, 'id = ' . $lastInsertId);
//
//// حذف داده
//$db->delete('users', 'id = ' . $lastInsertId);


