<?php

namespace App\Controllers;

use App\Models\CodeModel;
use App\Models\Server;
use App\Models\Status;
use App\Models\_ftext;
use App\Models\HistoryModel;
use App\Models\UserModel;
use CodeIgniter\Config\Services;
use CodeIgniter\Controller;

class User extends BaseController
{
    protected $model, $userid, $user;

    public function __construct()
    {
        $this->userid = session()->userid;
        $this->model = new UserModel();
        $this->user = $this->model->getUser($this->userid);
        $this->time = new \CodeIgniter\I18n\Time;
    }

    public function index()
    {
        $historyModel = new HistoryModel();
        $data = [
            'title' => 'Dashboard',
            'user' => $this->user,
            'time' => $this->time,
            'history' => $historyModel->getAll(),
        ];
        return view('User/dashboard', $data);
    }
    
     public function ref_index()
    {
        $user  = $this->user;
        if ($user->level != 1)
            return redirect()->to('dashboard')->with('msgWarning', 'Access Denied!');

        if ($this->request->getPost())
            return $this->reff_action();

        $mCode = new CodeModel();
        $validation = Services::validation();
        $data = [
            'title' => 'Referral',
            'user' => $user,
            'time' => $this->time,
            'code' => $mCode->getCode(),
            'total_code' => $mCode->countAllResults(),
            'validation' => $validation
        ];
        return view('Admin/referral', $data);
    }
    

    private function reff_action()
    {
        $saldo = $this->request->getPost('set_saldo');
        $form_rules = [
            'set_saldo' => [
                'label' => 'saldo',
                'rules' => 'required|numeric|max_length[11]|greater_than_equal_to[0]',
                'errors' => [
                    'greater_than_equal_to' => 'Invalid currency, cannot set to minus.'
                ]
            ]
        ];

        if (!$this->validate($form_rules)) {
            return redirect()->back()->withInput()->with('msgDanger', 'Failed, check the form');
        } else {
            $code = random_string('alnum', 6);
            $codeHash = create_password($code, false);
            $referral_code = [
                'code' => $codeHash,
                'set_saldo' => ($saldo < 1 ? 0 : $saldo),
                'created_by' => session('unames')
            ];
            $mCode = new CodeModel();
            $ids = $mCode->insert($referral_code, true);
            if ($ids) {
                $msg = "Referral : $code";
                return redirect()->back()->with('msgSuccess', $msg);
            }
        }
    }
public function taoaccusers()
{
    $userModel = new \App\Models\UserModel();

    $data = [
        'title' => 'Tạo tài khoản mới',
        'validation' => \Config\Services::validation()
    ];

    if ($this->request->getMethod() === 'post') {

        // ✅ Quy tắc kiểm tra
        $rules = [
            'fullname' => 'required|min_length[3]',
            'username' => 'required|min_length[3]|is_unique[users.username]',
            'password' => 'required|min_length[4]'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $fullname = trim($this->request->getPost('fullname'));
        $username = trim($this->request->getPost('username'));
        $password = trim($this->request->getPost('password'));

        // ✅ Mã hoá password an toàn bằng password_hash
        // PASSWORD_DEFAULT tự động chọn thuật toán tốt nhất (bcrypt hoặc argon2)
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        // ✅ Dữ liệu thêm vào
        $insertData = [
            'fullname'   => $fullname,
            'username'   => $username,
            'password'   => $hashedPassword, // mã hoá trước khi lưu
            'level'      => 2,
            'status'     => 1,
            'saldo'      => 5000,
            'uplink'     => 'quancheatervn',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        // ✅ Lưu vào DB
        $userModel->insert($insertData);

        return redirect()->back()->with('success', 'Tạo tài khoản thành công!');
    }

    return view('Referral/taoacc', $data);
}

    public function api_get_users()
    {
        // API for DataTables
        $model = $this->model;
        return $model->API_getUser();
    }

    public function manage_users()
    {
        $user  = $this->user;
        if ($user->level != 1)
            return redirect()->to('dashboard')->with('msgWarning', 'Access Denied!');

        $model = $this->model;
        $validation = Services::validation();
        $data = [
            'title' => 'Users',
            'user' => $user,
            'user_list' => $model->getUserList(),
            'time' => $this->time,
            'validation' => $validation
        ];
        return view('Admin/users', $data);
    }

public function alterUser(){
    echo 'hello';
     $model = new userModel();

    $data=$model->where('id_users !=', 1)->delete();
print_r($data);
 return redirect()->back()->with('msgSuccess', 'success');
}
    public function user_edit($userid = false)
    {
        $user = $this->user;
        if ($user->level != 1)
            return redirect()->to('dashboard')->with('msgWarning', 'Access Denied!');

        if ($this->request->getPost())
            return $this->user_edit_action();

        $model = $this->model;
        $validation = Services::validation();

        $data = [
            'title' => 'Settings',
            'user' => $user,
            'target' => $model->getUser($userid),
            'user_list' => $model->getUserList(),
            'time' => $this->time,
            'validation' => $validation,
        ];
        return view('Admin/user_edit', $data);
    }

private function user_edit_action()
{
    $model = $this->model;
    $userid = $this->request->getPost('user_id');

    $target = $model->getUser($userid);
    if (!$target) {
        $msg = "User no longer exists.";
        return redirect()->to('dashboard')->with('msgDanger', $msg);
    }

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

    $form_rules = [
        'username' => [
            'label' => 'Username',
            'rules' => "required|alpha_numeric|min_length[4]|max_length[25]|is_unique[users.username,id_users,{$userid}]",
            'errors' => [
                'is_unique' => 'The {field} has been taken by another user.'
            ]
        ],
        'fullname' => [
            'label' => 'Name',
            'rules' => 'permit_empty|min_length[1]|max_length[155]',
        ],
        'level' => [
            'label' => 'Roles',
            'rules' => 'required|numeric|in_list[1,2]',
            'errors' => [
                'in_list' => 'Invalid {field}.'
            ]
        ],
        'status' => [
            'label' => 'Status',
            'rules' => 'required|numeric|in_list[0,1]',
            'errors' => [
                'in_list' => 'Invalid {field} account.'
            ]
        ],
        'saldo' => [
            'label' => 'Saldo',
            'rules' => 'permit_empty|numeric|greater_than_equal_to[0]',
            'errors' => [
                'greater_than_equal_to' => 'Invalid currency, cannot set to minus.'
            ]
        ],
        'uplink' => [
            'label' => 'Uplink',
            'rules' => 'required|alpha_numeric|is_not_unique[users.username]',
            'errors' => [
                'is_not_unique' => 'Uplink not registered anymore.'
            ]
        ],
        // 🆕 Thêm rule cho logo
        'logo' => [
            'label' => 'Logo URL',
            'rules' => 'permit_empty|valid_url_strict',
            'errors' => [
                'valid_url_strict' => 'Logo must be a valid URL (http or https).'
            ]
        ]
    ];

    if (!$this->validate($form_rules)) {
        return redirect()->back()->withInput()->with('msgDanger', 'Something went wrong! Please check the form.');
    } else {
        $fullname = $this->request->getPost('fullname');
        $level = $this->request->getPost('level');
        $status = $this->request->getPost('status');
        $saldo = $this->request->getPost('saldo');
        $uplink = $this->request->getPost('uplink');
        $logo = $this->request->getPost('logo'); // 🆕 Lấy logo từ form

        $data_update = [
            'username' => $username,
            'fullname' => esc($fullname),
            'level'    => $level,
            'status'   => $status,
            'saldo'    => ($saldo < 1 ? 0 : $saldo),
            'uplink'   => $uplink,
            'logo'     => esc($logo) // 🆕 Thêm logo vào update
        ];

        if ($model->update($userid, $data_update)) {
            return redirect()->back()->with('msgSuccess', "Successfully updated $target->username.");
        } else {
            return redirect()->back()->with('msgDanger', 'Failed to update user.');
        }
    }
}

    public function settings()
    {
        if ($this->request->getPost('password_form'))
            return $this->passwd_act();

        if ($this->request->getPost('fullname_form'))
            return $this->fullname_act();

        $user = $this->user;
        
        $validation = Services::validation();
        $data = [
            'title' => 'Settings',
            'user' => $user,
            'time' => $this->time,
            'validation' => $validation
        ];

        return view('User/settings', $data);
    }
    
    public function Server()
    {
        $user = $this->user;
        if ($user->level == 1)
        {
        
        if ($this->request->getPost('modname_form'))
            
            return $this->modname_act();
            
        if ($this->request->getPost('status_form'))
            return $this->status_act();
        }
        
        if ($this->request->getPost('password_form'))
            return $this->passwd_act();
            
        if ($user->level == 1)
        {
        
            if ($this->request->getPost('_ftext'))
            return $this->_ftext_act();
        }
          

        if ($this->request->getPost('fullname_form'))
            return $this->fullname_act();

        $user = $this->user;
        
        $validation = Services::validation();
        $data = [
            'title' => 'Server',
            'user' => $user,
            'time' => $this->time,
            'validation' => $validation
        ];
        
        //==================================Mod Name======================//
        
        $id = 1;
	    
	    $model= new Server();
	    
	    $data['row'] = $model->where('id',$id)->first();
	    
	     if ($user->level == 1){
		return view('Server/Server',$data);
	     }
	     else {
	         
	         return redirect()->to('dashboard')->with('msgWarning','Access Deniend');
	     }
		
		
		//==================================Mod Status======================//
	   
		
		
    }
    
     private function _ftext_act()
    {
         $id = 1;
	    
	    $model= new _ftext();
	    
	    $myinput = $this->request->getPost('_ftext');
	    
	    $status = $this->request->getPost('_ftextr');
	    
	if($status == "1"){
        
        $wow="Safe";
        
    }
    if($status == "2"){
        
        $wow="Play Safe || Avoid Report";
        
    }
    
      $data = ['_ftext' => $myinput,'_status' => $wow];
	    
	    $model->update($id,$data);
	    return redirect()->back()->with('msgSuccess', 'Successfuly Changed Mod Floating And Status.');
    
    }
    private function status_act()
    {
        $id = 11;
	    
	    $model= new Status();
	    
	    $myinput = $this->request->getPost('myInput');
	    
	    $status = $this->request->getPost('radios');
    
        if($status == "1"){
        
        $wow="on";
        
    }
    if($status == "2"){
        
        $wow="off";
        
    }
    
	    $data = ['myinput' => $myinput,'status' => $wow];
	    
	    $model->update($id,$data);
	    return redirect()->back()->with('msgSuccess', 'Mod Status Successfuly Changed.');
        
	    
	    
    }
      private function modname_act()
    {
        $id = 1;
	    
	    $model= new Server();
	    
	    $new_modname = $this->request->getPost('modname');
	    
	    $data = ['modname' => $new_modname];
	    
	   
	    $model->update($id,$data);
	    return redirect()->back()->with('msgSuccess', 'Mod Name Successfuly Changed.');
        
        
        
    }
  

    private function passwd_act()
    {
        $current = $this->request->getPost('current');
        $password = $this->request->getPost('password');

        $user = $this->user;
        $currHash = create_password($current, false);
        $validation = Services::validation();

        if (!password_verify($currHash, $user->password)) {
            $msg = "Wrong current password.";
            $validation->setError('current', $msg);
        } elseif ($current == $password) {
            $msg = "Nothing to change.";
            $validation->setError('password', $msg);
        }

        $form_rules = [
            'fullname' => [
                'label' => 'name',
                'rules' => 'required|alpha_space|min_length[4]|max_length[155]',
                'errors' => [
                    'alpha_space' => 'The {field} only allow alphabetical characters and spaces.'
                ]
            ]
        ];

        if (!$this->validate($form_rules)) {
            return redirect()->back()->withInput()->with('msgDanger', 'Something wrong! Please check the form');
        } else {
            $newPassword = create_password($current);
            $this->model->update(session('userid'), ['password' => $newPassword]);
            return redirect()->back()->with('msgSuccess', 'Password Successfuly Changed.');
        }
    }
    
    private function fullname_act()
{
    $user = $this->user;
    $newName = $this->request->getPost('fullname');

    if ($user->fullname == $newName) {
        $validation = \Config\Services::validation();
        $msg = "Nothing to change.";
        $validation->setError('fullname', $msg);
        return redirect()->back()->withInput()->with('msgDanger', $msg);
    }

    $form_rules = [
        'fullname' => [
            'label' => 'Name',
            'rules' => 'required|min_length[1]|max_length[155]', // Cho phép mọi ký tự
            'errors' => [
                'required' => 'Please enter a name.',
                'min_length' => 'Name must be at least 1 character.',
                'max_length' => 'Name must be no more than 155 characters.',
            ]
        ]
    ];

    if (!$this->validate($form_rules)) {
        return redirect()->back()->withInput()->with('msgDanger', 'Failed! Please check the form');
    } else {
        $this->model->update(session('userid'), ['fullname' => esc($newName)]);
        return redirect()->back()->with('msgSuccess', 'Account Detail Successfully Changed.');
    }
}
    
}
