<?php

namespace App\Http\Controllers;

use App\Enums\FileKey;
use App\Enums\StatusEnum;
use App\Http\Controllers\Controller;
use App\Http\Services\AnalyticsService;
use App\Http\Services\TwoFactorService;
use App\Models\Platform;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Notification;
use App\Rules\FileExtentionCheckRule;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Illuminate\Validation\Rules\Password;
use App\Traits\Fileable;
use App\Traits\ModelAction;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Inertia\Inertia;

class HomeController extends Controller
{



    protected $user, $analyticsService , $twoFactorService;

    use Fileable, ModelAction;
    public function __construct(AnalyticsService $analyticsService , TwoFactorService $twoFactorService)
    {

        $this->user = auth_user('web');
        $this->analyticsService = new AnalyticsService();
        $this->twoFactorService = new TwoFactorService();


    }



    /**
     * User Dashboard
     *
     * @param Request $request
     * @return
     */
    public function home(Request $request)
    {
        return Inertia::render('Dashboard', [
            "platforms" => Platform::all(),
            'AnalyticalData' => $this->analyticsService->getAnalytics(),
        ]);

    }

    public function profileSettings()
    {
        return Inertia::render('ProfileSettings' , [
             'setup_data' => $this->twoFactorService->getSetupData()
        ]);


    }



    /**
     * profile Update
     * @param Request $request
     * @return RedirectResponse
     */
    public function profileUpdate(Request $request): RedirectResponse
    {

        $user = $this->user;

        if ($user->email == 'demo@cartuser.test') {
            if ($request->expectsJson() || $request->isXmlHttpRequest()) {
                return back()->with(response_status('This Function Is Not Available For Website Demo Mode'));
            }
        }

        $request->validate([
            'name' => ["required", "max:100", 'string'],
            'username' => ['nullable', "string", "max:155", "alpha_dash", 'unique:users,username,' . $this->user->id],
            'phone' => ['unique:users,phone,' . $this->user->id, 'max:191'],
            "phoneCode" => ['nullable', 'string'],
            "country" => ['nullable', 'string'],
            'email' => ['email', 'required', 'unique:users,email,' . $this->user->id],
            "image" => ['nullable', 'image', new FileExtentionCheckRule(json_decode(site_settings('mime_types'), true))]
        ]);

        $user->name = $request->input('name');
        $user->username = $request->input('username') ?? $user->username;
        $user->email = $request->input('email');
        $user->phone = $request->input('phone');
        $user->phone_code = $request->input('phoneCode');
        $user->country_code = $request->input('country');


        $user->save();

        if ($request->hasFile('image')) {
            $oldFile = $user->file()->where('type', FileKey::AVATAR->value)->first();
            $this->saveFile(
                $user,
                $this->storeFile(
                    file: $request->file('image'),
                    location: public_path(config("settings")['file_path']['profile']['user']['path']),
                    removeFile: @$oldFile
                )
                ,
                FileKey::AVATAR->value
            );

        }


        return back()->with(response_status('Profile Updated'));
    }

    public function profileAvatarUpdate(Request $request)
    {

        $user = $this->user;

        if ($request->hasFile('image')) {

            $oldFile = $user->file()->where('type', FileKey::AVATAR->value)->first();
            $this->saveFile(
                $user,
                $this->storeFile(
                    file: $request->file('image'),
                    location: public_path(config("settings")['file_path']['profile']['user']['path']),
                    removeFile: @$oldFile
                )
                ,
                FileKey::AVATAR->value
            );

        }



    }


    /**
     * update password
     *
     * @param Request $request
     * @return RedirectResponse
     */
    public function passwordUpdate(Request $request): RedirectResponse
    {
        $user = $this->user;

        if ($user->email == 'demo@cartuser.test') {
            if ($request->expectsJson() || $request->isXmlHttpRequest()) {
                return back()->with(response_status('This Function Is Not Available For Website Demo Mode'));
            }
        }

        $rules = [
            'current_password' => 'required|max:100',
            'password' => 'required|confirmed|min:6',
        ];

        if (site_settings('strong_password') == StatusEnum::true->status()) {
            $rules['password'] = [
                "required",
                "confirmed",
                Password::min(8)
                    ->mixedCase()
                    ->letters()
                    ->numbers()
                    ->symbols()
                    ->uncompromised()
            ];
        }

        $request->validate($rules);

        if ($this->user->password && !Hash::check($request->input('current_password'), $this->user->password)) {
            return back()->with('error', translate("Your Current Password does not match !!"));
        }

        $user->password = $request->input('password');
        $user->save();
        return back()->with(response_status('Password Updated'));
    }



    /**
     * read a notifications
     *
     */

    public function readNotification(Request $request): string
    {

        $notification = Notification::where('notificationable_type', 'App\Models\User')
            ->where("id", $request->input("id"))
            ->where("notificationable_id", $this->user->id)
            ->first();
        $status = false;
        $message = translate('Notification Not Found');
        if ($notification) {
            $notification->is_read = (StatusEnum::true)->status();
            $notification->save();
            $status = true;
            $message = translate('Notification Readed');
        }
        return json_encode([
            "status" => $status,
            "message" => $message
        ]);

    }


    /**
     * view  all notifications
     *
     */

    public function notification(Request $request): View
    {

        Notification::where('notificationable_type', 'App\Models\User')
            ->where("notificationable_id", $this->user->id)
            ->update([
                "is_read" => (StatusEnum::true)->status()
            ]);

        return view('user.notifications', [
            'notifications' => Notification::where('notificationable_type', 'App\Models\User')
                ->where("notificationable_id", $this->user->id)
                ->latest()
                ->paginate(paginateNumber())
        ]);


    }

    public function profileDelete(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:users,id'
        ]);

        $user = User::findOrFail($request->input('id'));

        // Check if the user being deleted is the owner
        if ($user->owner == StatusEnum::true->status()) {
            return redirect()->back()->with('error', translate('Owner account cannot be deleted. Transfer ownership first before deleting this account.'));
        }

        // Additional check: prevent users from deleting other users if they are not authorized
        // (You might want to add role/permission checks here)

        $user->delete();

        return redirect()->back()->with('success', translate('User profile deleted successfully'));
    }





    /**
     * Webhook Config Update
     * @param Request $request
     * @return RedirectResponse
     */
    public function webhookUpdate(Request $request): RedirectResponse
    {

        $response = response_status('You current plan doesnot have webhook access');
        $response = response_status('Webhook Api Key Updated');
        $request->validate([
            'webhook_api_key' => ['required', 'unique:users,webhook_api_key,' . $this->user->id],
        ]);

        $user = $this->user;
        $user->webhook_api_key = $request->input('webhook_api_key');
        $user->save();

        return back()->with($response);
    }

}
