<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\License;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use App\Models\WalletTransaction;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use App\Mail\UserCredentialsMail;
use App\Mail\UserWelcomeMail;
use App\Helpers\EmailConfig;

class UserController extends Controller
{
    /**
     * Display the user management page.
     */
    public function index()
    {
        $users = User::with('license')->orderBy('created_at', 'desc')->paginate(10);
        return view('admin.users.index', compact('users'));
    }

    /**
     * Show the form for creating a new user.
     */
    public function create()
    {
        $nextUserId = User::max('id') + 1;
        return view('admin.users.create', compact('nextUserId'));
    }

    /**
     * Store a newly created user in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|confirmed|min:8',
            'company_name' => 'required|string|max:255',
            'address' => 'required|string',
            'contact_number' => 'required|string|max:20',
            'alternate_number' => 'nullable|string|max:20',
            'business_type' => 'required|string',
            'website' => 'nullable|url',
            'gstin' => 'nullable|string|max:15',
            'status' => 'required|in:active,inactive,suspended',
            'user_id' => 'required|unique:users,user_id',
            'license_key' => 'required|unique:licenses,key',
            'license_start_date' => 'required|date',
            'expires_at' => 'required|date|after:license_start_date'
        ]);

        // Create user
        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'company_name' => $validated['company_name'],
            'address' => $validated['address'],
            'contact_number' => $validated['contact_number'],
            'alternate_number' => $validated['alternate_number'],
            'business_type' => $validated['business_type'],
            'website' => $validated['website'],
            'gstin' => $validated['gstin'],
            'status' => $validated['status'],
            'user_id' => $validated['user_id']
        ]);

        // Determine if license should be active based on start date
        $licenseStartDate = \Carbon\Carbon::parse($validated['license_start_date']);
        $isLicenseActive = $validated['status'] === 'active' && $licenseStartDate->isPast();

        // Create license
        $license = License::create([
            'key' => $validated['license_key'],
            'user_id' => $user->id,
            'starts_at' => $licenseStartDate,
            'expires_at' => \Carbon\Carbon::parse($validated['expires_at']),
            'is_active' => $isLicenseActive
        ]);

        // Update user status based on license start date
        $finalUserStatus = $validated['status'];
        if ($validated['status'] === 'active' && $licenseStartDate->isFuture()) {
            $finalUserStatus = 'inactive'; // Will be activated when start date arrives
        }
        
        $user->update(['status' => $finalUserStatus]);

        // Update user with license ID
        $user->update(['license_id' => $license->id]);

        // Send welcome email with credentials
        try {
            // Configure email settings
            EmailConfig::configureMail();
            
            // Send welcome email
            Mail::to($user->email)->send(new UserWelcomeMail($user, $validated['password']));
            
            Log::info('Welcome email sent successfully to user: ' . $user->email);
        } catch (\Throwable $e) {
            // Log error but don't block user creation
            Log::error('Failed to send welcome email to user: ' . $user->email, [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }

        return redirect()->route('admin.users.index')
            ->with('success', 'User created successfully.');
    }

    /**
     * Display the specified user.
     */
    public function show(User $user)
    {
        $user->load('license');
        $transactions = WalletTransaction::where('user_id', $user->id)
            ->orderByDesc('id')
            ->limit(10)
            ->get();
        return view('admin.users.show', compact('user', 'transactions'));
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(User $user)
    {
        $user->load('license');
        return view('admin.users.edit', compact('user'));
    }

    /**
     * Update the specified user in storage.
     */
    public function update(Request $request, User $user)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $user->id,
            'company_name' => 'required|string|max:255',
            'address' => 'required|string',
            'contact_number' => 'required|string|max:20',
            'alternate_number' => 'nullable|string|max:20',
            'business_type' => 'required|string',
            'website' => 'nullable|url',
            'gstin' => 'nullable|string|max:15',
            'status' => 'required|in:active,inactive,suspended',
            'license_key' => 'nullable|string|unique:licenses,key,' . optional($user->license)->id,
            'expires_at' => 'nullable|date',
        ]);

        $user->update($validated);

        // Update license status if user status changed
        if ($user->license && $user->status !== $request->old_status) {
            $user->license->update(['is_active' => $user->status === 'active']);
        }

        // Optionally update or create license details
        if ($request->filled('license_key') || $request->filled('expires_at')) {
            if ($user->license) {
                $user->license->update([
                    'key' => $request->input('license_key', $user->license->key),
                    'expires_at' => $request->input('expires_at', $user->license->expires_at),
                    'is_active' => $user->status === 'active',
                ]);
            } else if ($request->filled('license_key')) {
                $license = License::create([
                    'key' => $request->input('license_key'),
                    'user_id' => $user->id,
                    'expires_at' => $request->input('expires_at', now()->addYear()),
                    'is_active' => $user->status === 'active',
                ]);
                $user->update(['license_id' => $license->id]);
            }
        }

        return redirect()->route('admin.users.index')
            ->with('success', 'User updated successfully.');
    }

    /**
     * Update license via dedicated endpoint.
     */
    public function updateLicense(Request $request, User $user)
    {
        $validated = $request->validate([
            'license_key' => 'required|string|unique:licenses,key,' . optional($user->license)->id,
            'expires_at' => 'required|date',
            'is_active' => 'nullable|boolean',
        ]);

        if ($user->license) {
            $user->license->update([
                'key' => $validated['license_key'],
                'expires_at' => $validated['expires_at'],
                'is_active' => array_key_exists('is_active', $validated) ? (bool)$validated['is_active'] : ($user->status === 'active'),
            ]);
        } else {
            $license = License::create([
                'key' => $validated['license_key'],
                'user_id' => $user->id,
                'expires_at' => $validated['expires_at'],
                'is_active' => array_key_exists('is_active', $validated) ? (bool)$validated['is_active'] : ($user->status === 'active'),
            ]);
            $user->update(['license_id' => $license->id]);
        }

        return back()->with('success', 'License updated successfully.');
    }

    /**
     * Remove the specified user from storage.
     */
    public function destroy(User $user)
    {
        // Delete associated license first
        if ($user->license) {
            $user->license->delete();
        }

        $user->delete();

        return redirect()->route('admin.users.index')
            ->with('success', 'User deleted successfully.');
    }

    /**
     * Admin: Credit funds to a user's wallet.
     */
    public function creditWallet(Request $request, User $user)
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:1|max:1000000',
            'note' => 'nullable|string|max:255',
        ]);

        DB::transaction(function () use ($user, $validated) {
            $user->wallet_balance = ($user->wallet_balance ?? 0) + $validated['amount'];
            $user->save();

            WalletTransaction::create([
                'user_id' => $user->id,
                'type' => 'credit',
                'amount' => $validated['amount'],
                'balance_after' => $user->wallet_balance,
                'currency' => 'INR',
                'status' => 'success',
                'meta' => ['source' => 'admin', 'note' => $validated['note'] ?? null],
            ]);
        });

        return redirect()->route('admin.users.show', $user->id)
            ->with('success', 'Wallet credited successfully.');
    }
}