<?php

namespace App\Controllers;

use App\Core\Http\Request;
use App\Core\Response\Response;
use App\Database\Database;
use App\Repositories\UserRepository;
use App\Services\sms;

class Auth
{

    private function createUser( $name, $email,$phone , $password ){
        $request = new Request();
        $user = new UserRepository();
        $db = new Database();
        $user_test = $user->findByPhone( $phone );
        if(isset($user_test) and !empty($user_test) and count($user_test) > 0 ){
           return false;
        }else{
            try {
                $user_id = $db->insert("users" ,[
                    "name" => $name,
                    "email" => $email,
                    "phone" => $phone,
                    "password" => hash_password($password),
                    "pic_url" => "assets/media/avatars/blank.png",
                    "ip" => $request::ip(),
                ]);
                return $user_id;
            }catch (\Exception $e){
                return false;
            }

        }
    }
    public function SignUp(){
        session_start();
        $request = new Request();
        $response = new Response();
        $sms = new Sms();
        $user = new UserRepository();
        try{
            $user_test = $user->findByPhone( $request::input("phone"));
            if (isset($user_test) and !empty($user_test) and count($user_test) > 0 ){
                $response->notAcceptable("کاربری با این شماره همراه از قبل وجود دارد");
            }else{
                $code = create_random_code();
                if($sms::sendSMS($request::input("phone"), " $code کد تایید شما :")){
                    $_SESSION["create_user"] = [
                        "name" => $request->input("name"),
                        "email" => $request->input("email"),
                        "phone" => $request->input("phone"),
                        "password" => $request->input("password"),
                        "code"=>$code
                    ];
                    $response->ok("کد تایید پیامک شد");
                }else{
                    $response->serverError("مشکل در ارسال کد تایید");
                }
            }
        }catch(\Exception $e) {
            $response->serverError($e->getMessage());
        }
        $response->respond();
    }

    public function CheckCode(){
        session_start();
        $request = new Request();
        $response = new Response();
        $userR = new UserRepository();
        try {
            $code = $request::input("code");
            if ( (int)$code === (int)$_SESSION["create_user"]["code"]) {
                $user =  $this->createUser($_SESSION["create_user"]["name"],$_SESSION["create_user"]["email"],$_SESSION["create_user"]["phone"], $_SESSION["create_user"]["password"]);
                if($user){
                    $dataUser = $userR->findById((int) $user);
                    $_SESSION["user"] = [
                        "name"      => $dataUser["name"],
                        "email"     => $dataUser["email"],
                        "phone"     => $dataUser["phone"],
                        "id"        => $dataUser["id"],
                        "pic_url"   => $dataUser["pic_url"]
                    ];
                    $response->ok($user,"created");
                }else{
                    $response->notAcceptable("کاربری با این شماره همراه از قبل وجود دارد");
                }
            }else{
                $response->notAcceptable("کد وارد شده اشتباه می باشد !");
            }
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
        $response->respond();
    }
    public function Login(){
        session_start();
        $request = new Request();
        $response = new Response();
        $user = new UserRepository();
        try {
            $dataUser = $user->findByPhone($request::input("phone"));
            if (isset($dataUser) and !empty($dataUser) and count($dataUser) > 0 ){
                if (hash_verify($request::input("password"), $dataUser["password"])) {
                   $_SESSION["user"] = [
                       "name" => $dataUser["name"],
                       "email" => $dataUser["email"],
                       "phone" => $dataUser["phone"],
                       "id" => $dataUser["id"],
                       "pic_url"=> $dataUser["pic_url"]
                   ];
                    $response->ok($dataUser,"login");
                }else{
                    $response->notAcceptable("رمز اشتباه است !");
                }
            }else{
                $response->notAcceptable("کاربری با این شماره موبایل وجود ندارد");
            }
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
        $response->respond();
    }
    public function forget_number(){
        session_start();
        $request = new Request();
        $response = new Response();
        $sms = new Sms();
        try {
            $user = new UserRepository();
            $dataUser = $user->findByPhone($request::input("phone"));
            if (isset($dataUser) and !empty($dataUser) and count($dataUser) > 0 ){
                $code = create_random_code();
                if ($sms::sendSMS($request::input("phone") , "کد فراموشی رمز شما :$code")){
                    $_SESSION["forget_user"] = [
                        "name" => $dataUser["name"],
                        "email" => $dataUser["email"],
                        "phone" => $dataUser["phone"],
                        "id"=>$dataUser["id"],
                        "code"=>$code,
                        "password" => $dataUser["password"]
                    ];
                    $response->ok(null,"forget sms sent");
                }else{
                    $response->serverError("مشکل در ارسال پیام");
                }
            }else{
                $response->notAcceptable("کاربری با این شماره موبایل وجود ندارد !");
            }
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
    }
    public function forget_code(){
        session_start();
        $request = new Request();
        $response = new Response();
        try{
            $code = $request::input("code");
            if ( (int)$code === (int)$_SESSION["forget_user"]["code"]) {
                $response->ok();
            }else{
                $response->notAcceptable("کد وار  شده صحیح نمی باشد");
            }
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
    }
    public  function new_password(){
        session_start();
        $request = new Request();
        $response = new Response();
        $user = new UserRepository();
        try{
            $password = hash_password($request::input("password"));
            $user->Update($_SESSION["forget_user"]["id"],[
                "password" => $password
            ]);
            $response->ok();
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
    }
    public function Logout()
    {
        $response = new Response();
        try {
            session_start();

            // پاک کردن تمام متغیرهای سشن
            $_SESSION = [];

            // اگر از کوکی استفاده شده، آن را هم منقضی کن
            if (ini_get("session.use_cookies")) {
                $params = session_get_cookie_params();
                setcookie(session_name(), '', time() - 42000,
                    $params["path"], $params["domain"],
                    $params["secure"], $params["httponly"]
                );
            }

            // سشن را نابود کن
            session_destroy();
            $response->ok();
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
        $response->respond();
    }
}