<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class ReporterApplication extends Model
{
    use HasFactory;

    protected $fillable = [
        'full_name',
        'father_husband_name',
        'dob',
        'gender',
        'address',
        'mobile_number',
        'whatsapp_number',
        'email',
        'highest_qualification',
        'school_college_name',
        'applying_for',
        'area',
        'has_experience',
        'experience_details',
        'skills',
        'has_smartphone',
        'has_microphone',
        'has_internet',
        'availability_daily',
        'photo_path',
        'id_proof_path',
        'status',
        'admin_remarks',
    ];

    protected $casts = [
        'applying_for'       => 'array',
        'skills'             => 'array',
        'dob'                => 'date',
        'has_experience'     => 'boolean',
        'has_smartphone'     => 'boolean',
        'has_microphone'     => 'boolean',
        'has_internet'       => 'boolean',
        'availability_daily' => 'boolean',
    ];

    protected static function booted(): void
    {
        static::deleted(function (ReporterApplication $app) {
            self::deleteStorageFile($app->photo_path);
            self::deleteStorageFile($app->id_proof_path);
        });

        static::updating(function (ReporterApplication $app) {
            if ($app->isDirty('photo_path')) {
                self::deleteStorageFile($app->getOriginal('photo_path'));
            }
            if ($app->isDirty('id_proof_path')) {
                self::deleteStorageFile($app->getOriginal('id_proof_path'));
            }
        });
    }

    private static function deleteStorageFile(?string $path): void
    {
        if ($path && ! str_starts_with($path, 'http')) {
            Storage::disk('public')->delete($path);
        }
    }
}
