<?php
/**
 * Admin panel kontrolcüsü.
 */

function render_admin(string $view, array $vars = []): void
{
    extract($vars);
    $adminUser = $_SESSION['admin_name'] ?? ($_SESSION['admin_username'] ?? 'Yönetici');
    $activeMenu = $vars['activeMenu'] ?? '';
    ob_start();
    require APP_ROOT . '/app/views/admin/' . $view . '.php';
    $content = ob_get_clean();
    require APP_ROOT . '/app/views/admin/layout.php';
}

function admin_home(): void
{
    redirect(is_admin() ? 'admin/dashboard' : 'admin/login');
}

function admin_login_form(): void
{
    if (is_admin()) { redirect('admin/dashboard'); }
    $error = $_SESSION['login_error'] ?? '';
    unset($_SESSION['login_error']);
    require APP_ROOT . '/app/views/admin/login.php';
}

function admin_login(): void
{
    csrf_check();

    // Kaba-kuvvet yavaşlatma: art arda başarısız denemelerde geçici kilit
    $now = time();
    $lock = $_SESSION['login_lock'] ?? ['count' => 0, 'until' => 0];
    if ($lock['until'] > $now) {
        $_SESSION['login_error'] = 'Çok fazla hatalı deneme. Lütfen ' . ($lock['until'] - $now) . ' saniye sonra tekrar deneyin.';
        redirect('admin/login');
    }

    $username = trim($_POST['username'] ?? '');
    $password = (string) ($_POST['password'] ?? '');
    $admin = Database::one("SELECT * FROM admins WHERE username=?", [$username]);
    if ($admin && password_verify($password, $admin['password_hash'])) {
        unset($_SESSION['login_lock']);
        session_regenerate_id(true);
        $_SESSION['admin_id'] = (int) $admin['id'];
        $_SESSION['admin_username'] = $admin['username'];
        $_SESSION['admin_name'] = $admin['name'] ?: $admin['username'];
        redirect('admin/dashboard');
    }

    // Başarısız: sayacı artır, zamanlamayı sabitle (kullanıcı adı sızıntısını önler)
    usleep(400000);
    $lock['count'] = ($lock['count'] ?? 0) + 1;
    if ($lock['count'] >= 5) {
        $lock['until'] = $now + 60; // 5 hatadan sonra 60 sn kilit
        $lock['count'] = 0;
    }
    $_SESSION['login_lock'] = $lock;
    $_SESSION['login_error'] = 'Kullanıcı adı veya şifre hatalı.';
    redirect('admin/login');
}

function admin_logout(): void
{
    $_SESSION = [];
    session_destroy();
    redirect('admin/login');
}

function admin_dashboard(): void
{
    require_admin();
    $stats = [
        'categories' => (int) Database::value("SELECT COUNT(*) FROM categories"),
        'products'   => (int) Database::value("SELECT COUNT(*) FROM products"),
        'events'     => (int) Database::value("SELECT COUNT(*) FROM events"),
        'featured'   => (int) Database::value("SELECT COUNT(*) FROM products WHERE is_featured=1"),
    ];
    $recent = Database::all(
        "SELECT p.*, c.name AS category_name FROM products p
         LEFT JOIN categories c ON c.id=p.category_id ORDER BY p.id DESC LIMIT 6"
    );
    render_admin('dashboard', ['title'=>'Panel','activeMenu'=>'dashboard','stats'=>$stats,'recent'=>$recent]);
}

/* ------------------- KATEGORİLER ------------------- */

function admin_categories(): void
{
    require_admin();
    $categories = Database::all(
        "SELECT c.*, (SELECT COUNT(*) FROM products p WHERE p.category_id=c.id) AS pc
         FROM categories c ORDER BY c.sort_order, c.name"
    );
    render_admin('categories', ['title'=>'Kategoriler','activeMenu'=>'categories','categories'=>$categories]);
}

function admin_category_form(array $p): void
{
    require_admin();
    $cat = null;
    if (!empty($p['id'])) {
        $cat = Database::one("SELECT * FROM categories WHERE id=?", [(int)$p['id']]);
    }
    render_admin('category_form', ['title'=>$cat?'Kategori Düzenle':'Kategori Ekle','activeMenu'=>'categories','cat'=>$cat]);
}

function admin_category_save(): void
{
    require_admin();
    csrf_check();
    $id = (int) ($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    if ($name === '') { flash('Kategori adı zorunlu.','error'); redirect('admin/kategoriler'); }
    $slug = trim($_POST['slug'] ?? '') ?: slugify($name);
    $slug = ensure_unique_slug('categories', $slug, $id);

    try {
        $image = handle_upload('image', ['jpg','jpeg','png','webp','gif','svg']);
        $video = handle_upload('video', ['mp4','webm','mov']);
    } catch (Throwable $e) { flash($e->getMessage(),'error'); redirect('admin/kategoriler'); }

    $data = [
        'name'=>$name,'slug'=>$slug,
        'description'=>trim($_POST['description'] ?? ''),
        'icon'=>trim($_POST['icon'] ?? ''),
        'sort_order'=>(int)($_POST['sort_order'] ?? 0),
        'is_active'=>isset($_POST['is_active'])?1:0,
    ];
    if ($id) {
        $old = Database::one("SELECT image, video FROM categories WHERE id=?", [$id]);
        if ($image) {
            delete_media_file($old['image'] ?? null);
            $data['image'] = $image;
        } elseif (isset($_POST['remove_image'])) {
            delete_media_file($old['image'] ?? null);
            $data['image'] = '';
        }
        if ($video) {
            delete_media_file($old['video'] ?? null);
            $data['video'] = $video;
        } elseif (isset($_POST['remove_video'])) {
            delete_media_file($old['video'] ?? null);
            $data['video'] = '';
        }
        $set = implode(', ', array_map(fn($k)=>"`$k`=:$k", array_keys($data)));
        $data['id']=$id;
        Database::query("UPDATE categories SET $set WHERE id=:id", $data);
        flash('Kategori güncellendi.');
    } else {
        $data['image']=$image;
        $data['video']=$video;
        $cols = implode(',', array_map(fn($k)=>"`$k`", array_keys($data)));
        $ph = implode(',', array_map(fn($k)=>":$k", array_keys($data)));
        Database::query("INSERT INTO categories ($cols) VALUES ($ph)", $data);
        flash('Kategori eklendi.');
    }
    redirect('admin/kategoriler');
}

function admin_category_delete(array $p): void
{
    require_admin();
    verify_delete_token();
    $old = Database::one("SELECT image, video FROM categories WHERE id=?", [(int)$p['id']]);
    if ($old) {
        delete_media_file($old['image'] ?? null);
        delete_media_file($old['video'] ?? null);
    }
    Database::query("DELETE FROM categories WHERE id=?", [(int)$p['id']]);
    flash('Kategori silindi.');
    redirect('admin/kategoriler');
}

/* ------------------- ÜRÜNLER ------------------- */

function admin_products(): void
{
    require_admin();
    $catFilter = isset($_GET['cat']) ? (int)$_GET['cat'] : 0;
    $where = $catFilter ? "WHERE p.category_id=".$catFilter : "";
    $products = Database::all(
        "SELECT p.*, c.name AS category_name FROM products p
         LEFT JOIN categories c ON c.id=p.category_id $where ORDER BY p.sort_order, p.id DESC"
    );
    $categories = Database::all("SELECT * FROM categories ORDER BY sort_order, name");
    render_admin('products', ['title'=>'Ürünler','activeMenu'=>'products','products'=>$products,'categories'=>$categories,'catFilter'=>$catFilter]);
}

function admin_product_form(array $p): void
{
    require_admin();
    $product = null;
    if (!empty($p['id'])) {
        $product = Database::one("SELECT * FROM products WHERE id=?", [(int)$p['id']]);
    }
    $categories = Database::all("SELECT * FROM categories ORDER BY sort_order, name");
    render_admin('product_form', ['title'=>$product?'Ürün Düzenle':'Ürün Ekle','activeMenu'=>'products','product'=>$product,'categories'=>$categories]);
}

function admin_product_save(): void
{
    require_admin();
    csrf_check();
    $id = (int) ($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    if ($name === '') { flash('Ürün adı zorunlu.','error'); redirect('admin/urunler'); }
    $slug = trim($_POST['slug'] ?? '') ?: slugify($name);
    $slug = ensure_unique_slug('products', $slug, $id);

    try {
        $image = handle_upload('image', ['jpg','jpeg','png','webp','gif']);
        $video = handle_upload('video', ['mp4','webm','mov']);
    } catch (Throwable $e) { flash($e->getMessage(),'error'); redirect($id?'admin/urun/duzenle/'.$id:'admin/urun/ekle'); }

    $numeric = fn($k) => ($_POST[$k] ?? '') === '' ? null : (float)str_replace(',','.',$_POST[$k]);

    $data = [
        'category_id'=>($_POST['category_id']??'')?:null,
        'name'=>$name,'slug'=>$slug,
        'description'=>trim($_POST['description'] ?? ''),
        'price'=>(float)str_replace(',','.',$_POST['price'] ?? '0'),
        'calories'=>($_POST['calories']??'')===''?null:(int)$_POST['calories'],
        'protein'=>$numeric('protein'),
        'carbs'=>$numeric('carbs'),
        'fat'=>$numeric('fat'),
        'sugar'=>$numeric('sugar'),
        'caffeine'=>($_POST['caffeine']??'')===''?null:(int)$_POST['caffeine'],
        'allergens'=>trim($_POST['allergens'] ?? ''),
        'notes'=>trim($_POST['notes'] ?? ''),
        'is_featured'=>isset($_POST['is_featured'])?1:0,
        'is_active'=>isset($_POST['is_active'])?1:0,
        'sort_order'=>(int)($_POST['sort_order'] ?? 0),
    ];
    if ($id) {
        $old = Database::one("SELECT image, video FROM products WHERE id=?", [$id]);
        if ($image) {
            delete_media_file($old['image'] ?? null);
            $data['image'] = $image;
        } elseif (isset($_POST['remove_image'])) {
            delete_media_file($old['image'] ?? null);
            $data['image'] = '';
        }
        if ($video) {
            delete_media_file($old['video'] ?? null);
            $data['video'] = $video;
        } elseif (isset($_POST['remove_video'])) {
            delete_media_file($old['video'] ?? null);
            $data['video'] = '';
        }
        $set = implode(', ', array_map(fn($k)=>"`$k`=:$k", array_keys($data)));
        $data['id']=$id;
        Database::query("UPDATE products SET $set WHERE id=:id", $data);
        flash('Ürün güncellendi.');
    } else {
        $data['image']=$image; $data['video']=$video;
        $cols = implode(',', array_map(fn($k)=>"`$k`", array_keys($data)));
        $ph = implode(',', array_map(fn($k)=>":$k", array_keys($data)));
        Database::query("INSERT INTO products ($cols) VALUES ($ph)", $data);
        flash('Ürün eklendi.');
    }
    redirect('admin/urunler');
}

function admin_product_delete(array $p): void
{
    require_admin();
    verify_delete_token();
    $old = Database::one("SELECT image, video FROM products WHERE id=?", [(int)$p['id']]);
    if ($old) {
        delete_media_file($old['image'] ?? null);
        delete_media_file($old['video'] ?? null);
    }
    Database::query("DELETE FROM products WHERE id=?", [(int)$p['id']]);
    flash('Ürün silindi.');
    redirect('admin/urunler');
}

/* ------------------- ETKİNLİKLER ------------------- */

function admin_events(): void
{
    require_admin();
    $events = Database::all("SELECT * FROM events ORDER BY sort_order, id DESC");
    render_admin('events', ['title'=>'Etkinlikler','activeMenu'=>'events','events'=>$events]);
}

function admin_event_form(array $p): void
{
    require_admin();
    $event = null;
    if (!empty($p['id'])) {
        $event = Database::one("SELECT * FROM events WHERE id=?", [(int)$p['id']]);
    }
    render_admin('event_form', ['title'=>$event?'Etkinlik Düzenle':'Etkinlik Ekle','activeMenu'=>'events','event'=>$event]);
}

function admin_event_save(): void
{
    require_admin();
    csrf_check();
    $id = (int) ($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    if ($title === '') { flash('Etkinlik başlığı zorunlu.','error'); redirect('admin/etkinlikler'); }

    try {
        $image = handle_upload('image', ['jpg','jpeg','png','webp','gif']);
        $video = handle_upload('video', ['mp4','webm','mov']);
    } catch (Throwable $e) { flash($e->getMessage(),'error'); redirect('admin/etkinlikler'); }

    $data = [
        'title'=>$title,
        'description'=>trim($_POST['description'] ?? ''),
        'date_text'=>trim($_POST['date_text'] ?? ''),
        'badge'=>trim($_POST['badge'] ?? ''),
        'price_text'=>trim($_POST['price_text'] ?? ''),
        'link_url'=>trim($_POST['link_url'] ?? ''),
        'link_text'=>trim($_POST['link_text'] ?? ''),
        'sort_order'=>(int)($_POST['sort_order'] ?? 0),
        'is_active'=>isset($_POST['is_active'])?1:0,
    ];
    if ($id) {
        $old = Database::one("SELECT image, video FROM events WHERE id=?", [$id]);
        if ($image) {
            delete_media_file($old['image'] ?? null);
            $data['image'] = $image;
        } elseif (isset($_POST['remove_image'])) {
            delete_media_file($old['image'] ?? null);
            $data['image'] = '';
        }
        if ($video) {
            delete_media_file($old['video'] ?? null);
            $data['video'] = $video;
        } elseif (isset($_POST['remove_video'])) {
            delete_media_file($old['video'] ?? null);
            $data['video'] = '';
        }
        $set = implode(', ', array_map(fn($k)=>"`$k`=:$k", array_keys($data)));
        $data['id']=$id;
        Database::query("UPDATE events SET $set WHERE id=:id", $data);
        flash('Etkinlik güncellendi.');
    } else {
        $data['image']=$image; $data['video']=$video;
        $cols = implode(',', array_map(fn($k)=>"`$k`", array_keys($data)));
        $ph = implode(',', array_map(fn($k)=>":$k", array_keys($data)));
        Database::query("INSERT INTO events ($cols) VALUES ($ph)", $data);
        flash('Etkinlik eklendi.');
    }
    redirect('admin/etkinlikler');
}

function admin_event_delete(array $p): void
{
    require_admin();
    verify_delete_token();
    $old = Database::one("SELECT image, video FROM events WHERE id=?", [(int)$p['id']]);
    if ($old) {
        delete_media_file($old['image'] ?? null);
        delete_media_file($old['video'] ?? null);
    }
    Database::query("DELETE FROM events WHERE id=?", [(int)$p['id']]);
    flash('Etkinlik silindi.');
    redirect('admin/etkinlikler');
}

/* ------------------- AYARLAR ------------------- */

function admin_settings_form(): void
{
    require_admin();
    render_admin('settings', ['title'=>'Ayarlar','activeMenu'=>'settings','s'=>settings()]);
}

function admin_settings_save(): void
{
    require_admin();
    csrf_check();
    $keys = [
        'business_name','business_slogan','welcome_title','welcome_text','hero_subtitle','hero_badge',
        'phone','email','address','whatsapp','instagram','instagram_story','facebook','map_url','currency',
        'theme_primary','theme_secondary','theme_bg','theme_surface','theme_text','theme_muted','theme_mode',
    ];
    foreach ($keys as $k) {
        if (array_key_exists($k, $_POST)) {
            set_setting($k, trim((string)$_POST[$k]));
        }
    }
    set_setting('show_nutrition', isset($_POST['show_nutrition'])?'1':'0');
    set_setting('show_events', isset($_POST['show_events'])?'1':'0');
    set_setting('show_splash', isset($_POST['show_splash'])?'1':'0');

    try {
        $logo = handle_upload('logo', ['jpg','jpeg','png','webp','svg']);
        $heroVideo = handle_upload('hero_video', ['mp4','webm']);
        $heroPoster = handle_upload('hero_poster', ['jpg','jpeg','png','webp']);
    } catch (Throwable $e) { flash($e->getMessage(),'error'); redirect('admin/ayarlar'); }

    if ($logo) {
        delete_media_file(setting('logo'));
        set_setting('logo', $logo);
    } elseif (isset($_POST['remove_logo'])) {
        delete_media_file(setting('logo'));
        set_setting('logo', '');
    }

    if ($heroVideo) {
        delete_media_file(setting('hero_video'));
        set_setting('hero_video', $heroVideo);
    } elseif (isset($_POST['remove_hero_video'])) {
        delete_media_file(setting('hero_video'));
        set_setting('hero_video', '');
    }

    if ($heroPoster) {
        delete_media_file(setting('hero_poster'));
        set_setting('hero_poster', $heroPoster);
    } elseif (isset($_POST['remove_hero_poster'])) {
        delete_media_file(setting('hero_poster'));
        set_setting('hero_poster', '');
    }

    flash('Ayarlar kaydedildi.');
    redirect('admin/ayarlar');
}

/* ------------------- YAPAY ZEKA (AJAX) ------------------- */

function admin_ai_analyze(): void
{
    require_admin();
    csrf_check();
    header('Content-Type: application/json; charset=UTF-8');
    $name = trim($_POST['name'] ?? '');
    $desc = trim($_POST['description'] ?? '');
    if ($name === '') {
        echo json_encode(['ok'=>false,'error'=>'Ürün adı gerekli.'], JSON_UNESCAPED_UNICODE);
        return;
    }
    $result = NutritionAI::analyze($name, $desc);
    echo json_encode(['ok'=>true,'data'=>$result], JSON_UNESCAPED_UNICODE);
}

/* ------------------- YARDIMCI ------------------- */

/** Silme bağlantısı için CSRF token doğrular. */
function verify_delete_token(): void
{
    $token = $_GET['t'] ?? '';
    if (!hash_equals($_SESSION['csrf'] ?? '', $token)) {
        http_response_code(419);
        exit('Geçersiz veya süresi dolmuş istek. Lütfen listeye dönüp tekrar deneyin.');
    }
}

/** Token içeren güvenli silme bağlantısı üretir. */
function del_link(string $path): string
{
    return url($path) . '?t=' . urlencode(csrf_token());
}

function ensure_unique_slug(string $table, string $slug, int $excludeId = 0): string
{
    $base = $slug; $i = 2;
    while (true) {
        $row = Database::one("SELECT id FROM {$table} WHERE slug=? AND id<>?", [$slug, $excludeId]);
        if (!$row) { return $slug; }
        $slug = $base . '-' . $i++;
    }
}
