<?php include ROOT_PATH . '/admin/templates/header.php'; ?>

<?php
use Core\App\Models\Page;
use Core\App\Models\Settings;

$MAX_ITEMS = 6;
$currentCount = is_array($links) ? count($links) : 0;
$limitReached = $currentCount >= $MAX_ITEMS;

$pagesModel = new Page();
$pagesList  = $pagesModel->getAllIndexed('id');

$settingsModel = new Settings();
$settings = $settingsModel->getAll();

$sectionType = $section['type'] ?? 'pages';

$socialNetworks = [
    'facebook'  => 'Facebook',
    'instagram' => 'Instagram',
    'twitter'   => 'Twitter',
    'tiktok'    => 'TikTok',
    'youtube'   => 'YouTube',
    'linkedin'  => 'LinkedIn',
    'snapchat'  => 'Snapchat',
    'telegram'  => 'Telegram',
];

/**
 * المصدر الافتراضي: جدول settings
 */
$socialMap = [
    'facebook'  => $settings['social_facebook']  ?? '',
    'instagram' => $settings['social_instagram'] ?? '',
    'twitter'   => $settings['social_twitter']   ?? '',
    'tiktok'    => $settings['social_tiktok']    ?? '',
    'youtube'   => $settings['social_youtube']   ?? '',
    'linkedin'  => $settings['social_linkedin']  ?? '',
    'snapchat'  => $settings['social_snapchat']  ?? '',
    'telegram'  => $settings['social_telegram']  ?? '',
];

/**
 * إن وُجد تخصيص في footer_links → يتغلب على settings
 */
if ($sectionType === 'social' && !empty($links)) {
    foreach ($links as $l) {
        $key = $l['label'] ?? '';
        $url = $l['url'] ?? '';
        if ($key && $url) {
            $socialMap[$key] = $url;
        }
    }
}
?>

<div class="container-fluid py-4">

    <h3 class="mb-2"><?= __('footer.edit_section', 'Edit Footer Section') ?></h3>

    <div class="card mb-4">
        <div class="card-body">
            <form method="POST" action="/admin/footer/update/<?= (int)$section['id'] ?>">
                <?= \Core\System\Csrf::field(); ?>

                <div class="mb-3">
                    <label class="form-label"><?= __('footer.section_title', 'Section Title') ?></label>
                    <input type="text" name="title" class="form-control" required
                           value="<?= htmlspecialchars($section['title']) ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('footer.section_type', 'Section Type') ?></label>
                    <select class="form-select" disabled>
                        <option <?= $sectionType === 'pages' ? 'selected' : '' ?>>Pages</option>
                        <option <?= $sectionType === 'social' ? 'selected' : '' ?>>Social</option>
                        <option <?= $sectionType === 'contact' ? 'selected' : '' ?>>Contact</option>
                    </select>
                </div>

                <button type="submit" class="btn btn-primary"><?= __('actions.save', 'Save') ?></button>
            </form>
        </div>
    </div>

    <!-- PAGES -->
    <?php if ($sectionType === 'pages'): ?>
        <div class="card mb-4">
            <div class="card-body">

                <h5 class="mb-3">
                    <?= __('footer.links', 'Links') ?>
                    <span class="text-muted">(<?= $currentCount ?> / <?= $MAX_ITEMS ?>)</span>
                </h5>

                <?php if (!empty($links)): ?>
                    <table class="table table-bordered align-middle">
                        <thead>
                        <tr>
                            <th><?= __('footer.link_label', 'Label') ?></th>
                            <th><?= __('footer.link_type', 'Type') ?></th>
                            <th><?= __('footer.link_destination', 'Destination') ?></th>
                            <th><?= __('actions.actions', 'Actions') ?></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($links as $link): ?>
                            <tr>
                                <td><?= htmlspecialchars($link['label']) ?></td>
                                <td><?= htmlspecialchars($link['type']) ?></td>
                                <td>
                                    <?= ($link['type'] ?? '') === 'page'
                                        ? htmlspecialchars($pagesList[(int)$link['page_id']]['title'] ?? '')
                                        : htmlspecialchars($link['url'] ?? '') ?>
                                </td>
                                <td>
                                    <a href="/admin/footer/links/delete/<?= (int)$link['id'] ?>"
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('<?= __('actions.confirm_delete', 'Are you sure?') ?>')">
                                        <?= __('actions.delete', 'Delete') ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p class="text-muted"><?= __('footer.no_links', 'No links added yet.') ?></p>
                <?php endif; ?>

                <?php if (!$limitReached): ?>
                    <hr>
                    <form method="POST" action="/admin/footer/<?= (int)$section['id'] ?>/links/store">
                        <?= \Core\System\Csrf::field(); ?>

                        <div class="mb-3">
                            <label class="form-label"><?= __('footer.link_label', 'Label') ?></label>
                            <input type="text" name="label" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('footer.link_type', 'Type') ?></label>
                            <select name="type" id="linkType" class="form-select">
                                <option value="page"><?= __('footer.internal_page', 'Internal Page') ?></option>
                                <option value="custom"><?= __('footer.external_link', 'External Link') ?></option>
                            </select>
                        </div>

                        <div class="mb-3" id="pageField">
                            <label class="form-label"><?= __('footer.link_choose_page', 'Choose a Page') ?></label>
                            <select name="page_id" class="form-select">
                                <?php foreach ($pagesList as $pid => $p): ?>
                                    <option value="<?= (int)$pid ?>"><?= htmlspecialchars($p['title']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3 d-none" id="urlField">
                            <label class="form-label"><?= __('footer.link_url', 'External URL') ?></label>
                            <input type="url" name="url" class="form-control" placeholder="https://">
                        </div>

                        <button type="submit" class="btn btn-success">
                            <?= __('footer.add_link', 'Add Link') ?>
                        </button>
                    </form>
                <?php endif; ?>

            </div>
        </div>
    <?php endif; ?>

    <!-- SOCIAL -->
    <?php if ($sectionType === 'social'): ?>
        <div class="card mb-4">
            <div class="card-body">

                <h5 class="mb-3">
                    <?= __('footer.social_links', 'Social Networks') ?>
                    <span class="text-muted">(<?= $currentCount ?> / <?= $MAX_ITEMS ?>)</span>
                </h5>

                <?php if (!empty($links)): ?>
                    <table class="table table-bordered align-middle">
                        <thead>
                        <tr>
                            <th>Network</th>
                            <th>URL</th>
                            <th><?= __('actions.actions', 'Actions') ?></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($links as $link): ?>
                            <tr>
                                <td><?= ucfirst(htmlspecialchars($link['label'])) ?></td>
                                <td><?= htmlspecialchars($link['url']) ?></td>
                                <td>
                                    <a href="/admin/footer/links/delete/<?= (int)$link['id'] ?>"
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('<?= __('actions.confirm_delete', 'Are you sure?') ?>')">
                                        <?= __('actions.delete', 'Delete') ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p class="text-muted"><?= __('footer.no_social', 'No social networks added yet.') ?></p>
                <?php endif; ?>

                <?php if (!$limitReached): ?>
                    <hr>
                    <form method="POST" action="/admin/footer/<?= (int)$section['id'] ?>/links/store">
                        <?= \Core\System\Csrf::field(); ?>

                        <input type="hidden" name="type" value="social">

                        <div class="mb-3">
                            <label class="form-label">Network</label>
                            <select name="label" id="socialNetworkSelect" class="form-select" required>
                                <?php foreach ($socialNetworks as $key => $name): ?>
                                    <option value="<?= $key ?>"><?= $name ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text">
                                يتم جلب الرابط تلقائيًا من الإعدادات عند الاختيار.
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Profile URL</label>
                            <input type="url" name="url" id="socialUrlInput"
                                   class="form-control" required placeholder="https://">
                        </div>

                        <button type="submit" class="btn btn-success">
                            <?= __('footer.add_social', 'Add Social') ?>
                        </button>
                    </form>
                <?php endif; ?>

            </div>
        </div>

        <script>
        (function () {
            const socialMap = <?= json_encode($socialMap, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
            const select = document.getElementById('socialNetworkSelect');
            const input  = document.getElementById('socialUrlInput');

            function fillUrl() {
                if (!select || !input) return;
                const key = select.value;
                if (socialMap[key]) {
                    input.value = socialMap[key];
                } else {
                    input.value = '';
                }
            }

            if (select) {
                select.addEventListener('change', fillUrl);
                fillUrl();
            }
        })();
        </script>
    <?php endif; ?>

    <!-- CONTACT -->
    <?php if ($sectionType === 'contact'): ?>
        <div class="alert alert-info">
            <?= __('footer.contact_info', 'Contact information is managed from global settings.') ?>
        </div>
    <?php endif; ?>

</div>

<script>
(function () {
    const linkType = document.getElementById('linkType');
    const urlField = document.getElementById('urlField');
    const pageField = document.getElementById('pageField');

    function syncFields() {
        const isPage = linkType && linkType.value === 'page';
        if (urlField) urlField.classList.toggle('d-none', isPage);
        if (pageField) pageField.classList.toggle('d-none', !isPage);
    }

    if (linkType) {
        linkType.addEventListener('change', syncFields);
        syncFields();
    }
})();
</script>

<?php include ROOT_PATH . '/admin/templates/footer.php'; ?>
