<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * MediaModel — manages profile_media table.
 */
class MediaModel extends Model
{
    protected $table       = 'profile_media';
    protected $primaryKey  = 'id';
    protected $useTimestamps = false;
    protected $returnType  = 'array';

    protected $allowedFields = [
        'profile_id', 'media_type', 'title',
        'file_path', 'url', 'file_size', 'mime_type',
        'original_name', 'sort_order',
    ];

    public function getByProfile(int $profileId, string $type = ''): array
    {
        $builder = $this->where('profile_id', $profileId);
        if ($type) {
            $builder->where('media_type', $type);
        }
        return $builder->orderBy('sort_order', 'ASC')->findAll();
    }

    public function deleteWithFile(int $id): bool
    {
        $media = $this->find($id);
        if (! $media) {
            return false;
        }
        if (! empty($media['file_path'])) {
            $path = WRITEPATH . 'uploads/' . ltrim($media['file_path'], '/');
            if (file_exists($path)) {
                @unlink($path);
            }
        }
        return (bool) $this->delete($id);
    }
}
