<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PortalAuthController extends Controller
{
    public function showLoginForm()
    {
        return view('portal.auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'phone' => 'required|string',
        ]);

        // Clean phone number (optional, depending on storage format)
        // For now, exact match or simple 'like' search
        $phone = $request->phone;

        // Find customer
        $customer = Customer::where('phone', $phone)
            ->orWhere('whatsapp', $phone) // Also check whatsapp if applicable
            ->first();

        if (!$customer) {
            return back()->with('error', __('PhoneNumber not found in our records.'))->withInput();
        }

        if ($customer->status !== 'active') {
            return back()->with('error', __('Your account is not active.'))->withInput();
        }

        // Ensure token exists
        if (empty($customer->portal_token)) {
            $customer->portal_token = Str::random(32);
            $customer->save();
        }

        return redirect()->route('portal.index', ['token' => $customer->portal_token]);
    }
}
