<?php

namespace Core\App\Models;

class FooterLink
{
    protected string $table = 'footer_links';

    public function create(int $sectionId, array $data): bool
    {
        $type = $data['type'] ?? 'custom';

        // Validation حسب النوع
        if ($type === 'page' && empty($data['page_id'])) {
            return false;
        }

        if ($type === 'custom' && empty($data['url'])) {
            return false;
        }

        if ($type === 'social' && empty($data['url'])) {
            return false;
        }

        return db()->prepare("
            INSERT INTO {$this->table}
            (footer_section_id, label, type, page_id, url, position, is_enabled)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ")->execute([
            $sectionId,
            $data['label'] ?? '',
            $type,
            $type === 'page' ? (int)$data['page_id'] : null,
            in_array($type, ['custom', 'social'], true) ? $data['url'] : null,
            $data['position'] ?? 0,
            1
        ]);
    }

    public function update(int $id, array $data): bool
    {
        $type = $data['type'] ?? 'custom';

        if ($type === 'page' && empty($data['page_id'])) {
            return false;
        }

        if (in_array($type, ['custom', 'social'], true) && empty($data['url'])) {
            return false;
        }

        return db()->prepare("
            UPDATE {$this->table}
            SET
                label = ?,
                type = ?,
                page_id = ?,
                url = ?,
                position = ?,
                is_enabled = ?
            WHERE id = ?
        ")->execute([
            $data['label'] ?? '',
            $type,
            $type === 'page' ? (int)$data['page_id'] : null,
            in_array($type, ['custom', 'social'], true) ? $data['url'] : null,
            $data['position'] ?? 0,
            isset($data['is_enabled']) ? 1 : 1,
            $id
        ]);
    }

    public function delete(int $id): bool
    {
        return db()->prepare("
            DELETE FROM {$this->table}
            WHERE id = ?
        ")->execute([$id]);
    }

    public function getBySection(int $sectionId): array
    {
        return db()->prepare("
            SELECT *
            FROM {$this->table}
            WHERE footer_section_id = ?
              AND is_enabled = 1
            ORDER BY position ASC, id ASC
        ")->execute([$sectionId]) ? db()->query("
            SELECT *
            FROM {$this->table}
            WHERE footer_section_id = {$sectionId}
              AND is_enabled = 1
            ORDER BY position ASC, id ASC
        ")->fetchAll() : [];
    }
}
