<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

class File extends Model
{
    protected $table = 'filedata';

    protected $fillable = [
        'title',
        'group_id',
        'upload_file',
        'file_type',
        'epglink',
        'username',
        'password',
        'status',
        'expiray_date',
        'external_link',
        'created_by',
    ];
    
    protected $appends = ['display_status'];

    protected $casts = [
        'expiray_date' => 'date',
    ];

    // Automatically decrypt password when accessed
    protected function password(): \Illuminate\Database\Eloquent\Casts\Attribute
    {
        return \Illuminate\Database\Eloquent\Casts\Attribute::make(
            get: function($value) {
                if (!$value) return null;
                try {
                    return Crypt::decrypt($value);
                } catch (\Exception $e) {
                    // Return as-is if it's not encrypted (for existing plain text passwords)
                    return $value;
                }
            },
            set: fn($value) => $value ? Crypt::encrypt($value) : null,
        );
    }
    
    protected function displayStatus(): \Illuminate\Database\Eloquent\Casts\Attribute
    {
        return \Illuminate\Database\Eloquent\Casts\Attribute::make(
            get: function() {
                if ($this->expiray_date && $this->expiray_date->endOfDay()->isPast()) {
                    return 'expired';
                }
                return $this->status;
            },
        );
    }
    
     public function group()
    {
        return $this->belongsTo(Group::class, 'group_id');
    } 
    public function codes()
    {
        return $this->hasMany(Code::class, 'file_id');
    }
}
