<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class LogActivity extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->model('User_model');
        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        // Hanya admin yang bisa melihat log
        if ($this->session->userdata('role') !== 'admin') {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('dashboard');
        }
    }

    public function index() {
        // Otomatis hapus log > 3 bulan (90 hari)
        $this->User_model->cleanup_logs(90);

        $data['title'] = 'Log Aktivitas';

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('log_activity/index', $data);
        $this->load->view('templates/footer');
    }

    public function ajax_data() {
        if (!$this->input->is_ajax_request()) {
            exit('No direct script access allowed');
        }

        $draw      = (int) $this->input->post('draw');
        $start     = (int) $this->input->post('start');
        $length    = (int) $this->input->post('length');
        $search    = $this->input->post('search')['value'] ?? '';
        $order_col = (int) ($this->input->post('order')[0]['column'] ?? 0);
        $order_dir = $this->input->post('order')[0]['dir'] ?? 'desc';

        $total_records    = $this->User_model->count_all_logs();
        $filtered_records = $this->User_model->count_filtered_logs($search);
        $data_rows        = $this->User_model->get_datatables_logs($start, $length, $search, $order_col, $order_dir);

        $data = [];
        foreach ($data_rows as $l) {
            $badge_class = 'bg-secondary';
            $icon = 'bi-dot';
            $tipe_lower = strtolower($l->tipe);
            
            if (strpos($tipe_lower, 'login') !== false) { $badge_class = 'bg-info'; $icon = 'bi-box-arrow-in-right'; }
            elseif (strpos($tipe_lower, 'create') !== false || strpos($tipe_lower, 'tambah') !== false) { $badge_class = 'bg-success'; $icon = 'bi-plus-circle'; }
            elseif (strpos($tipe_lower, 'update') !== false || strpos($tipe_lower, 'ubah') !== false || strpos($tipe_lower, 'edit') !== false) { $badge_class = 'bg-warning'; $icon = 'bi-pencil-square'; }
            elseif (strpos($tipe_lower, 'delete') !== false || strpos($tipe_lower, 'hapus') !== false) { $badge_class = 'bg-danger'; $icon = 'bi-trash'; }
            elseif (strpos($tipe_lower, 'download') !== false) { $badge_class = 'bg-primary'; $icon = 'bi-download'; }
            elseif (strpos($tipe_lower, 'logout') !== false) { $badge_class = 'bg-dark'; $icon = 'bi-box-arrow-right'; }

            $waktu_html = '
                <div class="d-flex flex-column">
                    <span class="text-sm font-weight-bold mb-0">' . date('d M Y', strtotime($l->created_at)) . '</span>
                    <small class="text-muted">' . date('H:i:s', strtotime($l->created_at)) . '</small>
                </div>';

            $user_html = '
                <div class="d-flex align-items-center">
                    <div class="avatar avatar-sm me-2 bg-gradient-light d-flex align-items-center justify-content-center text-primary rounded-circle" style="width: 32px; height: 32px; background: #f8fafc;">
                        <i class="bi bi-person"></i>
                    </div>
                    <div class="d-flex flex-column">
                        <span class="text-sm font-weight-bold mb-0">' . htmlspecialchars($l->nama_lengkap ?? 'User Dihapus') . '</span>
                        <small class="text-muted text-xs">' . ucfirst($l->role ?? 'N/A') . '</small>
                    </div>
                </div>';

            $tipe_html = '
                <span class="badge ' . $badge_class . ' d-inline-flex align-items-center px-2 py-1" style="border-radius: 6px; font-size: 0.7rem;">
                    <i class="bi ' . $icon . ' me-1"></i>' . strtoupper($l->tipe) . '
                </span>';

            $data[] = [
                $waktu_html,
                $user_html,
                $tipe_html,
                htmlspecialchars($l->aktivitas),
                '<code class="text-xs text-muted">' . $l->ip_address . '</code>'
            ];
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'draw'            => $draw,
                'recordsTotal'    => $total_records,
                'recordsFiltered' => $filtered_records,
                'data'            => $data,
            ]));
    }

    public function bersihkan() {
        if ($this->User_model->clear_all_logs()) {
            $this->User_model->log_activity($this->session->userdata('user_id'), 'delete', 'Membersihkan seluruh log aktivitas sistem');
            $this->session->set_flashdata('success', 'Seluruh log aktivitas berhasil dibersihkan!');
        } else {
            $this->session->set_flashdata('error', 'Gagal membersihkan log!');
        }
        redirect('log-activity');
    }
}
