<?php
require_once (dirname(__DIR__, 2) . '/init.php');
if (!m_admin_check()) {
    m_redirect(ADMIN_URL . '/login');
}

$db = new DB();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $languages = languages('data');
    $lang_ref_id = bin2hex(random_bytes(32));
    $lang_is_default = lang_is_default('lang_code');
    $csrf_token = csrf_token($_POST['csrf_token']);
    if ($csrf_token[0]) {
        $title = m_u_p('title');
        $slug = m_u_p('sef');
        $parent_id = m_u_p('parent_id')?? NULL;
        $category_id = m_u_p('category_id')?? NULL;
        $model = m_u_p('model');

        // create izni kontrolü (model alındıktan sonra)
        if (function_exists('can')){
            if (!can('create', $model)){
                if (function_exists('m_set_session')){
                    m_set_session('formSuccess', false);
                    m_set_session('error_message', lang('security_violation', [], 'Bu işlem için yetkiniz yok.'));
                }
                $back = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ADMIN_URL;
                header('Location: '.$back);
                exit();
            }
        }
        $status = m_u_p('status');
        $description = m_u_p('description') ?? NULL;;
        $content = m_u_p('content') ?? NULL;;
        $image = m_u_p('image') ?? NULL;;
        $icon = m_u_p('icon') ?? NULL;;
        $images = m_u_p('images') ?? NULL;;
        $seo_title = m_u_p('seo_title') ?? NULL;
        $seo_description = m_u_p('seo_description') ?? NULL;
        $seo_keywords = m_u_p('seo_keywords') ?? NULL;
        $action = m_u_p('save');
        $featuresData= trim(strip_tags($_POST['featuresData']));


        if($model == 'sliders' OR $model == 'testimonials' OR $model == 'feedback'){
            if (empty($title)) {
                m_set_session('formSuccess', false);
                m_set_session('error_message', form_vali_title);
                m_redirect($_SERVER["HTTP_REFERER"]);
                exit; // veya die;
            }
        }else{
            if (empty($title) && empty($slug)) {
                m_set_session('formSuccess', false);
                m_set_session('error_message', form_title_and_sef);
                m_redirect($_SERVER["HTTP_REFERER"]);
                exit; // veya die;
            } elseif (empty($title)) {
                m_set_session('formSuccess', false);
                m_set_session('error_message', form_vali_title);
                m_redirect($_SERVER["HTTP_REFERER"]);
                exit; // veya die;
            } elseif (empty($slug)) {
                m_set_session('formSuccess', false);
                m_set_session('error_message', form_vali_sef);
                m_redirect($_SERVER["HTTP_REFERER"]);
                exit; // veya die;
            }
            $result  = $db->table('posts')->where('sef', '=', $slug)->get();
            if ($result['total_count'] != 0) {
                $slug = $slug.'-'.rand(1,10);
            }
        }



        foreach ($languages as $language){
            if ($parent_id !== 0 or $category_id !== 0) {
                $parent = post_with_id($parent_id);
                foreach ($parent as $par){
                    if ($par['lang'] == $language['lang_code']) {
                        $parent_id = $par['id'];
                        $category_id = $par['id'];
                    }
                }
            }
            if ($category_id !== 0) {
                $categories = post_with_id($category_id);
                foreach ($categories as $category){
                    if ($category['lang'] == $language['lang_code']) {
                        $category_id = $category['id'];
                    }
                }
            }
            if ($lang_is_default != $language['lang_code']){
                $slug =  m_u_p('sef');
                if ($slug != ''){
                    $slug = $slug.'-'.$language['lang_code'];
                }
            }
            $data=[
                'lang'=> $language['lang_code'],
                'parent_id'=> $parent_id,
                'category_id'=> $category_id,
                'lang_ref_id'=>$lang_ref_id,
                'module_type'=> $model,
                'title'=>$title,
                'description'=> $description,
                'content'=> $content,
                'image'=> $image,
                'icon'=> $icon,
                'images'=> $images,
                'sef'=>$slug,
                'seo_title'=> $seo_title,
                'seo_description'=> $seo_description,
                'seo_keywords'=> $seo_keywords,
                'features'=> $featuresData,
                'status'=> $status,
                'sort'=>'0',
                'created_at'=> $db->now(),
                'updated_at'=> $db->now()
            ];
        $query = $db->table('posts')->insert($data);
        }
        if ($query) {
            pingSearchEngines();
            // IndexNow: yeni içerik URL'sini bildir
            $urlList = [];
            $defaultLang = $lang_is_default;
            foreach ($languages as $language){
                $slugForLang = $title ? ($slug . ($defaultLang != $language['lang_code'] && $slug !== '' ? '-' . $language['lang_code'] : '')) : '';
                $finalSlug = $slugForLang ?: '';
                $urlList[] = rtrim(DOMAIN,'/') . '/' . ltrim($finalSlug,'/');
            }
            indexnow_submit($urlList, $lang_is_default);
            generate_sitemap();
            $_SESSION['formSuccess'] = true;
            $_SESSION['success_message'] = lang('form_success_message', [], 'Değişiklikler Başarıyla Uygulandı!');
            m_delete_session('title');
            m_delete_session('sef');
            if ($action != '') {
                m_redirect(ADMIN_URL . '/' . $model . '/lists');
            }else{
                $last_id = $db->table('posts')->where('lang', '=', $lang_is_default)->where('lang_ref_id', '=', $lang_ref_id)->get();
                m_redirect(ADMIN_URL . '/' . $model . '/edit/'.$last_id['data'][0]['id']);
            }
        } else {
            $_SESSION['formSuccess'] = false;
            $_SESSION['error_message'] = lang('form_error_message', [], 'Değişiklikler Kaydedilirken Bir Sorun Yaşandı!');
            m_redirect($_SERVER["HTTP_REFERER"]);
            exit;
        }

    } else {
        m_set_session('formSuccess', false);
        m_set_session('error_message', lang('form_token_error', [], 'Token eşleşmiyor, lütfen sayfayı yenileyip tekrar deneyin'));
        m_set_session('title', $_POST['title']);
        m_set_session('sef', $_POST['sef']);
        m_redirect($_SERVER["HTTP_REFERER"]);

    }
}else{
    m_redirect(ADMIN_URL);

}
