<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Post;
use App\Models\NewsletterSubscriber;
use SawaStacks\Utils\Kropify;
use Illuminate\Support\Facades\File;
use App\Models\GeneralSetting;

class AdminController extends Controller
{
    /**
     * Zeigt das Admin-Dashboard an.
     *
     * ROUTE: /admin/dashboard
     * METHOD: GET
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
    */
    public function adminDashboard(Request $request)
    {
        $data = [
            "pageTitle" => "Dashboard",
            "tagsCount" => Post::whereNotNull('tags')->where('tags', '!=', '')->pluck('tags')->count(),
            "postsCount" => Post::count(),
            "subscribersCount" => NewsletterSubscriber::count(),
            "latestPosts" => Post::latest()->take(5)->get(),
            "postsWithoutMetaDescriptionCount" => Post::whereNull('meta_description')->orWhere('meta_description', '')->count(),
            "postsWithoutMetaKeywordsCount" => Post::whereNull('meta_keywords')->orWhere('meta_keywords', '')->count(),
            "postsWithoutTagsCount" => Post::whereNull('tags')->orWhere('tags', '')->count(),
            "postsWithoutMetaDescription" => Post::whereNull('meta_description')->orWhere('meta_description', '')->latest()->take(5)->get(),
            "postsWithoutMetaKeywords" => Post::whereNull('meta_keywords')->orWhere('meta_keywords', '')->latest()->take(5)->get(),
            "postsWithoutTags" => Post::whereNull('tags')->orWhere('tags', '')->latest()->take(5)->get(),
        ];

        return view("back.pages.dashboard", $data);
    }

    /**
     * Meldet den Benutzer ab und beendet die Session.
     *
     * ROUTE: /logout
     * METHOD: POST
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
    */
    public function logoutHandler(Request $request) {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        if(isset($request->source)) {
            return redirect()->back();
        }
        return redirect()->route("admin.login")->with("success", "Du hast dich ausgeloggt");
    }

    /**
     * Zeigt die Profilseite des eingeloggten Benutzers an.
     *
     * ROUTE: /admin/profile
     * METHOD: GET
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
    */
    public function profileView(Request $request) {
        $data = [
            "pageTitle" => "Profile"
        ];

        return view("back.pages.profile", $data);
    }

    /**
     * Aktualisiert das Profilbild des eingeloggten Benutzers.
     *
     * ROUTE: /admin/profile/picture
     * METHOD: POST
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function updateProfilePicture(Request $request) {
         $user = User::findOrFail(auth()->id());

        if (!$request->hasFile('profilePictureFile')) {
            return response()->json([
                'status'  => 0,
                'message' => 'Keine Datei hochgeladen.',
            ]);
        }

        $file = $request->file('profilePictureFile');

        // Der Zielordner relativ zum public/ Verzeichnis:
        $path = 'images/users/';

        // Dateiname erzeugen
        $filename = 'IMG_' . uniqid() . '.png';

        // Altes Bild speichern zum Löschen
        $oldPicture = $user->getAttributes()['picture'] ?? null;

        // Datei mit Kropify speichern (direkt public_path)
        $upload = Kropify::getFile($file, $filename)
            ->setPath($path)       // relativ zu public/
            ->useMove()            // Speichert physisch in public/<path>
            ->save();

        if (!$upload) {
            return response()->json([
                'status'  => 0,
                'message' => 'Fehler beim Hochladen des Profilfotos.',
            ]);
        }

        // Neues Bild wurde erfolgreich gespeichert → altes löschen
        if ($oldPicture && File::exists(public_path($path . $oldPicture))) {
            File::delete(public_path($path . $oldPicture));
        }

        // Im User speichern
        $user->update([
            'picture' => $filename,
        ]);

        return response()->json([
            'status'  => 1,
            'message' => 'Profilfoto erfolgreich hochgeladen.',
            'image'   => $path . $filename, // falls du die URL direkt brauchst
        ]);
    }

    /**
     * Zeigt die Seite für allgemeine Einstellungen an.
     *
     * ROUTE: /admin/settings/general
     * METHOD: GET
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
    */
    public function generalSettings(Request $request) {
        $data = [
            'pageTitle' => "Allgemeine Einstellungen"
        ];

        return view("back.pages.general_settings", $data);
    }

    /**
     * Aktualisiert das Website-Logo in den allgemeinen Einstellungen.
     *
     * ROUTE: /admin/settings/logo
     * METHOD: POST
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function updateLogo(Request $request) {
        $settings = GeneralSetting::take(1)->first();

        if(!is_null($settings)) {
            $path = 'images/site/';
            $old_logo = $settings->site_logo;
            $file = $request->file("site_logo");
            $filename = 'logo_'.uniqid().'.png';

            if($request->hasFile('site_logo')) {
                $upload = $file->move(public_path($path), $filename);

                if($upload) {
                    if($old_logo != null && File::exists(public_path($path.$old_logo))) {
                        File::delete(public_path($path.$old_logo));
                    }

                    $settings->update(['site_logo' => $filename]);
                    return response()->json(['status' => 1, 'image_path' => $path.$filename, 'message' => 'Logo wurde erfolgreich geändert']);
                } else {
                    return response()->json(['status' => 0, 'message' => 'Fehler beim hochladen von Logo']);
                }
            }
        } else {
            return response()->json(['status' => 0, 'message' => 'Make sure you updated general Settings form First']);
        }
    }

    /**
     * Aktualisiert das Website-Favicon in den allgemeinen Einstellungen.
     *
     * ROUTE: /admin/settings/favicon
     * METHOD: POST
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
    */
    public function updateFavicon(Request $request) {
        $settings = GeneralSetting::take(1)->first();

        if(!is_null($settings)) {
            $path = 'images/site/';
            $old_favicon = $settings->site_favicon;
            $file = $request->file("site_favicon");
            $filename = 'favicon_'.uniqid().'.png';

            if($request->hasFile('site_favicon')) {
                $upload = $file->move(public_path($path), $filename);

                if($upload) {
                    if($old_favicon != null && File::exists(public_path($path.$old_favicon))) {
                        File::delete(public_path($path.$old_favicon));
                    }

                    $settings->update(['site_favicon' => $filename]);
                    return response()->json(['status' => 1, 'image_path' => $path.$filename, 'message' => 'Favicon wurde erfolgreich geändert']);
                } else {
                    return response()->json(['status' => 0, 'message' => 'Fehler beim hochladen von Favicon']);
                }
            }
        } else {
            return response()->json(['status' => 0, 'message' => 'Make sure you updated general Settings form First']);
        }
    }

    /**
     * Zeigt die Verwaltungsseite für Kategorien an.
     *
     * ROUTE: /admin/categories
     * METHOD: GET
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
    */
    public function categoriesPage(Request $request) {
        $data = [
            "pageTitle" => "Kategorien verwalten"
        ];

        return view("back.pages.categories_page", $data);
    }
    
    /**
     * Zeigt die Verwaltungsseite für den Home-Slider an.
     *
     * ROUTE: /admin/slider
     * METHOD: GET
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
    */
    public function manageSlider(Request $request) {
        $data = [
            'pageTitle' => 'Manage Home Slider'
        ];

        return view('back.pages.slider', $data);
    }

}
