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

class Pesan extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();

        // Cek apakah user sudah login
        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }
    }

    public function index()
    {
        if (!check_permission('pesan', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }

        $data = [
            "active_menu" => "pesan"
        ];

        $this->load->view('partials/header', $data);
        $this->load->view('pesan/layout'); 
        $this->load->view('partials/footer');
    }

    // =========================================================
    //                  DATATABLE SERVERSIDE
    // =========================================================
    public function get_data()
    {

        if (!check_permission('pesan', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }
        
        $table          = 'notifikasi';
        $column_order   = array(null, 'created_at', 'type', 'nomor_whatsapp', 'email', 'pesan', 'status');
        $column_search  = array('pesan', 'nomor_whatsapp', 'email', 'status', 'type');
        $order          = array('created_at' => 'DESC');

        $this->db->from($table);

        $search_value = !empty($_POST['search']['value']) ? $_POST['search']['value'] : '';

        // SEARCH
        if ($search_value != '') {
            $this->db->group_start();
            foreach ($column_search as $i => $col_name) {
                if ($i === 0) {
                    $this->db->like($col_name, $search_value);
                } else {
                    $this->db->or_like($col_name, $search_value);
                }
            }
            $this->db->group_end();
        }

        // ORDER
        if (isset($_POST['order'])) {
            $col_index = $_POST['order'][0]['column'];
            $dir       = $_POST['order'][0]['dir'];
            if (isset($column_order[$col_index])) {
                $this->db->order_by($column_order[$col_index], $dir);
            }
        } else {
            $this->db->order_by(key($order), $order[key($order)]);
        }

        // PAGINATION
        if ($_POST['length'] != -1) {
            $this->db->limit($_POST['length'], $_POST['start']);
        }

        $query = $this->db->get();
        $data  = [];
        $no    = $_POST['start'];

        foreach ($query->result() as $row) {
            $no++;
            
            // Badge for 'status'
            $statusBadge = '';
            switch ($row->status) {
                case 'terkirim': $statusBadge = '<span class="badge bg-success">Terkirim</span>'; break;
                case 'proses': $statusBadge = '<span class="badge bg-info">Proses</span>'; break;
                case 'pending': $statusBadge = '<span class="badge bg-warning">Pending</span>'; break;
                case 'dibaca': $statusBadge = '<span class="badge bg-primary">Dibaca</span>'; break;
                default: $statusBadge = '<span class="badge bg-secondary">' . htmlspecialchars($row->status) . '</span>'; break;
            }

            // Type display
            $typeDisplay = '';
            switch ($row->type) {
                case 'wa_official': $typeDisplay = 'WhatsApp Official'; break;
                case 'wa_unofficial': $typeDisplay = 'WhatsApp Unofficial'; break;
                case 'email': $typeDisplay = 'Email'; break;
                default: $typeDisplay = htmlspecialchars($row->type); break;
            }

            $penerima = !empty($row->nomor_whatsapp) ? htmlspecialchars($row->nomor_whatsapp) : htmlspecialchars($row->email);

            $data[] = [
                $no,
                date('d-m-Y H:i:s', strtotime($row->created_at)),
                $typeDisplay,
                $penerima,
                '<div class="truncate-text">' . htmlspecialchars($row->pesan) . '</div>',
                $statusBadge
            ];
        }

        // COUNT TOTAL RECORDS
        $this->db->from($table);
        if ($search_value != '') {
            $this->db->group_start();
            foreach ($column_search as $i => $col_name) {
                if ($i === 0) {
                    $this->db->like($col_name, $search_value);
                } else {
                    $this->db->or_like($col_name, $search_value);
                }
            }
            $this->db->group_end();
        }
        $recordsFiltered = $this->db->count_all_results();

        $output = [
            "draw"            => intval($_POST['draw']),
            "recordsTotal"    => $this->db->count_all($table),
            "recordsFiltered" => $recordsFiltered,
            "data"            => $data
        ];

        echo json_encode($output);
    }
}
