<?php
namespace App\Controllers;

// Users Management
class User extends BaseController
{
    protected $db;
    
    public function __construct()
    {
        // Koneksi database dan validation service
        $this->db = \Config\Database::connect();
    }

    public function index()
    {
        // $db = \Config\Database::connect();
        $sql = "select u.USERID, u.USERLEVEL from GDC_CMOD.dbo.USERS u
            left join glendb.dbo.USERS u1 on u1.USERID=u.USERID
            where u1.LOCKEDACCOUNT is null";
		$query = $this->db->query($sql);
		$results = $query->getResultArray();
		$data['data'] = $results;

        return view('user', $data);
    }

    public function create()
    {
        // ambil input
        $userid     = (string) strtoupper(trim($this->request->getPost('userid')));
        $userlevel  = (string) trim($this->request->getPost('userlevel'));
        $password   = (string) trim($this->request->getPost('password'));
        $password_2 = (string) trim($this->request->getPost('password_2'));

        // Cek Password Apakah Sama
        if ($password != $password_2) {
            return redirect()->back()->withInput()->with('errors', ['password' => '*Password tidak sama'])->with('showModal', 'addUserModal');
        }
        if ( strlen($password) < 3 ) {
            return redirect()->back()->withInput()->with('errors', ['password' => '*Password harus diatas 2 karakter'])->with('showModal', 'addUserModal');
        }

        // Cek Apakah USERID Sama
        $sql = $this->db->query("SELECT USERID FROM gdc_cmod.dbo.USERS WHERE USERID = ?", [$userid]);
        $query = $sql->getRowArray();
        if ($query != null) {
            return redirect()->back()->withInput()->with('errors', ['userid' => ' *Userid Sudah Dipakai'])->with('showModal', 'addUserModal');
        }

        // Hash Password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        // Insert
        $this->db->transBegin();
        try {
            $sqlInsert = "
                INSERT INTO gdc_cmod.dbo.USERS (USERID, USERLEVEL, PASSWORD)
                VALUES (?, ?, ?)
            ";
            $this->db->query($sqlInsert, [$userid, $userlevel, $hashedPassword]);

            $this->db->transCommit();

        } catch (\Throwable $e) {
            // Kalau ada error, rollback semua perubahan
            $this->db->transRollback();

            // (Opsional) tampilkan atau log error
            // return redirect()->back()->with('errors', ['server_error' => '*Error: '.$e->getMessage()])->with('showModal', 'addUserModal');
            return redirect()->back()->with('errors', ['server_error' => 'Terjadi kesalahan pada server.']);
        }

        return redirect()->back()->with('success', 'User '.$userid.' Berhasil ditambahkan!');
    }

    public function update()
    {
        // Ambil Input
        $userid     = (string) strtoupper(trim($this->request->getPost('userid')));
        $userlevel  = (string) trim($this->request->getPost('userlevel'));
        $password   = (string) trim($this->request->getPost('password'));
        $password_2 = (string) trim($this->request->getPost('password_2'));
        
        // Jika password tidak kosong - Lakukan Full Update
        if ( $password != '' || $password_2 != '')  {
            
            // Cek Password Apakah Sama
            if ($password != $password_2) {
                return redirect()->back()->withInput()->with('errors', ['password' => '*Password tidak sama'])->with('showModal', 'editUserModal'.$userid);
            }

            // Hash Password
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $sqlUpdate ="
                UPDATE gdc_cmod.dbo.USERS 
                SET USERLEVEL = ?,
                    PASSWORD = ?
                WHERE USERID = ?
            ";
            $fullUpdate = true;

        // Jika password kosong - Lakukan Partial Update Saja
        } else {
            $sqlUpdate ="
                UPDATE gdc_cmod.dbo.USERS 
                SET USERLEVEL = ?
                WHERE USERID = ?
            ";
            $fullUpdate = false;
        }

        // Insert
        $this->db->transBegin();
        try {

            if ($fullUpdate) {
                $this->db->query($sqlUpdate, [$userlevel, $hashedPassword, $userid]);
            } else {
                $this->db->query($sqlUpdate, [$userlevel, $userid]);
            }
            
            $this->db->transCommit();

        } catch (\Throwable $e) {
            // Kalau ada error, rollback semua perubahan
            $this->db->transRollback();

            // (Opsional) tampilkan atau log error
            return redirect()->back()->with('errors', ['server_error' => 'Terjadi kesalahan pada server.']);
        }

        return redirect()->back()->with('success', 'User '.$userid.' Berhasil Diupdate!');
    }

    public function delete()
    {
        $userid = (string) strtoupper(trim($this->request->getPost('userid')));

        $this->db->transBegin();
        try {
            $sqlDelete = "DELETE FROM gdc_cmod.dbo.USERS WHERE USERID = ?";
            $this->db->query($sqlDelete, [$userid]);
            $this->db->transCommit();

            return redirect()->back()->with('success', "User {$userid} berhasil dihapus!");

        } catch (\Throwable $e) {
            $this->db->transRollback();
            log_message('error', 'Delete user error: ' . $e->getMessage());
            return redirect()->back()->with('errors', ['server_error' => 'Terjadi kesalahan pada server.']);
        }

    }

}
