<?php

namespace App\Services;

class PaymentService
{
    public function initiate(int $userId, ?int $careRequestId, float $amount, string $method = 'mpesa'): int
    {
        $db = db_connect();
        $reference = 'TL-' . strtoupper(bin2hex(random_bytes(4)));
        $db->table('payments')->insert([
            'user_id'=>$userId,'care_request_id'=>$careRequestId,'reference'=>$reference,
            'amount'=>$amount,'currency'=>'KES','method'=>$method,'status'=>'pending','created_at'=>date('Y-m-d H:i:s')
        ]);
        return (int)$db->insertID();
    }

    public function markPaid(int $paymentId, ?string $gatewayReference = null): bool
    {
        return (bool) db_connect()->table('payments')->where('id',$paymentId)->update([
            'status'=>'paid','gateway_reference'=>$gatewayReference,'paid_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')
        ]);
    }
}
