<?php

declare(strict_types=1);

namespace App\Http\Controllers\Pages;

use Hypervel\Http\Request;
use App\Models\User;

use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Log;
use Hypervel\Support\Facades\Redis;
use Hypervel\Support\Facades\Response;

use Hypervel\Support\Facades\Hash;
use Hypervel\Support\Facades\Session;

use App\Http\Controllers\Pages\PageController;

class AccountSettingsPageController
{

    public $JSCommands = [
        'SetDarkMode' => "UISetDarkMode();"
    ];

    public function listDetails()
    {
        $currentuser = User::findOrFail(Auth::id());
        $res = [];

        $res['photourl'] = $currentuser->photourl[0] ?? '';
        $res['mobile'] = $currentuser->mobile_number ?? '';
        $res['name'] = $currentuser->name ?? $currentuser->nickname ?? $currentuser->fullname ?? $currentuser->username ?? '';
        $res['fullname'] = $currentuser->fullname ?? $currentuser->name ?? '';
        $res['nickname'] = $currentuser->nickname ?? $currentuser->username ?? '';
        $res['joined'] = $currentuser->created_at ?? '';
        $res['referralcode'] = $currentuser->referralcode ?? '';
        $res['email'] = $currentuser->email ?? '';
        $res['landline'] = $currentuser->landline ?? '';
        $res['hashkey'] = $currentuser->hashkey ?? '';
        $res['total_balance'] = $currentuser->total_balance ?? 0;
        $res['settings'] = $currentuser->settings ?? [];


        return Response::json($res ?: []);
    }

    public function listSettings()
    {
        return Response::json(Auth::user()->settings);
    }


    public function listRunScripts()
    {
        $scripts = '';
        $settings = Auth::user()->settings;
        $darkmode = $settings['dark_mode'] ?? $settings['darkmode'] ?? false;



        if ($darkmode) {
            $scripts .= $this->JSCommands['SetDarkMode'];
        }

        Response::raw($scripts);
    }

    public function changepassword(Request $request)
    {

        $validated = $request->validate([
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:6',
            'new_confirm_password' => 'required|string|same:new_password',
        ]);

        if (!$validated['current_password'] or !$validated['new_password'] or !$validated['new_confirm_password']) {
            return Response::json(['message' => 'Enter Old Password, New Password and Password Confirmation.'], 400);
        }

        try {
            $user = User::findOrFail(Auth::id());
        } catch (\Throwable $th) {
            return Response::json(['message' => 'Internal server error during credit transfer'], 500);
        }

        $newhash = Hash::make($validated['current_password']);
        if (!Hash::check($validated['current_password'], $user->password)) {
            return Response::json(['message' => 'Your current password is incorrect.'], 400);
        }

        $user->password = Hash::make($validated['new_password']);
        $user->save();
        return Response::json(['message' => 'Password changed successfully'], 200);
    }

    public function getUserNotes()
    {
        try {
            $user = User::findOrFail(Auth::id());
            return Response::json($user->notes, 200);
        } catch (\Throwable $th) {
            return Response::json(['message' => 'User Not Found!'], 404);
        }
    }

    public function clearUserNotes()
    {
        try {
            $user = User::findOrFail(Auth::id());
          $user->notes='';
          $user->save();
          return Response::json(['success' => true], 200);
        } catch (\Throwable $th) {
           return Response::json(['message' => 'User Not Found!'], 404);
        }
    }

    
    public function logoutnow()
    {
        $sessionId = session()?->getId();
        $user = Auth::user();
        
        Log::info('[Logout] Attempting logout for session: ' . $sessionId);
        
        if ($user && isset($user->hashkey)) {
            // Signal SSE streams to terminate
            Redis::setex("forced_logout:{$user->hashkey}", 60, "1");
            Log::info('[Logout] Forced logout signal set for user: ' . $user->hashkey);
        }

        // Logout from all possible guards
        Auth::logout();
        try {
            if (Auth::guard('jwt')->check()) {
                Auth::guard('jwt')->logout();
            }
        } catch (\Throwable $th) {
            // Ignore if JWT guard is not properly configured
        }
        
        if (session()) {
            session()->flush();
            session()->invalidate();
            Log::info('[Logout] Session invalidated. New ID: ' . session()->getId());
        }

        // Forced Redis destruction for THIS session ID (covers multiple prefix formats)
        if ($sessionId) {
            $prefix = config('cache.prefix', 'bukidbountyapp_cache');
            
            // Try idiomatic Cache forget first (handles prefixing automatically)
            \Hypervel\Support\Facades\Cache::forget($sessionId);
            
            // Try manual Redis deletion for both common prefix patterns (with and without colon)
            Redis::del(($prefix ? $prefix . ':' : '') . $sessionId);
            Redis::del(($prefix ? $prefix : '') . $sessionId);
            
            Log::info('[Logout] Forced Redis/Cache deletion for session: ' . $sessionId);
        }

        return redirect('/login?logged_out=1');
    }


    public function updatePhoto(Request $request)
    {
        if (!$request->hasFile('photo')) {
            return Response::json(['success' => false, 'message' => 'No photo uploaded'], 400);
        }

        try {
            $user = User::findOrFail(Auth::id());
            $file = $request->file('photo');
            $filename = $file->getClientFilename();
            
            // Upload the file using FilesMainController
            $result = \App\Http\Controllers\FilesMainController::uploadFileList(
                $file,
                'User Profile Photo: ' . $user->username,
                $filename ?? 'profile_photo.jpg',
                'Uploaded by ' . $user->username,
                ['user_id' => $user->id, 'type' => 'profile_photo'],
                'user_photos',
                ['profile_photo'],
                0,
                'profile_photo',
            );

            // If it's a response object, it might be an error response from uploadFileList
            if (is_object($result) && method_exists($result, 'getStatusCode')) {
                return $result;
            }

            if ($result && isset($result->hashkey)) {
                $photoUrl = $result->resolvedUrl();
                
                // Update user photoUrl array
                $user->photourl = [$photoUrl];
                $user->save();

                return Response::json([
                    'success' => true, 
                    'message' => 'Photo updated successfully',
                    'url' => $photoUrl
                ]);
            }

            return Response::json(['success' => false, 'message' => 'Failed to process file upload: No result hashkey.'], 500);

        } catch (\Throwable $th) {
            return Response::json(['success' => false, 'message' => $th->getMessage()], 500);
        }
    }

}
