<?php

namespace App\Http\Controllers\Partner;

use App\Http\Controllers\Controller;
use App\Models\Partner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function show()
    {
        $partner = Partner::findOrFail(auth()->user()->partner_id);
        return view('partner.profile.show', compact('partner'));
    }

    public function edit()
    {
        $partner = Partner::findOrFail(auth()->user()->partner_id);
        return view('partner.profile.edit', compact('partner'));
    }

    public function update(Request $request)
    {
        $partner = Partner::findOrFail(auth()->user()->partner_id);
        
        $validated = $request->validate([
            'company_name' => 'required|string|max:255',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
            'whatsapp' => 'nullable|string|max:20',
            'email' => 'required|email|max:255',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        // Handle logo upload
        if ($request->hasFile('logo')) {
            // Delete old logo if exists
            if ($partner->logo && Storage::disk('public')->exists($partner->logo)) {
                Storage::disk('public')->delete($partner->logo);
            }
            
            // Store new logo
            $logoPath = $request->file('logo')->store('partners/logos', 'public');
            $validated['logo'] = $logoPath;
        } else {
            // Keep existing logo if not uploading new one
            $validated['logo'] = $partner->logo;
        }

        $partner->update($validated);

        // Update user email if changed
        $user = auth()->user();
        if ($user->email !== $validated['email']) {
            $user->update(['email' => $validated['email']]);
        }

        return redirect()->route('partner.profile.show')->with('success', 'Company profile updated successfully.');
    }
}
