<?php

namespace App\Controllers\Pesaing;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Dataswot extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->DataswotModel = model('App\Models\Pesaing\DataswotModel');
    }

    private function setJsonHeader()
    {
        return $this->response->setHeader('Content-Type', 'application/json');
    }

    //Validation Rule
    private function ruleData($id = null)
    {
        return [
            'id' => 'trim',
            'id_pesaing' => 'required|numeric',
            'id_produk' => 'required|numeric',
            'kekuatan' => 'required|max_length[500]',
            'kelemahan' => 'required|max_length[500]',
            'kesempatan' => 'required|max_length[500]',
            'ancaman' => 'required|max_length[500]',
        ];
    }

    public function index()
    {
        //function($modul, $menu) --------
        $links = genlinks('pesaing', 'dataswot');

        $link_show = base_url('pesaing/dataswot/show/');

        $rekam = $links['rekam']['status'];
        $link_rekam = base_url('pesaing/dataswot/new');

        $ubah = $links['ubah']['status'];
        $link_ubah = base_url('pesaing/dataswot/edit/');

        $hapus = $links['hapus']['status'];
        $link_hapus = base_url('pesaing/dataswot/delete');

        return view('pesaing/swot/swot_list', [
            'rekam' => $rekam,
            'link_show' => $link_show,
            'link_rekam' => $link_rekam,
            'ubah' => $ubah,
            'link_ubah' => $link_ubah,
            'hapus' => $hapus,
            'link_hapus' => $link_hapus,
        ]);
    }

    public function datagrid()
    {
        $this->setJsonHeader();

        $user_id = auth()->id();
        $id_kantor = $this->DataswotModel->kantor_user($user_id);

        $page           = trim($this->request->getPost('page')) ? trim($this->request->getPost('page')) : 1;
        $rows           = trim($this->request->getPost('rows')) ? trim($this->request->getPost('rows')) : 10;
        $sort           = trim($this->request->getPost('sort'));
        $order          = trim($this->request->getPost('order'));
        $filterRules    = trim($this->request->getPost('filterRules'));
        $start          = ($page - 1) * $rows;

        if ($sort && $order) {
            $sortOrder = multi_sort($sort, $order);
        } else {
            $sortOrder = multi_sort('id', 'ASC');
        }

        $datas = $this->DataswotModel->get_rows2($rows, $start, $filterRules, $sortOrder, $id_kantor);
        foreach ($datas as $k => $v)
        {
            $datas[$k]->id = encrypt_url($v->id);
        }

        $res['total']  = $this->DataswotModel->get_total2($filterRules, $id_kantor);
        $res['rows']   = $datas;

        return $this->response->setJSON($res);
    }

    public function show($id)
    {
        $row = $this->DataswotModel->find_by_id(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        return view('pesaing/swot/swot_show', [
            'back' => base_url('pesaing/dataswot'),
            'id' => encrypt_url($row->id),
            'id_pesaing' => $row->id_pesaing,
            'id_produk' => $row->id_produk,
            'nama_pesaing' => $row->nama_pesaing,
            'nama_produk' => $row->uraian,
            'lati' => $row->lati,
            'longi' => $row->longi,
            'kekuatan' => $row->kekuatan,
            'kelemahan' => $row->kelemahan,
            'kesempatan' => $row->kesempatan,
            'ancaman' => $row->ancaman,
            'username' => $row->username,
            'wkt_rek' => $row->wkt_rek,
            'map_api' => $map_api,
        ]);
    }

    public function new()
    {
        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        $id_kantor = $this->DataswotModel->get_user_kantor(auth()->id());
        
        return view('pesaing/swot/swot_form', [
            'action' => base_url('pesaing/dataswot/create'),
            'back' => base_url('pesaing/dataswot'),
            'button' => 'SIMPAN DATA',
            'id' => '',
            'id_pesaing' => '',
            'id_produk' => '',
            'kekuatan' => '',
            'kelemahan' => '',
            'kesempatan' => '',
            'ancaman' => '',
            'dd_pesaing' => $this->DataswotModel->dd_pesaing($id_kantor),
            'dd_produk' => $this->DataswotModel->dd_produk(),
            'id_kantor' => $id_kantor,
            'map_api' => $map_api,
        ]);
    }

    public function create()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('dataswot', 'rekam')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //Collect form data
        $data = [
            'id_pesaing' => $this->request->getPost('id_pesaing', FILTER_SANITIZE_NUMBER_INT),
            'id_produk' => $this->request->getPost('id_produk', FILTER_SANITIZE_NUMBER_INT),
            'kekuatan' => $this->request->getPost('kekuatan', FILTER_SANITIZE_SPECIAL_CHARS),
            'kelemahan' => $this->request->getPost('kelemahan', FILTER_SANITIZE_SPECIAL_CHARS),
            'kesempatan' => $this->request->getPost('kesempatan', FILTER_SANITIZE_SPECIAL_CHARS),
            'ancaman' => $this->request->getPost('ancaman', FILTER_SANITIZE_SPECIAL_CHARS),
            'id_rek' => auth()->id(),
            'wkt_rek' => date('Y-m-d H:i:s'),
        ];

        $vrData = $this->ruleData();
        //jika validasi gagal
        if (!$this->validate($vrData)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        if (!$this->DataswotModel->insert($data)) {
            return $this->fail($this->DataswotModel->errors(), 500);
        }

        return $this->respond(['message' => B_SIMPAN], 201);
    }

    public function edit($id)
    {
        $row = $this->DataswotModel->find_by_id(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        $map_api = getenv('GOOGLE_MAPS_API_KEY');
        $id_kantor = $this->DataswotModel->get_user_kantor(auth()->id());
        
        return view('pesaing/swot/swot_form', [
            'action' => base_url('pesaing/dataswot/update'),
            'back' => base_url('pesaing/dataswot'),
            'button' => 'UBAH DATA', 
            'id' => encrypt_url($row->id),
            'id_pesaing' => $row->id_pesaing,
            'id_produk' => $row->id_produk,
            'kekuatan' => $row->kekuatan,
            'kelemahan' => $row->kelemahan,
            'kesempatan' => $row->kesempatan,
            'ancaman' => $row->ancaman,
            'dd_pesaing' => $this->DataswotModel->dd_pesaing($id_kantor),
            'dd_produk' => $this->DataswotModel->dd_produk(),
            'id_kantor' => $id_kantor,
            'map_api' => $map_api,
        ]);
    }

    public function update()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('dataswot', 'ubah')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        //collect form data
        $id = decrypt_url(trim($this->request->getPost('id')));

        $data = [
            'id'  => $id,
            'id_pesaing' => $this->request->getPost('id_pesaing', FILTER_SANITIZE_NUMBER_INT),
            'id_produk' => $this->request->getPost('id_produk', FILTER_SANITIZE_NUMBER_INT),
            'kekuatan' => $this->request->getPost('kekuatan', FILTER_SANITIZE_SPECIAL_CHARS),
            'kelemahan' => $this->request->getPost('kelemahan', FILTER_SANITIZE_SPECIAL_CHARS),
            'kesempatan' => $this->request->getPost('kesempatan', FILTER_SANITIZE_SPECIAL_CHARS),
            'ancaman' => $this->request->getPost('ancaman', FILTER_SANITIZE_SPECIAL_CHARS),
        ];

        $vrData = $this->ruleData($id);
        //jika validasi gagal
        if (!$this->validate($vrData)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        if (!$this->DataswotModel->update($id, $data)) {
            return $this->fail($this->DataswotModel->errors(), 500);
        }

        return $this->respond(['message' => B_UBAH], 200);
    }

    public function delete()
    {
        $this->setJsonHeader();

        //jika tdk memiliki akses utk rekam data
        if (!priv_menu('dataswot', 'hapus')) {
            return $this->fail(['message' => NO_AKSES], 403);
        }

        $ids  = $this->request->getPost('ids');

        $del = array();
        foreach ($ids as $id) {
            $del[] = decrypt_url($id);
        }

        if (!$this->DataswotModel->delete($del)) {
            return $this->fail($this->DataswotModel->errors(), 500);
        } else {
            return $this->respond(['message' => count($del).lang('App.delete_success')]);
        }
    }

    //AMBIL DETAIL PESAING BY ID
    public function get_pesaing_detail()
    {
        $this->setJsonHeader();

        $id_pesaing = $this->request->getPost('id_pesaing');
        $data = $this->DataswotModel->get_pesaing_detail($id_pesaing);

        return json_encode($data);
    }
}
