<?php

namespace App\Controllers;

/**
 * Port dari Home::signin()/signup()/signout() (CI3, storefront). Dipisah
 * ke controller sendiri (bukan numpuk di Home) supaya lebih jelas, tapi
 * URL lama (home/signin, home/signup, home/signout) dipertahankan lewat
 * Routes.php agar link/bookmark lama tidak rusak.
 *
 * Beda dari sisi admin: customer pakai tabel `userdata`, session key
 * usrid/lvl/status (BUKAN isMasok), dan tidak ada gerbang URL rahasia.
 */
class Auth extends BaseController
{
    public function signin(string $pwreset = 'none')
    {
        $url = session()->get('url') ?? site_url();

        if ($this->request->getPost('email') !== null && $pwreset === 'none') {
            $email = (string) $this->request->getPost('email');

            $user = $this->db->table('userdata')
                ->where('username', $email)
                ->orWhere('nohp', $email)
                ->get()
                ->getRow();

            if ($user === null) {
                return $this->response->setJSON([
                    'success' => false,
                    'csrf'    => csrf_hash(),
                ]);
            }

            if ((int) $user->status === 0) {
                session()->set('id', $user->id);

                return $this->response->setJSON([
                    'success'  => true,
                    'redirect' => site_url('home/signup/verifikasi'),
                    'csrf'     => csrf_hash(),
                ]);
            }

            $pass = (string) $this->request->getPost('pass');
            if ($this->func->verifyPassword($pass, $user->password)) {
                if ($this->func->isLegacyPassword($user->password)) {
                    $this->db->table('userdata')->where('id', $user->id)->update(['password' => $this->func->hashPassword($pass)]);
                }

                session()->set([
                    'usrid'  => $user->id,
                    'lvl'    => $user->level,
                    'status' => $user->status,
                ]);

                $this->func->addlog([
                    'usrid'   => $user->id,
                    'ip'      => $this->request->getIPAddress(),
                    'type'    => 'web',
                    'ket'     => 'login sukses',
                    'created' => date('Y-m-d H:i:s'),
                ]);

                return $this->response->setJSON(['success' => true, 'redirect' => $url]);
            }

            return $this->response->setJSON([
                'success'  => false,
                'redirect' => $url,
                'csrf'     => csrf_hash(),
            ]);
        }

        if ($pwreset === 'pwreset') {
            if ($this->request->getPost('email') !== null) {
                if ($this->func->resetPass((string) $this->request->getPost('email'))) {
                    return $this->response->setJSON(['success' => true, 'redirect' => $url]);
                }

                return $this->response->setJSON(['success' => false, 'redirect' => $url, 'msg' => 'gagal mengirim email']);
            }

            return view('customer/head', ['func' => $this->func, 'db' => $this->db, 'titel' => 'reset password'])
                . view('customer/main/pwreset', ['func' => $this->func, 'db' => $this->db])
                . view('customer/foot', ['func' => $this->func, 'db' => $this->db]);
        }

        return view('customer/head', ['func' => $this->func, 'db' => $this->db, 'titel' => 'Masuk'])
            . view('customer/signin', ['func' => $this->func, 'db' => $this->db, 'nama' => $this->func->globalset('nama')])
            . view('customer/foot', ['func' => $this->func, 'db' => $this->db]);
    }

    public function signup(string $pwreset = 'none')
    {
        $set = $this->func->globalset('semua');
        $now = date('Y-m-d H:i:s');
        $data = ['func' => $this->func, 'db' => $this->db];

        if ($this->request->getGet('verify') !== null) {
            $selesai = false;
            if ($this->request->getPost('verify') !== null) {
                $verifid = $this->func->arrDec((string) $this->request->getGet('verify'));
                if ($verifid !== null && isset($verifid['id'])) {
                    $this->db->table('userdata')->where('id', (int) $verifid['id'])->update(['status' => 1]);
                    $selesai = true;
                }
            }

            return view('customer/head', $data + ['titel' => 'Verifikasi Alamat Email'])
                . view('customer/main/sukses_verifikasi', $data + ['selesai' => $selesai])
                . view('customer/foot', $data);
        }

        if ($this->request->getPost('id') !== null && $pwreset === 'kirimulang') {
            $id = (int) $this->func->decode((string) $this->request->getPost('id'));

            if ($this->func->verifEmail($id)) {
                $this->func->verifWA($id);

                return $this->response->setJSON(['success' => true, 'csrf' => csrf_hash(), 'message' => '']);
            }

            return $this->response->setJSON(['success' => false, 'csrf' => csrf_hash(), 'message' => 'alamat email sudah terdaftar']);
        }

        if ($this->request->getPost('email') !== null && $pwreset === 'cekemail') {
            $ada = $this->db->table('userdata')->where('username', $this->request->getPost('email'))->countAllResults() > 0;

            if ($ada) {
                return $this->response->setJSON(['success' => false, 'csrf' => csrf_hash(), 'message' => 'alamat email sudah terdaftar']);
            }

            return $this->response->setJSON(['success' => true, 'csrf' => csrf_hash(), 'message' => '']);
        }

        if ($this->request->getPost('email') !== null && $pwreset === 'none') {
            return $this->prosesDaftar($set, $now);
        }

        if ($pwreset === 'verifikasi') {
            return view('customer/head', $data + ['titel' => 'Verifikasi Alamat Email'])
                . view('customer/main/sukses_verifikasi', $data + ['belumverif' => true])
                . view('customer/foot', $data);
        }

        return view('customer/head', $data + ['titel' => 'Mendaftar'])
            . view('customer/signup', $data)
            . view('customer/foot', $data);
    }

    /**
     * Pendaftaran baru -- port dari dua blok if/else CI3 yang nyaris
     * identik (upline_wajib true/false) jadi satu alur, validasi tetap
     * persis sama: email/no HP belum dipakai, dan upline harus valid
     * KALAU upline_wajib aktif.
     */
    private function prosesDaftar($set, string $now)
    {
        $email = (string) $this->request->getPost('email');
        $nohp  = (string) $this->request->getPost('nohp');
        $nama  = (string) $this->request->getPost('nama');
        $pass  = (string) $this->request->getPost('pass');
        $uplineInput = $this->request->getPost('upline');

        $emailDipakai = $this->db->table('userdata')->where('username', $email)->countAllResults() > 0;
        $nohpDipakai  = $this->db->table('userdata')->where('nohp', $nohp)->countAllResults() > 0;

        $uplineRow = $uplineInput !== null
            ? $this->db->table('userdata')->where('id', $uplineInput)->get()->getRow()
            : null;
        $upline = $uplineRow !== null ? (int) $uplineRow->id : 0;

        $uplineWajib = (bool) ($set->upline_wajib ?? false);

        if ($emailDipakai || $nohpDipakai || ($uplineWajib && $upline === 0)) {
            $pesan = $emailDipakai ? 'Email sudah terdaftar!' : ($nohpDipakai ? 'No HP sudah terdaftar!' : 'ID Upline tidak dikenal!');

            return $this->response->setBody('<script type="text/javascript">confirm(' . json_encode($pesan) . ');history.back();</script>');
        }

        $this->db->table('userdata')->insert([
            'username'  => $email,
            'nama'      => $nama,
            'nohp'      => $nohp,
            'password'  => $this->func->hashPassword($pass),
            'level'     => 1,
            'pin'       => '0000',
            'tgl'       => $now,
            'max_topup' => $this->func->getSetting('max_topup'),
            'max_saldo' => $this->func->getSetting('max_saldo'),
            'upline'    => $upline,
            'status'    => 0,
        ]);
        $usrid = $this->db->insertID();

        $this->db->table('profil')->insert([
            'usrid'   => $usrid,
            'nohp'    => $nohp,
            'nama'    => $nama,
            'kelamin' => 0,
            'foto'    => 'user.png',
            'lahir'   => 0,
        ]);
        $this->db->table('saldo')->insert([
            'usrid' => $usrid,
            'apdet' => date('Y-m-d H:i:s'),
            'saldo' => 0,
        ]);

        $this->func->addlog([
            'usrid'   => $usrid,
            'ip'      => $this->request->getIPAddress(),
            'type'    => 'web',
            'ket'     => 'register',
            'created' => date('Y-m-d H:i:s'),
        ]);

        $this->func->verifEmail($usrid);
        $this->func->verifWA($usrid);

        return view('customer/main/selesai_daftar', ['email' => $email, 'nowa' => $nohp]);
    }

    public function signout()
    {
        session()->destroy();

        return redirect()->to(site_url());
    }
}
