<?php

namespace App\Controllers\Account;

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

class Profile extends BaseController
{
    use ResponseTrait;

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

    public function index()
    {
        $users = auth()->getProvider();
        $user  = $users->findById(auth()->id());
        
        if (! $user) {
            exit('Data tidak ditemukan');
        }

        $row  = $this->ProfileModel->get_by_id(auth()->id());

        return view('account/profile/profile_show', [
            'avatar'                 => base_url('files/avatar/'.$row->avatar),
            'username'               => $user->username,
            'email'                  => $user->email,
            'last_active'            => $user->last_active,
            'row'                    => $row,
            'action_change_password' => base_url('account/profile/update_password'),
            'password'               => '',
            'password_confirm'       => '',
            'action_change_avatar'   => base_url('account/profile/update_avatar'),
            'action_change_wa' => base_url('account/profile/update'),
        ]);
    }

    public function datagrid()
    {
        header('Content-Type: application/json');

        $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 = NULL;
        }

        //id user
        $users = auth()->getProvider();
        $id_user  = auth()->id();

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

        // save to session for export excel
        $sessionDatagrid = array(
            'sortOrder' => $sortOrder,
            'filterRules' => $filterRules,
        );
        $this->session->set($sessionDatagrid);

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


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

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

    public function update()
    {
        $users = auth()->getProvider();
        $user  = $users->findById(auth()->id());

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

        header('Content-Type: application/json');
        $id = auth()->id();
        $rules = [
            'whatsapp' => 'required|numeric',
        ];
        $data = [
            'whatsapp' => trim($this->request->getPost('whatsapp', FILTER_SANITIZE_NUMBER_INT)),
        ];

        if ($this->validate($rules)) {
            $users = auth()->getProvider();

            $user = $users->findById(auth()->id());
            $user->fill($data);
            $users->save($user);

            return $this->respond(['message' => 'Whatsapp number changed!']);
        }
        return $this->fail($this->validation->getErrors(), 400);
    }

    public function update_password()
    {
        $users = auth()->getProvider();
        $user  = $users->findById(auth()->id());

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

        header('Content-Type: application/json');

        $id       = auth()->id();
        $password = trim($this->request->getPost('password'));

        $rules = [
            'password'         => 'required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|strong_password',
            'password_confirm' => [
                'label' => 'password confirm',
                'rules' => 'trim|required|regex_match[/^[a-zA-Z0-9\s.,@-]+$/]|matches[password]',
            ],
        ];

        $data = [
            'password' => $this->request->getPost('password', FILTER_SANITIZE_SPECIAL_CHARS),
        ];

        if ($this->validate($rules)) {
            $users = auth()->getProvider();

            $user = $users->findById(auth()->id());
            $user->fill($data);
            $users->save($user);

            return $this->respond(['message' => lang('App.change_password_success')]);
        }

        return $this->fail($this->validation->getErrors(), 400);
    }

    public function update_avatar()
    {
        $users = auth()->getProvider();
        $user  = $users->findById(auth()->id());

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

        $validationRule = [
            'avatar' => [
                'label' => 'Avatar',
                'rules' => [
                    'uploaded[avatar]',
                    'is_image[avatar]',
                    'mime_in[avatar,image/jpg,image/jpeg,image/png]',
                    'max_size[avatar,1024]',
                    //'max_dims[avatar,512,512]',
                ],
            ],
        ];
        
        if (! $this->validate($validationRule)) {
            return $this->fail($this->validation->getErrors(), 400);
        } else {
            $file = $this->request->getFile('avatar');

            //nama file baru
            $id_user = auth()->id();
            $ts = str_replace(['-', ':', ' '], '', date('Y-m-d H:i:s'));
            $fileExtension = $file->getExtension();
            $newFileName = "{$id_user}_{$ts}.{$fileExtension}";

            // Pindahkan file ke direktori uploads dengan nama baru
            if ($file->move(ROOTPATH . 'public/files/avatar', $newFileName)) {
                $data = [
                    'avatar'  => $newFileName,
                ];

                $users = auth()->getProvider();

                $user = $users->findById(auth()->id());
                $user->fill($data);
                $users->save($user);

                return $this->respond(['message' => lang('App.change_avatar_success')]);

            } else {
                return $this->fail(['errors' => 'Something went wrong.'], 400);
            }
        }

        return $this->fail(['errors' => 'The file has already been moved.'], 400);
    }
}
