<?php

namespace App\Controllers\Admin;
use App\Controllers\BaseController;

use App\Entities\User;

class Users extends BaseController
{
    private $model;
    private $Settingsmodel;

    public function __construct()
	{
        $this->model = new \App\Models\UserModel;

        $this->myUser = service('auth')->getCurrentUser();
		$this->Settingsmodel = new \App\Models\GeneralSettingsModel;
	}

    public function index()
    {
        // $users = $this->model->orderBy('id') ->paginate(5);

        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['myUser'] = $this->myUser;
        $data['title'] = 'قائمة الأعضاء';

        // $data['users'] = $users;
        // $data['pager'] = $this->model->pager;

        $data['users'] = $this->model->findAll();
        $data['page'] = view('Admin/Users/index', $data);

        return view('Admin/layouts/default', $data);

    }

    public function show($id)
    {
        $user = $this->getUserOr404($id);

        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['myUser'] = $this->myUser;
        $data['title'] = 'العضو' . ' / ' .$user->name;

        $data['user'] = $user;
        $data['page'] = view('Admin/Users/show', $data);

        return view('Admin/layouts/default', $data);
    }

    public function new ()
    {
        $user = new User;

        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['myUser'] = $this->myUser;
        $data['title'] = 'اضافة عضو';

        $data['user'] = $user;
        $data['page'] = view('Admin/Users/new', $data);

        return view('Admin/layouts/default', $data);
    }

    public function edit($id)
    {
        $user = $this->getUserOr404($id);

        $data['settings'] = $this->Settingsmodel->where('id', 1)->first();
        $data['myUser'] = $this->myUser;
        $data['title'] = 'تعديل البيانات' . ' / ' .$user->name;

        $data['user'] = $user;
        $data['page'] = view('Admin/Users/edit', $data);

        return view('Admin/layouts/default', $data);
    }

	//--------------------------------------

	public function create()
	{
		$user = new User($this->request->getPost());

		if ($this->model->protect(false)->insert($user)) {

            $this->sendemail($user);
			return redirect()->to('dashboard/users/' . $this->model->insertID)
				->with('info', 'تم إنشاء العضو بنجاح');
		} else {
			return redirect()->back()
				->with('errors', $this->model->errors())
				->with('warning', 'هناك خطأ ما!')
				->withInput();
		}

	}

    private function sendemail($user)
    {
        $email = service('email');

        $email->setTo($user->email);

        $email->setSubject('تم إنشاء حساب لكم');

        $message = view('Admin/Users/activation_email', [
			'username' => $user->name,
            'useremail' => $user->email,
            'userpass' => $user->password,
            'is_active' => $user->is_active,
        ]);

        $email->setMessage($message);

        $email->send();
    }

    public function update($id)
    {
        $user = $this->getUserOr404($id);

        $post = $this->request->getPost();

        if (empty($post['password'])) {

            $this->model->disablePasswordValidation();

            unset($post['password']);
            unset($post['password_confirmation']);
        }

        $user->fill($post);

        if (!$user->hasChanged()) {

            return redirect()->back()
                ->with('warning', 'لا يوجد أي بيانات جديدة')
                ->withInput();
        }

        if ($this->model->protect(false)->save($user)) {

            return redirect()->to('dashboard/users/' . $id)
                ->with('info', 'تم تحديث بيانات العضو بنجاح');

        } else {

            return redirect()->back()
                ->with('errors', $this->model->errors())
                ->with('warning', 'هناك خطأ ما')
                ->withInput();

        }
    }


    public function delete($id)
    {
        $user = $this->getUserOr404($id);
        if ($this->model->delete(['id' => $id])) {
            return redirect()->to('dashboard/users')
                ->with('info', 'تم حذف العضو بنجاح');
        } else {
            return redirect()->back()
                ->with('errors', $this->model->errors())
                ->with('warning', 'هناك خطأ ما');
        }
    }



    private function getUserOr404($id)
    {
        $user = $this->model->where('id', $id)
            ->first();

        if ($user === null) {

            throw new \CodeIgniter\Exceptions\PageNotFoundException("العضو غير موجود الترميز الخاص به : $id");

        }

        return $user;
    }
}