<?php
declare(strict_types=1);

namespace App\Modules\Sales\Services;

use App\Core\App;
use App\Core\Logger;

/**
 * Guest payment wrapper — bypasses the member_id validation in PaymentService.
 * Creates payment + receipt directly for guest sales.
 */
final class InventoryPaymentService
{
    /**
     * Process a guest payment (no member_id required).
     */
    public static function processGuestPayment(array $data): array
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $amount        = $data['amount'] ?? '0.00';
        $paymentMethod = $data['payment_method'] ?? 'cash';
        $guestName     = $data['guest_name'] ?? 'زائر';
        $description   = $data['description'] ?? 'مبيعات مخزون (زائر)';

        if (bccomp((string) $amount, '0.01', 2) < 0) {
            return ['success' => false, 'error' => 'المبلغ يجب أن يكون أكبر من صفر'];
        }

        $db->beginTransaction();
        try {
            // Generate receipt number (same pattern as PaymentService)
            $year = date('Y');
            $prefix = 'REC-' . $year . '-';
            $last = $db->selectOne(
                "SELECT receipt_number FROM receipts WHERE receipt_number LIKE ? ORDER BY id DESC LIMIT 1",
                [$prefix . '%']
            );
            $seq = $last ? ((int) substr($last['receipt_number'], -6)) + 1 : 1;
            $receiptNumber = $prefix . str_pad((string) $seq, 6, '0', STR_PAD_LEFT);

            // Create payment record (member_id = NULL for guest)
            $paymentId = $db->insert('payments', [
                'member_id'               => null,
                'payment_type'            => 'inventory_sale',
                'amount'                  => $amount,
                'currency'                => 'EGP',
                'payment_method'          => $paymentMethod,
                'related_entity_type'     => $data['related_entity_type'] ?? null,
                'related_entity_id'       => $data['related_entity_id'] ?? null,
                'notes'                   => $description . ' — ' . $guestName,
                'payment_date'            => date('Y-m-d'),
                'received_by_employee_id' => $employee ? (int) $employee->id : null,
                'is_voided'               => 0,
                'created_at'              => date('Y-m-d H:i:s'),
                'updated_at'              => date('Y-m-d H:i:s'),
                'created_by'              => $employee ? (int) $employee->id : null,
            ]);

            // Create receipt (member_id = NULL — requires Phase_25_021 migration)
            $receiptId = $db->insert('receipts', [
                'receipt_number'        => $receiptNumber,
                'member_id'             => null,
                'payment_id'            => $paymentId,
                'receipt_type'          => 'payment',
                'amount'                => $amount,
                'amount_in_words_ar'    => function_exists('number_to_arabic_words') ? number_to_arabic_words((float) $amount) : '',
                'description_ar'        => $description,
                'issued_by_employee_id' => $employee ? (int) $employee->id : null,
                'issued_at'             => date('Y-m-d H:i:s'),
                'is_voided'             => 0,
                'print_count'           => 0,
                'created_at'            => date('Y-m-d H:i:s'),
            ]);

            $db->update('payments', ['receipt_id' => $receiptId], '`id` = ?', [$paymentId]);

            $db->commit();

            Logger::info("Guest payment #{$paymentId} processed — receipt: {$receiptNumber}");

            return [
                'success'        => true,
                'payment_id'     => $paymentId,
                'receipt_id'     => $receiptId,
                'receipt_number' => $receiptNumber,
                'amount'         => $amount,
            ];

        } catch (\Throwable $e) {
            $db->rollBack();
            Logger::error("Guest payment failed: " . $e->getMessage());
            return ['success' => false, 'error' => 'فشل تسجيل الدفع: ' . $e->getMessage()];
        }
    }
}
