<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Comment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\UserSession;
use Carbon\Carbon;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('permission:manage_users');
    }

    public function index()
    {
        return view('admin.dashboard');
    }

    public function users()
    {
        $users = User::with('roles')->get();
        return view('admin.users', compact('users'));
    }

    public function orders()
    {
        return view('admin.orders');
    }

    public function addresses()
    {
        return view('admin.addresses');
    }

    public function promoCodes()
    {
        return view('admin.promo-codes');
    }

    public function createAddresses()
    {
        return view('pages.admin.addresses.create');
    }

    public function postCreateAddress(Request $request)
    {
        $validatedData = $request->validate([
            'address' => 'required|string|min:6',
        ]);

        $data = $request->except('_token');

        $text = trim($data['address']);
        $textAr = explode("\n", $data['address']);  // remove the last \n or whitespace character
        // $a = array_filter($textAr, 'trim'); // remove any extra \r characters left behind

        foreach ($textAr as $address) {
            $trim_address = trim(preg_replace('/\s+/', ' ', $address));
            $new_address = new Address();
            $new_address->address = $address;
            $new_address->save();
        }

        session()->flash('success', 'Successfuly added Address.');

        return back();
    }

    public function currencies()
    {
        return view('admin.currencies');
    }

    public function editUser(User $user)
    {
        if (auth()->user()->hasRole('admin') || $user->manager_id == auth()->user()->id) {
            $user->load(['roles', 'address', 'comments', 'orders']);
            $roles = \App\Models\Role::all();
            $sessions = $user->sessions()->orderByDesc('login_at')->get();
            $managers = User::whereHas('roles', function($query) {
                $query->where('name', 'manager');
            })->get();
            $showLoginAsButton = (auth()->user()->hasRole('admin') || (auth()->user()->hasRole('manager') && $user->manager_id == auth()->user()->id)) && auth()->user()->id != $user->id && !$user->hasRole('admin');
            return view('admin.edit-user', compact('user', 'roles', 'sessions', 'managers', 'showLoginAsButton'));
        } else {
            return redirect()->route('admin.users')->with('error', 'You are not authorized to edit this user.');
        }
    }

    public function addComment(Request $request, User $user)
    {
        $request->validate(['content' => 'required|string|max:1000']);
        $user->comments()->create(['content' => $request->content]);
        return back()->with('message', 'Comment added successfully.');
    }

    public function deleteComment(User $user, Comment $comment)
    {
        if ($comment->user_id === $user->id) {
            $comment->delete();
            return back()->with('message', 'Comment deleted successfully.');
        }
        abort(403);
    }

    public function updateUser(Request $request, User $user)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'login' => 'required|string|max:255',
            'password' => 'nullable|string|min:8',
            'roles' => 'array',
            'address' => 'nullable|string|max:255',
            'promo_code' => 'nullable|string|max:255',
            'manager_id' => 'nullable|exists:users,id',
            'phone_number' => 'nullable|integer'
        ]);

        $user->name = $validated['name'];
        $user->email = $validated['email'];
        $user->login = $validated['login'];
        $user->promo_code = $validated['promo_code'] ?? $user->promo_code;
        if ($request->manager_id == '') {
            $user->manager_id = null;
        } else {
            $user->manager_id = $validated['manager_id'];
        }
        if (!empty($validated['password'])) {
            $user->password = bcrypt($validated['password']);
        }
        
        $user->phone_number = $validated['phone_number'];
        $user->save();
        if (isset($validated['roles'])) {
            $user->roles()->sync($validated['roles']);
        }
        if (!empty($validated['address'])) {
            if ($user->address) {
                $user->address->update(['address' => $validated['address']]);
            } else {
                $user->address()->create(['address' => $validated['address']]);
            }
        } else if ($user->address) {
            $user->address->delete();
        }
        return redirect()->route('admin.users.edit', $user->id)->with('message', 'User updated successfully.');
    }

    public function loginAsUser(User $user)
    {
        if (!auth()->user()->hasRole('admin') && !auth()->user()->hasRole('manager')) {
            return redirect()->route('admin.users')->with('message', 'Only administrators and managers can impersonate users.');
        }

        if (auth()->user()->hasRole('manager') && $user->manager_id != auth()->user()->id) {
            return redirect()->route('admin.users')->with('message', 'You are not authorized to impersonate this user.');
        }
        // Store original user ID in session
        session()->put('impersonator_id', auth()->id());
        
        // Login as the requested user
        Auth::login($user);
        
        return redirect()->route('dashboard')->with('success', 'You are now logged in as ' . $user->name);
    }
} 