<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $customer = Auth::guard('customer')->user();
        $rentals = $customer->rentals()->latest()->get();
        $inquiries = $customer->inquiries()->latest()->get();
        
        // Sum up payments from rentals
        $totalPayments = $rentals->sum(function($rental) {
            return $rental->receipts->where('status', '!=', 'cancelled')->sum('amount');
        });

        return view('frontend.customer.dashboard', compact('customer', 'rentals', 'inquiries', 'totalPayments'));
    }

    public function rentals()
    {
        $customer = Auth::guard('customer')->user();
        $rentals = $customer->rentals()->latest()->paginate(10);
        return view('frontend.customer.rentals', compact('rentals'));
    }

    public function rentalShow($id)
    {
        $customer = Auth::guard('customer')->user();
        $rental = $customer->rentals()->with(['car', 'receipts', 'inspection'])->findOrFail($id);
        return view('frontend.customer.rental-show', compact('rental'));
    }

    public function inquiries()
    {
        $customer = Auth::guard('customer')->user();
        $inquiries = $customer->inquiries()->with('car')->latest()->paginate(10);
        return view('frontend.customer.inquiries', compact('inquiries'));
    }

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

    public function updateProfile(Request $request)
    {
        $customer = Auth::guard('customer')->user();
        
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', 'max:20'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:customers,email,'.$customer->id],
            'password' => ['nullable', 'confirmed', \Illuminate\Validation\Rules\Password::defaults()],
        ]);

        $data = [
            'name' => $request->name,
            'phone' => $request->phone,
            'email' => $request->email,
        ];

        if ($request->password) {
            $data['password'] = \Illuminate\Support\Facades\Hash::make($request->password);
        }

        $customer->update($data);

        return back()->with('success', 'تم تحديث الملف الشخصي بنجاح.');
    }
}
