<?php

namespace Core\App\Models;

use PDO;

class FooterSection
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = db();
    }

    /**
     * Get all footer sections ordered
     */
    public function getAll(): array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM footer_sections
            ORDER BY position ASC
        ");
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get enabled footer sections ordered
     */
    public function getEnabled(): array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM footer_sections
            WHERE is_enabled = 1
            ORDER BY position ASC
        ");
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Alias for compatibility
     */
    public function getEnabledOrdered(): array
    {
        return $this->getEnabled();
    }

    /**
     * Get section by ID
     */
    public function getById(int $id): ?array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM footer_sections
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $id]);

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    /**
     * Create section
     */
    public function create(array $data): bool
    {
        $stmt = $this->db->prepare("
            INSERT INTO footer_sections
                (title, position, is_enabled)
            VALUES
                (:title, :position, :is_enabled)
        ");

        return $stmt->execute([
            ':title'      => $data['title'],
            ':position'   => (int)($data['position'] ?? 0),
            ':is_enabled' => (int)($data['is_enabled'] ?? 1),
        ]);
    }

    /**
     * Update section
     */
    public function update(int $id, array $data): bool
    {
        $stmt = $this->db->prepare("
            UPDATE footer_sections
            SET
                title = :title,
                position = :position,
                is_enabled = :is_enabled
            WHERE id = :id
        ");

        return $stmt->execute([
            ':title'      => $data['title'],
            ':position'   => (int)($data['position'] ?? 0),
            ':is_enabled' => (int)($data['is_enabled'] ?? 1),
            ':id'         => $id,
        ]);
    }

    /**
     * Delete section
     */
    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare("
            DELETE FROM footer_sections
            WHERE id = :id
        ");

        return $stmt->execute([':id' => $id]);
    }
}
