
<?php

class CrudService
{

    private $conn;

    public function __construct($db)
    {
        $this->conn = $db;
    }


    public function create($table, $data)
    {

        $columns = array_keys($data);

        $fields = implode(',', $columns);

        $placeholders = ':' . implode(',:', $columns);

        $query = "INSERT INTO $table ($fields) VALUES ($placeholders)";

        $stmt = $this->conn->prepare($query);

        $stmt->execute($data);

        return $this->conn->lastInsertId();

    }



    public function update($table, $data, $id)
    {

        $fields = [];

        foreach ($data as $key => $value) {
            $fields[] = "$key = :$key";
        }

        $fields = implode(',', $fields);

        $query = "UPDATE $table SET $fields WHERE id = :id";

        $data['id'] = $id;

        $stmt = $this->conn->prepare($query);

        return $stmt->execute($data);

    }



    public function softDelete($table, $id)
    {

        $query = "UPDATE $table SET status = 0 WHERE id = :id";

        $stmt = $this->conn->prepare($query);

        return $stmt->execute([
            ':id'=>$id
        ]);

    }



    public function get($table, $id)
    {

        $query = "SELECT * FROM $table WHERE id = :id";

        $stmt = $this->conn->prepare($query);

        $stmt->execute([
            ':id'=>$id
        ]);

        return $stmt->fetch();

    }



    public function list($table, $options = [])
    {

        $page  = $options['page'] ?? 1;
        $limit = $options['limit'] ?? 10;

        $search = $options['search'] ?? null;
        $status = $options['status'] ?? null;
        $sort   = $options['sort'] ?? 'id';
        $order  = $options['order'] ?? 'DESC';


        $offset = ($page - 1) * $limit;

        $where = [];
        $params = [];


        if ($status !== null) {
            $where[] = "status = :status";
            $params['status'] = $status;
        }


        if ($search) {
            $where[] = "name LIKE :search";
            $params['search'] = "%$search%";
        }


        $whereSQL = '';

        if (!empty($where)) {
            $whereSQL = "WHERE " . implode(" AND ", $where);
        }


        $query = "

            SELECT * FROM $table
            $whereSQL
            ORDER BY $sort $order
            LIMIT $limit OFFSET $offset

        ";


        $stmt = $this->conn->prepare($query);

        $stmt->execute($params);

        return $stmt->fetchAll();

    }

}
