<?php

namespace App\Models;

use CodeIgniter\Model;

class TokenModel extends Model
{
    protected $table      = 'token_api';
    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;

    protected $returnType     = 'array';
    protected $useSoftDeletes = false;

    protected $allowedFields = ['date_last_access', 'ip', 'username', 'user_id', 'token', 'other'];

    // Custom vars

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = true;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

  /**
     * ✅ YENİ: Token doğrulama metodu
     */
    public function validateToken($token)
    {
        if (empty($token)) {
            return false;
        }

        $tokenData = $this->where('token', $token)->first();

        if (!$tokenData) {
            return false;
        }

        // Token yaşı kontrolü (2 ay)
        $tokenDate = strtotime($tokenData['date_last_access']);
        $now = time();
        $tokenAge = $now - $tokenDate;
        $twoMonths = 60 * 60 * 24 * 60; // 60 gün

        if ($tokenAge > $twoMonths) {
            // Token süresi dolmuş
            $this->delete($tokenData['id']);
            return false;
        }

        // Son erişim zamanını güncelle
        $this->update($tokenData['id'], [
            'date_last_access' => date('Y-m-d H:i:s')
        ]);

        return $tokenData;
    }
}