<?php

namespace App\Libraries;

use Config\Database;

class DataTables
{
    protected $db;

    public function __construct()
    {
        $this->db = Database::connect();
    }

    public function BuildDatatables($query, $where, $isWhere, $search, $table)
    {
        $request = service('request');

        $draw   = intval($request->getPost("draw"));
        $start  = intval($request->getPost("start"));
        $length = intval($request->getPost("length"));
        $searchValue = $request->getPost("search")['value'] ?? '';

        // SEARCH
        if (!empty($searchValue)) {
            $like = [];
            foreach ($search as $field) {
                $like[] = "$field LIKE '%$searchValue%'";
            }
            $isWhere .= " AND (" . implode(" OR ", $like) . ")";
        }

        // ORDER
        $orderBy = "";
        $orderData = $request->getPost("order");
        if ($orderData) {
            $columnIndex = $orderData[0]['column'];
            $dir = $orderData[0]['dir'];
            $orderBy = " ORDER BY {$search[$columnIndex]} $dir";
        }

        // LIMIT
        $limit = " LIMIT $start, $length";

        // FINAL QUERY
        $finalQuery = "$query WHERE $isWhere $orderBy $limit";
        $data = $this->db->query($finalQuery)->getResultArray();

        // TOTAL FILTER
        $filterQuery = "$query WHERE $isWhere";
        $filtered = $this->db->query($filterQuery)->getNumRows();

        // TOTAL DATA
        $total = $this->db->table($table)->countAllResults();

        return json_encode([
            "draw" => $draw,
            "recordsTotal" => $total,
            "recordsFiltered" => $filtered,
            "data" => $data
        ]);
    }
}
