<?php

namespace App\Models;

use CodeIgniter\Model;

class TransactionModel extends Model
{
    protected $table = 'transactions';
    protected $allowedFields = [
        'msisdn',
        'customer_msisdn',
        'amount',
        'transaction_id',
        'naration',
        'payment_method', // cash | points | crypto
        'status',       // Stores integer values: 0=pending, 1=success, 2=failed
        'tip_id',
        'plan_id',
        'builder_ticket_id',
        'tip_unlocked',
        'points_used',
        'points_awarded',
        'created_at',
        'updated_at',
        'status_check_attempts'
    ];
    protected $useTimestamps = true;
    
    // Add this to ensure status values are consistent
    protected $beforeInsert = ['setStatusFormat', 'setTipUnlocked'];
    protected $beforeUpdate = ['setStatusFormat', 'setTipUnlocked'];
    
    protected function setStatusFormat(array $data)
    {
        if (isset($data['data']['status'])) {
            // Convert status to integer if it's a string
            if (is_string($data['data']['status'])) {
                $status = strtolower($data['data']['status']);
                if ($status === 'success' || $status === '1') {
                    $data['data']['status'] = 1;
                } elseif ($status === 'failed' || $status === '2') {
                    $data['data']['status'] = 2;
                } else {
                    $data['data']['status'] = 0; // pending
                }
            } else {
                // Ensure it's an integer
                $data['data']['status'] = (int) $data['data']['status'];
            }
        }
        return $data;
    }

    protected function setTipUnlocked(array $data)
    {
        if (isset($data['data']['tip_unlocked'])) {
            $data['data']['tip_unlocked'] = (int) $data['data']['tip_unlocked'];
        }
        return $data;
    }

    /**
     * Update transaction status
     * 
     * @param string $transactionId
     * @param string $status
     * @param bool $tipUnlocked
     * @return bool
     */
    public function updateStatus(string $transactionId, string $status, bool $tipUnlocked = false): bool
    {
        return $this->where('transaction_id', $transactionId)
                    ->set([
                        'status' => strtolower($status),
                        'tip_unlocked' => $tipUnlocked ? 1 : 0
                    ])
                    ->update();
    }
}