<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Meeting;
use App\Models\Order;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $client = Auth::guard('client')->user();

        $stats = [
            'orders_total'     => $client->orders()->count(),
            'orders_open'      => $client->orders()->open()->count(),
            'orders_completed' => $client->orders()->where('status', 'completed')->count(),
            'meetings_total'   => $client->meetings()->count(),
        ];

        $recentOrders   = $client->orders()->with('service', 'assignedUser')->latest()->limit(5)->get();
        $upcomingMeetings = $client->meetings()
            ->whereIn('status', ['pending', 'confirmed'])
            ->where('preferred_date', '>=', today())
            ->orderBy('preferred_date')
            ->limit(3)
            ->get();

        return view('client.dashboard.index', compact('client', 'stats', 'recentOrders', 'upcomingMeetings'));
    }

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

    public function updateProfile(\Illuminate\Http\Request $request)
    {
        $client = Auth::guard('client')->user();

        $data = $request->validate([
            'name'         => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'phone'        => 'required|string|max:30',
            'position'     => 'nullable|string|max:120',
            'industry'     => 'nullable|string|max:120',
            'website'      => 'nullable|url|max:255',
            'address'      => 'nullable|string',
            'password'     => 'nullable|string|min:6|confirmed',
        ]);

        if (empty($data['password'])) {
            unset($data['password']);
        }
        $client->update($data);

        return back()->with('success', 'Мэдээлэл шинэчлэгдлээ.');
    }
}
