<?php

namespace App\Controllers\Panel\Whatsapp;

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

class History extends BC
{
    use ResponseTrait;
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        $data['page_title'] = "Whatsapp - Riwayat Pesan";
        return view('Panel/Whatsapp/history', $data);
    }
    public function all()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $did = $this->request->getVar('device');
        $sid = $this->request->getVar('sender');
        $start = $this->request->getVar('start');
        $end = $this->request->getVar('end');
        $db = db_connect();
        $wm = $db->table('whatsapp_message wm');
        $wm->join('users u', 'u.id=wm.user_id', 'left');
        $wm->join('whatsapp_device wd', 'wd.id=wm.device_id');
        $wm->select("wd.nama device_name,IFNULL(u.fullname,'DELETED USER') sender_name,wm.nomor,wm.message,wm.created_at");
        if (is_numeric($sid)) $wm->where('wm.user_id', $sid);
        if (is_numeric($did)) $wm->where('wm.device_id', $did);
        if ($start && $end) {
            $wm->where("(CASE WHEN wm.created_at BETWEEN $start AND $end THEN '1' ELSE '0' END)=", '1', false);
        } else
        if ($start) {
            $wm->where("wm.created_at >=", $start);
        } else
        if ($end) {
            $wm->where("wm.created_at <=", $end);
        }
        $data['data'] = $wm->get()->getResultArray();
        return $this->respond($data);
    }
}
