<?php

namespace App\Http\Controllers;

use App\Models\Property;
use App\Models\Agent;
use App\Models\Inquiry;
use App\Models\ViewingAppointment;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class AgentPortalController extends Controller
{
    // Agent Login Form View
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // Login Authentication Logic
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials, $request->remember)) {
            $request->session()->regenerate();

            if (Auth::user()->role === 'admin') {
                return redirect()->route('admin.dashboard')->with('success', 'Welcome to Admin Portal!');
            }
            return redirect()->route('agent.dashboard')->with('success', 'Logged in to Agent Portal!');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('home')->with('success', 'Successfully logged out.');
    }

    // Agent Portal Dashboard
    public function dashboard()
    {
        $user = Auth::user();
        $agent = $user->agent ?? Agent::first();

        $properties = Property::where('agent_id', $agent->id)->latest()->paginate(10);
        $propertyIds = Property::where('agent_id', $agent->id)->pluck('id');

        $inquiries = Inquiry::whereIn('property_id', $propertyIds)->latest()->take(5)->get();
        $appointments = ViewingAppointment::whereIn('property_id', $propertyIds)->latest()->take(5)->get();

        return view('agent.dashboard', compact('user', 'agent', 'properties', 'inquiries', 'appointments'));
    }

    // Agent Create Property
    public function createProperty()
    {
        return view('agent.properties.create');
    }

    public function storeProperty(Request $request)
    {
        $user = Auth::user();
        $agent = $user->agent ?? Agent::first();

        $request->validate([
            'title' => 'required|string|max:255',
            'price' => 'required|numeric',
            'property_type' => 'required|string',
            'status' => 'required|string',
            'address' => 'required|string',
            'city' => 'required|string',
            'description' => 'required|string',
        ]);

        $images = [];
        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $file) {
                $filename = time() . '_' . rand(100,999) . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('assets/properties'), $filename);
                $images[] = 'assets/properties/' . $filename;
            }
        } else {
            $images[] = 'assets/properties/villa.jpg';
        }

        Property::create([
            'title' => $request->title,
            'slug' => Str::slug($request->title) . '-' . rand(100, 999),
            'description' => $request->description,
            'price' => $request->price,
            'property_type' => $request->property_type,
            'status' => $request->status,
            'featured' => false,
            'bedrooms' => $request->bedrooms ?? 0,
            'bathrooms' => $request->bathrooms ?? 0,
            'sqft' => $request->sqft ?? 0,
            'address' => $request->address,
            'city' => $request->city,
            'state' => $request->state ?? 'Abuja',
            'country' => 'Nigeria',
            'title_document' => $request->title_document ?? 'C of O Verified',
            'features' => $request->features ? array_map('trim', explode(',', $request->features)) : [],
            'images' => $images,
            'agent_id' => $agent->id,
        ]);

        return redirect()->route('agent.dashboard')->with('success', 'Your property listing was published successfully!');
    }

    // Agent Profile Edit
    public function editProfile()
    {
        $user = Auth::user();
        $agent = $user->agent ?? Agent::first();
        return view('agent.profile', compact('user', 'agent'));
    }

    public function updateProfile(Request $request)
    {
        $user = Auth::user();
        $agent = $user->agent ?? Agent::first();

        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string',
            'whatsapp' => 'required|string',
            'bio' => 'nullable|string',
        ]);

        if ($request->hasFile('photo')) {
            $file = $request->file('photo');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('assets/agents'), $filename);
            $agent->photo = 'assets/agents/' . $filename;
        }

        $agent->name = $request->name;
        $agent->phone = $request->phone;
        $agent->whatsapp = $request->whatsapp;
        $agent->bio = $request->bio;
        $agent->save();

        $user->name = $request->name;
        $user->save();

        return back()->with('success', 'Your agent profile has been updated!');
    }
}
