<?php

namespace App\Services;

use App\Models\Customer;
use App\Models\Order;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class CustomerPortalService
{
    public function authenticate(string $phone, string $pin): Customer
    {
        $customer = Customer::query()->where('phone', $phone)->where('is_active', true)->first();

        if (! $customer || ! Hash::check($pin, $customer->pin)) {
            throw ValidationException::withMessages(['phone' => 'Nomor HP atau PIN tidak cocok.']);
        }

        return $customer;
    }

    public function resetPin(Customer $customer): void
    {
        $customer->update(['pin' => Hash::make('000000'), 'pin_changed_at' => null]);
    }

    public function trackingData(Order $order): array
    {
        $order->load(['customer', 'progressLogs', 'details']);

        return [
            'id' => $order->id,
            'invoice_no' => $order->invoice_no,
            'status' => $order->status,
            'payment_status' => $order->payment_status,
            'tanggal_masuk' => $order->received_at?->format('d/m/Y H:i') ?? '-',
            'estimasi_selesai' => $order->estimated_done_at?->format('d/m/Y H:i') ?? '-',
            'sisa_tagihan' => (float) $order->balance_due,
            'progress' => $order->progressLogs->sortBy('created_at')->values(),
            'details' => $order->details,
        ];
    }
}
