<?php

namespace App\Http\Controllers\Reseller;

use App\Http\Controllers\Controller;
use App\Models\Reseller;
use App\Models\User;
use App\Models\Order;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Facades\Validator;

class ResellerController extends Controller
{
    public function showLoginForm()
    {
        return view('reseller.login');
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $credentials = $request->only('email', 'password');
            if (Auth::guard('resellers')->attempt($credentials)) {
                $reseller = Auth::guard('resellers')->user();
                
                if ($reseller->status !== 'active') {
                    Auth::guard('resellers')->logout();
                    return redirect()->back()->withErrors(['error' => 'Your account is not active.'])->withInput();
                }

                return redirect()->route('reseller.dashboard');
            } else {
                return redirect()->back()->withErrors(['error' => 'Invalid credentials'])->withInput();
            }
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'Something went wrong'])->withInput();
        }
    }

    public function logout()
    {
        Auth::guard('resellers')->logout();
        return redirect()->route('reseller.login');
    }

    public function dashboard()
    {
        $reseller = Auth::guard('resellers')->user();
        
        $totalUsers = User::where('reseller_id', $reseller->id)->count();
        $activeUsers = User::where('reseller_id', $reseller->id)->where('isPremium', 1)->count();
        $totalRevenue = Order::whereHas('user', function ($query) use ($reseller) {
            $query->where('reseller_id', $reseller->id);
        })->sum('price');
        
        $recentOrders = Order::whereHas('user', function ($query) use ($reseller) {
            $query->where('reseller_id', $reseller->id);
        })->with('user')->latest()->take(10)->get();

        return view('reseller.dashboard', compact(
            'reseller',
            'totalUsers',
            'activeUsers',
            'totalRevenue',
            'recentOrders'
        ));
    }

    public function users(Request $request)
    {
        $reseller = Auth::guard('resellers')->user();
        
        $query = User::where('reseller_id', $reseller->id);

        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->search}%")
                  ->orWhere('email', 'like', "%{$request->search}%");
            });
        }

        if ($request->status) {
            $query->where('isPremium', $request->status === 'active' ? 1 : 0);
        }

        $users = $query->orderBy('created_at', 'desc')->paginate(20);

        return view('reseller.users', compact('users'));
    }

    public function createUserForm()
    {
        return view('reseller.user-create');
    }

    public function createUser(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:6|confirmed',
            'phone' => 'nullable|string|max:20',
            'expiry_date' => 'nullable|date',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $reseller = Auth::guard('resellers')->user();

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'reseller_id' => $reseller->id,
            'reseller_commission' => $reseller->commission_rate,
            'isPremium' => 1,
            'expired_date' => $request->expiry_date,
        ]);

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

    public function editUser($id)
    {
        $reseller = Auth::guard('resellers')->user();
        $user = User::where('id', $id)->where('reseller_id', $reseller->id)->firstOrFail();

        return view('reseller.user-edit', compact('user'));
    }

    public function updateUser(Request $request, $id)
    {
        $reseller = Auth::guard('resellers')->user();
        $user = User::where('id', $id)->where('reseller_id', $reseller->id)->firstOrFail();

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $id,
            'password' => 'nullable|string|min:6|confirmed',
            'phone' => 'nullable|string|max:20',
            'expiry_date' => 'nullable|date',
            'isPremium' => 'required|in:0,1',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $user->name = $request->name;
        $user->email = $request->email;
        $user->phone = $request->phone;
        $user->expired_date = $request->expiry_date;
        $user->isPremium = $request->isPremium;

        if ($request->password) {
            $user->password = Hash::make($request->password);
        }

        $user->save();

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

    public function deleteUser($id)
    {
        $reseller = Auth::guard('resellers')->user();
        $user = User::where('id', $id)->where('reseller_id', $reseller->id)->firstOrFail();

        $user->delete();

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

    public function profile()
    {
        $reseller = Auth::guard('resellers')->user();
        return view('reseller.profile', compact('reseller'));
    }

    public function updateProfile(Request $request)
    {
        $reseller = Auth::guard('resellers')->user();

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:resellers,email,' . $reseller->id,
            'phone' => 'nullable|string|max:20',
            'company_name' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $reseller->name = $request->name;
        $reseller->email = $request->email;
        $reseller->phone = $request->phone;
        $reseller->company_name = $request->company_name;
        $reseller->save();

        return redirect()->route('reseller.profile')->with('success', 'Profile updated successfully.');
    }

    public function changePassword(Request $request)
    {
        $reseller = Auth::guard('resellers')->user();

        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        if (!Hash::check($request->current_password, $reseller->password)) {
            return redirect()->back()->withErrors(['current_password' => 'Current password is incorrect.'])->withInput();
        }

        $reseller->password = Hash::make($request->password);
        $reseller->save();

        return redirect()->route('reseller.profile')->with('success', 'Password changed successfully.');
    }

    public function orders(Request $request)
    {
        $reseller = Auth::guard('resellers')->user();
        
        $query = Order::whereHas('user', function ($q) use ($reseller) {
            $q->where('reseller_id', $reseller->id);
        })->with('user');

        if ($request->search) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->search}%")
                  ->orWhere('email', 'like', "%{$request->search}%");
            });
        }

        $orders = $query->orderBy('created_at', 'desc')->paginate(20);

        // Get credit requests for this reseller
        $creditRequests = \App\Models\CreditRequest::where('reseller_id', $reseller->id)
            ->with('creditPackage')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('reseller.orders', compact('orders', 'creditRequests'));
    }

    public function addBalance(Request $request)
    {
        $reseller = Auth::guard('resellers')->user();

        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:1',
            'payment_method' => 'nullable|string',
            'proof_of_payment' => 'nullable|image|mimes:jpeg,png,jpg,gif,pdf|max:2048',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Handle proof of payment upload
        $proofPath = null;
        if ($request->hasFile('proof_of_payment')) {
            $proofPath = $request->file('proof_of_payment')->store('proof_of_payment', 'public');
        }

        // Use the new credit system
        $reseller->addCredit(
            $request->amount,
            'credit',
            'Balance added via ' . ($request->payment_method ?? 'manual'),
            null,
            null,
            $proofPath
        );

        return redirect()->route('reseller.dashboard')->with('success', 'Balance added successfully.');
    }

    /**
     * Credit management - show transactions
     */
    public function creditTransactions(Request $request)
    {
        $reseller = Auth::guard('resellers')->user();
        
        $query = $reseller->creditTransactions();

        if ($request->type) {
            $query->where('type', $request->type);
        }

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $transactions = $query->orderBy('created_at', 'desc')->paginate(20);

        return view('reseller.credit.transactions', compact('transactions'));
    }

    /**
     * Credit summary/dashboard
     */
    public function creditSummary()
    {
        $reseller = Auth::guard('resellers')->user();

        $stats = [
            'current_balance' => $reseller->balance,
            'total_earned' => $reseller->totalCommissionEarned(),
            'total_credits' => $reseller->totalCreditsAdded(),
            'total_debits' => $reseller->totalDebits(),
        ];

        $recentTransactions = $reseller->recentTransactions(10);

        return view('reseller.credit.summary', compact('stats', 'recentTransactions'));
    }

    /**
     * Request withdrawal
     */
    public function requestWithdrawal(Request $request)
    {
        $reseller = Auth::guard('resellers')->user();

        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:1',
            'payment_details' => 'required|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        if ($reseller->balance < $request->amount) {
            return redirect()->back()->withErrors(['amount' => 'Insufficient balance.'])->withInput();
        }

        // Create a pending debit transaction (admin will process)
        $reseller->deductCredit(
            $request->amount,
            'debit',
            'Withdrawal request: ' . $request->payment_details,
            null,
            null
        );

        return redirect()->route('reseller.credit.transactions')->with('success', 'Withdrawal request submitted successfully.');
    }

    /**
     * Display available credit packages
     */
    public function creditPackages()
    {
        $packages = \App\Models\CreditPackage::where('is_active', true)->orderBy('price', 'asc')->get();
        return view('reseller.credit.packages', compact('packages'));
    }

    /**
     * Request a credit package
     */
    public function requestCreditPackage(Request $request, $id)
    {
        $package = \App\Models\CreditPackage::findOrFail($id);
        
        $validator = Validator::make($request->all(), [
            'payment_method' => 'required|string',
            'payment_reference' => 'required|string',
            'proof_of_payment' => 'nullable|image|mimes:jpeg,png,jpg,gif,pdf|max:2048',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $reseller = Auth::guard('resellers')->user();

        // Handle proof of payment upload
        $proofPath = null;
        if ($request->hasFile('proof_of_payment')) {
            $proofPath = $request->file('proof_of_payment')->store('proof_of_payment', 'public');
        }

        \App\Models\CreditRequest::create([
            'reseller_id' => $reseller->id,
            'credit_package_id' => $package->id,
            'amount_paid' => $package->price,
            'payment_method' => $request->payment_method,
            'payment_reference' => $request->payment_reference,
            'proof_of_payment' => $proofPath,
            'status' => 'pending',
        ]);

        return redirect()->route('reseller.credit.summary')->with('success', 'Credit package request submitted. Waiting for admin approval.');
    }
}