<?php

namespace App\Controllers\Panel\LainLain;

use App\Controllers\Panel\BC;
use CodeIgniter\API\ResponseTrait;

class Logs extends BC
{
    use ResponseTrait;
    public function index()
    {
        $data['page_title'] = "Riwayat Aktivitas";
        return view('Panel/LainLain/Logs/index', $data);
    }
    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $where = [];
        if ($this->request->getGet('ut')) {
            $where['user_type'] = $this->request->getGet('ut');
        } else {
            $where['user_type !='] = null;
        }
        if ($this->request->getGet('ui')) $where['la.user_id'] = $this->request->getGet('ui');
        $db = db_connect();
        $builder = $db->table('log_activity la');
        if ($where) $builder->where($where);
        if ($this->request->getGet('sd') && $this->request->getGet('ed')) {
            $sd = $this->request->getGet('sd');
            $ed = $this->request->getGet('ed');
            $builder->where("la.created_at BETWEEN '{$sd}' AND '{$ed}'", null, false);
        } elseif ($this->request->getGet('sd')) {
            $sd = $this->request->getGet('sd');
            $builder->where('la.created_at >', $sd);
        } elseif ($this->request->getGet('ed')) {
            $ed = $this->request->getGet('ed');
            $builder->where('la.created_at <', $ed);
        }
        $bu = base_url(config('app')->imgPath . "/users");
        $select = ["la.*"];
        $select[] = "(CASE WHEN u.id IS NOT NULL THEN 0 ELSE (CASE WHEN m.id IS NULL THEN 1 ELSE 0 END) END) deleted";
        $select[] = "(CASE WHEN u.id IS NOT NULL THEN u.fullname ELSE (CASE WHEN m.id IS NOT NULL THEN m.nama ELSE la.fullname END) END) fullname";
        $select[] = "CONCAT('$bu/',IFNULL((CASE WHEN u.id IS NOT NULL THEN u.photo ELSE (CASE WHEN m.id IS NOT NULL THEN m.photo ELSE NULL END) END),'profile-photo.png')) photo";
        $builder->select(implode(',', $select));
        $builder->join('users u', 'u.id=la.user_id AND la.user_type=1', 'left');
        $builder->join('m_siswa m', 'm.id=la.user_id AND la.user_type=2', 'left');
        $data = $builder->orderBy('created_at', 'DESC')->get($this->request->getGet('lim') ?? 100)->getResultArray();
        return $this->respond($data);
    }
    public function users()
    {
        $db = db_connect();
        $users = $db->table('log_activity');
        $users->select('user_id,fullname,user_type');
        $users->distinct();
        $users->orderBy('created_at', 'DESC');
        $users = $users->get()->getResultArray();
        return $this->respond($users);
    }
    public function delete()
    {
        db_connect()->table('log_activity')->truncate();
        return $this->respond(['message' => "Berhasil menghapus riwayat"]);
    }
}
