<?php

namespace App\Controllers\Panel\Whatsapp;

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

class Send extends BC
{
    use ResponseTrait;
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        $data['page_title'] = "Whatsapp - Kirim Pesan";
        return view('Panel/Whatsapp/send', $data);
    }

    public function contactList()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $photo_link = base_url("") . config('app')->imgPath . "/users/";
        $db = db_connect();
        $staff = $db->table('users u');
        $staff->join('users_roles ur', 'ur.user_id=u.id');
        $staff->select("u.id,CONCAT('$photo_link',u.photo)photo,u.fullname,u.phone,'staff' ut");
        $staff->whereIn('role_id', [2, 3, 4]);
        $staff = $staff->get()->getResultArray();
        $siswa = $db->table('m_siswa ms');
        $siswa->select("id,nama fullname,CONCAT('$photo_link',ms.photo)photo,phone,'siswa' ut");
        $siswa = $siswa->get()->getResultArray();
        $contact = [...$staff, ...$siswa];
        return $this->respond($contact);
    }
    public function send()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }

        $message = $this->request->getVar('message');
        $users = $this->request->getVar('users');
        if (!$message) return $this->fail("Pesan tidak valid");
        if (!$users) return $this->fail("Kontak tidak valid");
        $swid = [];
        $sfid = [];
        foreach ((array)$users as $u) {
            if ($u->ut == 'staff') $sfid[] = $u->id;
            else $swid[] = $u->id;
        }
        $config = json_decode(options('whatsapp'), true);
        $db = db_connect();
        $where = [
            'is_connected' => '1',
            'status' => '1',
        ];
        if (!$config['randomize']) $where['is_default'] = '1';
        $devices = $db->table('whatsapp_device')->getWhere($where)->getResultArray();
        if (count($devices) <= 0) return $this->fail("Tidak ada perangkat aktif");
        $msgData = [
            'success' => 0,
            'failed' => 0,
        ];
        $msgs = [];
        if ($sfid) {
            $staff = $db->table('users u');
            $staff->join('users_roles ur', 'ur.user_id=u.id');
            $staff->select("u.fullname,u.phone");
            $staff->whereIn('u.id', $sfid);
            foreach ($staff->get()->getResultArray() as $k => $v) {
                $device = $config['randomize'] ? $devices[random_int(0, count($devices) - 1)] : $devices[0];
                if (!$v['phone']) continue;
                $msg = $message;
                $msg = str_replace("{nama}", $v['fullname'], $msg);
                $s = $k * 10;
                $rm = sendWAMessage($device['device_id'], [
                    'schedule' => date('Y-m-d H:i:s', strtotime("+$s seconds")),
                    'message' => $msg,
                    'number' => $v['phone'],
                ]);
                $msgs[] = [
                    'user_id' => user()->id,
                    'device_id' => $device['id'],
                    'nomor' => $v['phone'],
                    'message' => $msg,
                    'created_at' => time(),
                    'updated_at' => time(),
                ];
                if ($rm['status']) $msgData['success']++;
                if (!$rm['status']) $msgData['failed']++;
            }
        }
        if ($swid) {
            $siswa = $db->table('m_siswa ms');
            $siswa->join('m_kelas mk', 'mk.id=ms.kelas_id');
            $siswa->select("ms.nama fullname,ms.phone,mk.nama kelas");
            $siswa->whereIn('ms.id', $swid);
            foreach ($siswa->get()->getResultArray() as $k => $v) {
                $device = $config['randomize'] ? $devices[random_int(0, count($devices) - 1)] : $devices[0];
                if (!$v['phone']) continue;
                $msg = $message;
                $msg = str_replace("{nama}", $v['fullname'], $msg);
                $msg = str_replace("{kelas}", $v['kelas'], $msg);
                $s = $k * 10;
                $rm = sendWAMessage($device['device_id'], [
                    'schedule' => date('Y-m-d H:i:s', strtotime("+$s seconds")),
                    'message' => $msg,
                    'number' => $v['phone'],
                ]);
                $msgs[] = [
                    'user_id' => user()->id,
                    'device_id' => $device['id'],
                    'nomor' => $v['phone'],
                    'message' => $msg,
                    'created_at' => time(),
                    'updated_at' => time(),
                ];
                if ($rm['status']) $msgData['success']++;
                if (!$rm['status']) $msgData['failed']++;
            }
        }
        $db->table('whatsapp_message')->insertBatch($msgs);
        setLog('Mengirim pesan whatsapp');
        return $this->respond(['message' => "Pesan berhasil : $msgData[success].<br>Pesan gagal : $msgData[failed]"]);
    }
}
