<?php

namespace App\Models;

use App\Core\Model;

class MenuModel extends Model
{
    protected string $table = 'menus';

    /**
     * Semua menu (flat) dengan nama parent, untuk ditampilkan di tabel admin.
     */
    public function getAllFlat(): array
    {
        $stmt = $this->db->query(
            "SELECT m.*, p.label AS parent_label
             FROM {$this->table} m
             LEFT JOIN {$this->table} p ON m.parent_id = p.id
             ORDER BY COALESCE(m.parent_id, m.id) ASC, m.parent_id IS NOT NULL ASC, m.urutan ASC"
        );

        return $stmt->fetchAll();
    }

    /**
     * Daftar menu level atas (untuk pilihan parent di form, submenu tidak boleh
     * jadi parent lagi supaya struktur tetap 2 level).
     */
    public function getParentOptions(): array
    {
        $stmt = $this->db->query(
            "SELECT id, label FROM {$this->table} WHERE parent_id IS NULL ORDER BY urutan ASC"
        );

        return $stmt->fetchAll();
    }

    public function getMenuUtama(): array
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM {$this->table} WHERE parent_id IS NULL AND is_active = 1 ORDER BY urutan ASC"
        );
        $stmt->execute();
        $menus = $stmt->fetchAll();

        foreach ($menus as &$menu) {
            $sub = $this->db->prepare(
                "SELECT * FROM {$this->table} WHERE parent_id = :id AND is_active = 1 ORDER BY urutan ASC"
            );
            $sub->execute(['id' => $menu['id']]);
            $menu['children'] = $sub->fetchAll();
        }

        return $menus;
    }
}
