<?php

namespace App\Models;

use CodeIgniter\Model;

class BuilderTicketModel extends Model
{
    protected $table = 'builder_tickets';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'msisdn',
        'match_ids',
        'legs_snapshot',
        'combined_odds',
        'leg_count',
        'amount',
        'transaction_id',
        'status',
        'created_at',
        'updated_at',
    ];

    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    // JSON-encode arrays on write.
    protected $beforeInsert = ['encodeJsonFields'];
    protected $beforeUpdate = ['encodeJsonFields'];

    protected function encodeJsonFields(array $data): array
    {
        foreach (['match_ids', 'legs_snapshot'] as $field) {
            if (isset($data['data'][$field]) && is_array($data['data'][$field])) {
                $data['data'][$field] = json_encode($data['data'][$field]);
            }
        }
        return $data;
    }

    /**
     * Mark a ticket as paid after successful payment.
     */
    public function markPaid(int $ticketId, ?string $transactionId = null): bool
    {
        $update = [
            'status' => 'paid',
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if ($transactionId !== null && $transactionId !== '') {
            $update['transaction_id'] = $transactionId;
        }
        return (bool) $this->update($ticketId, $update);
    }
}
