<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * SectionModel — manages the `profile_sections` table.
 *
 * Custom sections (Text / Photo / Video / Document) that members
 * can add to their profile independently of the built-in sections.
 */
class SectionModel extends Model
{
    protected $table         = 'profile_sections';
    protected $primaryKey    = 'id';
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $returnType    = 'array';

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

    // ── Queries ──────────────────────────────────────────────────────

    /**
     * All visible sections for a profile, ordered by sort_order then creation.
     */
    public function getByProfile(int $profileId): array
    {
        return $this->where('profile_id', $profileId)
                    ->where('is_visible', 1)
                    ->orderBy('sort_order', 'ASC')
                    ->orderBy('id', 'ASC')
                    ->findAll();
    }

    /**
     * Delete a section and its associated uploaded file (if any).
     */
    public function deleteWithFile(int $id): bool
    {
        $section = $this->find($id);
        if (! $section) {
            return false;
        }

        // Remove the file from disk if one was uploaded
        if (! empty($section['file_path'])) {
            $path = FCPATH . 'uploads/' . ltrim($section['file_path'], '/');
            if (file_exists($path)) {
                @unlink($path);
            }
        }

        return (bool) $this->delete($id);
    }
}
