<?php 
    $data = array();
    $data['title'] = "Kullanıcı Ekle | ".$App->title;
    $data['links'] = [];
    $data['styles'] = [];
    $data['header']['scripts'] = [];
    $data['version'] = $App->version;
    $data['csrf_token'] = $csrf_generator->create();
    $data['sidebar_menu'] = $menu->get(array('position'=>'sidebar'));
    $data['sidebar_active_menu'] = $menu->getActiveMenuItemId(trim($_SERVER['REQUEST_URI']));
    $data['footer']['scripts'] = [];
    $menu_items = $menu->get(array('position'=>'footer'));
    foreach($menu_items as $item){
        if($item['col'] == "1"){
            $data['menu']['footer']["1"][] = $item;
        }
        if($item['col'] == "2"){
            $data['menu']['footer']["2"][] = $item;
        }
        if($item['col'] == "3"){
            $data['menu']['footer']["3"][] = $item;
        }
        if($item['col'] == "4"){
            $data['menu']['footer']["4"][] = $item;
        }
    }

    $data['breadcrumbs'] = array();
    $data['breadcrumbs'][] = array(
        'text' => "Pano",
        'href' => "/admin",
        'index' => 1
    );
    $data['breadcrumbs'][] = array(
        'text' => "Kullanıcılar",
        'href' => "/admin/users/list",
        'index' => 2
    );
    $data['breadcrumbs'][] = array(
        'text' => "Kullanıcı Ekle",
        'href' => "#",
        'index' => 3
    );

    $response = array();
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        if(!isset($_POST['name']) || empty($_POST['name']) || strlen($_POST['name']) > 255) {
            $response[] = array('status'=>false, 'element'=>'name', 'message'=>'Geçersiz isim girdiniz.');
        }
        if(!isset($_POST['surname']) || empty($_POST['surname']) || strlen($_POST['surname']) > 255) {
            $response[] = array('status'=>false, 'element'=>'surname', 'message'=>'Lütfen geçerli bir soyisim girdiniz.');
        }
        if(!isset($_POST['email']) || empty($_POST['email']) || strlen($_POST['email']) > 255 || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $response[] = array('status'=>false, 'element'=>'email', 'message'=>'Hatalı e-posta adresi. Lütfen geçerli bir e-posta giriniz.');
        }else if(!checkdnsrr(substr($_POST['email'], strpos($_POST['email'], '@') + 1), 'MX')) {
            $response[] = array('status'=>false, 'element'=>'email', 'message'=>'Geçersiz e-posta adresi. Böyle bir e-posta bulunamadı.');
        }
        if(!isset($_POST['password']) || empty($_POST['password'])) {
            $response[] = array('status'=>false, 'element'=>'password', 'message'=>'Parolanız en az sekiz karakter, en az bir harf, bir sayı ve bir özel karakter (~?!@#$%^&.,*) içermelidir.');
        }
        if(!isset($_POST['user_group']) || $_POST['user_group'] == 0 || $_POST['user_group'] == '') {
            $response[] = array('status'=>false, 'element'=>'user_group', 'message'=>'Lütfen bir unvan seçiniz');
        }
        if(!isset($_POST['promotion_approval']) || strlen($_POST['promotion_approval']) > 1 || !preg_match('/^[0-1]+$/', $_POST['promotion_approval'])) {
            $promotion_approval = 0;
        }else{
            $promotion_approval = 1;
        }
        if(!isset($_POST['user_agreement']) || strlen($_POST['user_agreement']) > 1 || !preg_match('/^[0-1]+$/', $_POST['user_agreement'])) {
            $user_agreement = 0;
        }else{
            $user_agreement = 1;
        }
        if(!isset($_POST['kvkk_approval']) || strlen($_POST['kvkk_approval']) > 1 || !preg_match('/^[0-1]+$/', $_POST['kvkk_approval'])) {
            $kvkk_approval = 0;
        }else{
            $kvkk_approval = 1;
        }

        if($utils->isUserExists($_POST['email'])){
            $response[] = array('status'=>false, 'message'=>'Bu e-postaya sahip bir hesap zaten var.');
        }else{
            if(empty($response)) {
                $hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $avatar = $utils->strtolower_tr(mb_substr($_POST['name'], 0, 1, 'UTF-8'));
                $avatar .= ".jpg";
    
                $stmt = $db->query("INSERT INTO {$db->prefix}users (`status`, `user_group`, `name`, `surname`, `avatar`, `username`, `email`, `password`, `gln_number`, `company`, `promotion_approval`, `user_agreement`, `kvkk_approval`, `date_created`, `last_login`) VALUES (1,:user_group,:name,:surname,:avatar,:username,:email,:password,:gln_number,:company,:promotion_approval,:user_agreement,:kvkk_approval,NOW(),NOW())", 
                array(':user_group'=>$_POST['user_group'], ':name'=>$_POST['name'], ':surname'=>$_POST['surname'], ':avatar'=>$avatar, ':username'=>trim($_POST['email']), ':email'=>trim($_POST['email']), ':password'=>$hashed_password, ':gln_number'=>$_POST['gln_number'], ':company'=>$_POST['company'], ':promotion_approval'=>$promotion_approval, ':user_agreement'=>$user_agreement, ':kvkk_approval'=>$kvkk_approval));
                
                if($stmt->error) {
                    $utils->errorLog("error", "Cannot register user. Error: ".$stmt->error_info['message'], 0, $_SERVER['REQUEST_URI']);
                    $response[] = array('status'=>false, 'message'=>'Bir hata oluştu ve isteğiniz yerine getirilemedi. Lütfen daha sonra tekrar deneyiniz.');
                }else{
                    $user_id = $db->getLastId();
                    $session->data['messageType'] = "success"; 
                    $session->data['messageTitle'] = "Başarılı!"; 
                    $session->data['message'] = "Kullanıcı başarıyla oluşturuldu."; 
                    header("Location: /admin/users/edit?id={$user_id}");
                    exit();
                }
            }
        }
	}
    

    $user_groups 	    = $user->getUserGroups();
?>
<?php include DIR_VIEWS."parts/header.php"; ?>
        <?php if(isset($response) && !empty($response)): ?>
            <?php foreach($response as $res): ?>
                <div class="alert alert-danger alert-dismissible flash-message" role="alert">
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    <div class="alert-message">
                        <?php echo $res["message"]; ?>
                    </div>
                </div>
            <?php endforeach ?>
        <?php endif; ?>
        <main class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title"><i class="bi bi-person-check"></i> Kullanıcı Bilgileri</h5>
                            </div>
                            <div class="card-body">
                                <form action="" method="post">
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_name" class="form-label font-weight-bold">Ad</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" class="form-control" name="name" id="user_name" placeholder="adı" value="<?php echo isset($_POST["name"]) ? htmlspecialchars($_POST["name"], ENT_QUOTES, 'UTF-8') : ''; ?>" required>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_surname" class="form-label font-weight-bold">Soyad</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" class="form-control" name="surname" id="user_surname" placeholder="soyadı" value="<?php echo isset($_POST["surname"]) ? htmlspecialchars($_POST["surname"], ENT_QUOTES, 'UTF-8') : ''; ?>" required>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_email" class="form-label font-weight-bold">Eposta</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="email" class="form-control" name="email" id="user_email" placeholder="john@example.com" value="<?php echo isset($_POST["email"]) ? htmlspecialchars($_POST["email"], ENT_QUOTES, 'UTF-8') : ''; ?>" required>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_password" class="form-label font-weight-bold">Yeni Parola</label>
                                        </div>
                                        <div class="col-md-9 position-relative">
                                            <input type="password" class="form-control" name="password" id="user_password" placeholder="" value="" required>
                                            <span class="password-visibility-toggler" data-password="user_password">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-eye" viewBox="0 0 16 16">
                                                    <path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z"/>
                                                    <path d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0z"/>
                                                </svg>
                                            </span>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_phone" class="form-label font-weight-bold">Telefon</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="tel" class="form-control" name="phone" id="user_phone" placeholder="(___)___-__-__" value="<?php echo isset($_POST["phone"]) ? htmlspecialchars($_POST["phone"], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_birthdate" class="form-label font-weight-bold">Doğum Tarihi</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="date" class="form-control" name="birthdate" id="user_birthdate" value="<?php echo isset($_POST["birthdate"]) ? htmlspecialchars($_POST["birthdate"], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_group" class="form-label font-weight-bold">Kullanıcı Grubu</label>
                                        </div>
                                        <div class="col-md-9">
                                            <select name="user_group" id="user_group" class="form-control form-select" required>
                                                <?php foreach ($user_groups as $user_group): ?>
                                                    <option value="<?php echo $user_group['id']; ?>"><?php echo $user_group['title']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_status" class="form-label font-weight-bold">Üyelik Durumu</label>
                                        </div>
                                        <div class="col-md-9">
                                            <select name="status" id="user_status" class="form-control form-select" required>
                                                <option value="1">Aktif</option>
                                                <option value="0">Pasif</option>
                                                <option value="2">Aktarım</option>
                                            </select>
                                        </div>
                                    </div>
                                    <hr>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_gln_number" class="form-label font-weight-bold">GLN Numarası</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" class="form-control" name="gln_number" id="user_gln_number" value="<?php echo isset($_POST["gln_number"]) ? htmlspecialchars($_POST["gln_number"], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label for="user_company" class="form-label font-weight-bold">Kurum Adı</label>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" class="form-control" name="company" id="user_company" value="<?php echo isset($_POST["company"]) ? htmlspecialchars($_POST["company"], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        </div>
                                    </div>
                                    <hr>
                                    <div class="row mb-3">
                                        <div class="col-9 col-md-3">
                                            <label for="user_agreement" class="form-label font-weight-bold">Kullanıcı Sözleşmesi</label>
                                        </div>
                                        <div class="col-3 col-md-9">
                                            <input type="checkbox" class="form-label" id="user_agreement" checked required>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-9 col-md-3">
                                            <label for="kvkk_approval" class="form-label font-weight-bold">KVKK Onayı</label>
                                        </div>
                                        <div class="col-3 col-md-9">
                                            <input type="checkbox" class="form-label" id="kvkk_approval" checked>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-9 col-md-3">
                                            <label for="promotion_approval" class="form-label font-weight-bold">Bülten Onayı</label>
                                        </div>
                                        <div class="col-3 col-md-9">
                                            <input type="checkbox" class="form-label" id="promotion_approval" <?php echo isset($_POST["promotion_approval"]) && !empty($_POST["promotion_approval"]) ? 'checked' : ''; ?>>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-12 text-end">
                                            <input type="submit" name="update" class="btn btn-primary" value="Kaydet">
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
<?php include DIR_VIEWS."parts/footer.php"; ?>