<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * SectionItemModel — manages the `profile_section_items` table.
 *
 * Each row represents one photo, video-URL, or document that
 * belongs to a custom profile section.  Text sections store
 * their content directly in `profile_sections.content` and
 * do not use this table.
 */
class SectionItemModel extends Model
{
    protected $table         = 'profile_section_items';
    protected $primaryKey    = 'id';
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = '';             // no updated_at column
    protected $returnType    = 'array';

    protected $allowedFields = [
        'section_id', 'file_path', 'url',
        'original_name', 'file_size', 'mime_type', 'sort_order',
    ];

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

    /**
     * All items for a single section, ordered by sort_order then id.
     */
    public function getBySection(int $sectionId): array
    {
        return $this->where('section_id', $sectionId)
                    ->orderBy('sort_order', 'ASC')
                    ->orderBy('id', 'ASC')
                    ->findAll();
    }

    /**
     * All items for multiple sections in one query.
     * Returns an array keyed by section_id for O(1) lookup in PHP.
     *
     * @param  int[]  $sectionIds
     * @return array  ['<section_id>' => [item, ...], ...]
     */
    public function getBySections(array $sectionIds): array
    {
        if (empty($sectionIds)) {
            return [];
        }

        $rows = $this->whereIn('section_id', $sectionIds)
                     ->orderBy('sort_order', 'ASC')
                     ->orderBy('id', 'ASC')
                     ->findAll();

        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row['section_id']][] = $row;
        }
        return $grouped;
    }

    // ── Mutations ─────────────────────────────────────────────────────────────

    /**
     * Delete an item and remove its uploaded file from disk (if any).
     */
    public function deleteWithFile(int $id): bool
    {
        $item = $this->find($id);
        if (! $item) {
            return false;
        }

        if (! empty($item['file_path'])) {
            $path = FCPATH . 'uploads/' . ltrim($item['file_path'], '/');
            if (file_exists($path)) {
                @unlink($path);
            }
        }

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

    /**
     * Delete ALL items for a section (used when the section itself is deleted).
     * Also removes uploaded files from disk.
     */
    public function deleteAllForSection(int $sectionId): void
    {
        $items = $this->getBySection($sectionId);
        foreach ($items as $item) {
            if (! empty($item['file_path'])) {
                $path = FCPATH . 'uploads/' . ltrim($item['file_path'], '/');
                if (file_exists($path)) {
                    @unlink($path);
                }
            }
        }
        $this->where('section_id', $sectionId)->delete();
    }
}
