<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin', 'clinic_admin']);
require DENTAL_ROOT . '/app/layout.php';

function website_manager_safe_redirect(string $extra = ''): never
{
    header('Location: website_pages.php' . $extra);
    exit;
}

function website_manager_nav_url_valid(string $url): bool
{
    if ($url === '') return false;
    if (preg_match('/\s/', $url)) return false;
    if (preg_match('/^(javascript|data):/i', $url)) return false;
    return function_exists('public_website_safe_url') ? public_website_safe_url($url) : (bool) preg_match('/^(https?:\/\/|mailto:|tel:|[A-Za-z0-9_\-.\/]+(?:\.php)?(?:[?#][^\s]*)?|#[A-Za-z0-9_-]+)$/', $url);
}

function website_manager_page_image_upload(string $field): ?string
{
    if (empty($_FILES[$field]) || ($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        return null;
    }
    $file = $_FILES[$field];
    if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        throw new RuntimeException('The ' . str_replace('_', ' ', $field) . ' upload failed.');
    }
    if ((int)($file['size'] ?? 0) > 4 * 1024 * 1024) {
        throw new RuntimeException('Page images must be 4 MB or smaller.');
    }
    $tmp = (string)($file['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        throw new RuntimeException('The uploaded image could not be verified.');
    }
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string)$finfo->file($tmp);
    $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp'];
    if (!isset($allowed[$mime])) {
        throw new RuntimeException('Use a JPG, PNG, or WebP image for public pages.');
    }
    $size = @getimagesize($tmp);
    if (!is_array($size) || (int)($size[0] ?? 0) < 1 || (int)($size[1] ?? 0) < 1) {
        throw new RuntimeException('The uploaded file is not a valid image.');
    }
    if ((int)$size[0] > 5000 || (int)$size[1] > 5000) {
        throw new RuntimeException('Page images must be 5000 px or smaller on each side.');
    }
    $dir = DENTAL_ROOT . '/public/uploads/website-pages';
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
    $htaccess = $dir . '/.htaccess';
    if (!is_file($htaccess)) {
        file_put_contents($htaccess, "Options -Indexes\n\n<FilesMatch \"\\.(?:php[0-9]?|phtml|phar|cgi|pl|py|sh|shtml)$\">\n  <IfModule mod_authz_core.c>\n    Require all denied\n  </IfModule>\n  <IfModule !mod_authz_core.c>\n    Order allow,deny\n    Deny from all\n  </IfModule>\n</FilesMatch>\n");
    }
    $name = $field . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(5)) . '.' . $allowed[$mime];
    if (!move_uploaded_file($tmp, $dir . '/' . $name)) {
        throw new RuntimeException('The page image could not be saved. Check public/uploads permissions.');
    }
    $path = 'public/uploads/website-pages/' . $name;
    if (function_exists('public_website_register_media')) {
        public_website_register_media($path, ucfirst(str_replace('_', ' ', $field)), '', 'page_upload');
    }
    return $path;
}

$pages = public_website_pages();
$customLinks = public_website_custom_nav_links();
$mediaItems = function_exists('public_website_media_items') ? public_website_media_items() : [];
$editId = (string) ($_GET['edit'] ?? '');
$editingPage = null;
foreach ($pages as $page) {
    if ($page['id'] === $editId) {
        $editingPage = $page;
        break;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string) ($_POST['action'] ?? '');

        if ($action === 'save_page') {
            $id = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) ($_POST['id'] ?? ''));
            $title = trim((string) ($_POST['title'] ?? ''));
            if ($title === '') throw new RuntimeException('Enter a page title.');
            $slug = public_website_slugify((string) ($_POST['slug'] ?? $title));
            if (!preg_match('/^[a-z0-9][a-z0-9-]{1,79}$/', $slug)) throw new RuntimeException('Use a simple URL slug such as about-us or privacy-policy.');
            if (function_exists('public_website_slug_reserved') && public_website_slug_reserved($slug)) throw new RuntimeException('This slug is reserved by the system. Use a public page slug such as about-the-clinic or service-guide.');
            $existingIndex = null;
            $existingRecord = [];
            foreach ($pages as $index => $page) {
                if ($page['slug'] === $slug && $page['id'] !== $id) throw new RuntimeException('Another page already uses this URL slug.');
                if ($id !== '' && $page['id'] === $id) {
                    $existingIndex = $index;
                    $existingRecord = $page;
                }
            }
            if ($id === '') $id = 'pg_' . bin2hex(random_bytes(6));

            $layoutStyle = (string)($_POST['layout_style'] ?? 'split');
            if (!in_array($layoutStyle, ['split', 'centered', 'poster', 'cards'], true)) $layoutStyle = 'split';
            $themeStyle = (string)($_POST['theme_style'] ?? 'clinic');
            if (!in_array($themeStyle, ['clinic', 'soft', 'premium', 'minimal'], true)) $themeStyle = 'clinic';
            $imagePosition = (string)($_POST['image_position'] ?? 'right');
            if (!in_array($imagePosition, ['right', 'left', 'top', 'background'], true)) $imagePosition = 'right';

            $heroImage = (string)($existingRecord['hero_image'] ?? '');
            $contentImage = (string)($existingRecord['content_image'] ?? '');
            if (!empty($_POST['remove_hero_image'])) $heroImage = '';
            if (!empty($_POST['remove_content_image'])) $contentImage = '';
            $selectedHeroMedia = function_exists('public_website_media_path_from_id') ? public_website_media_path_from_id((string)($_POST['hero_image_media'] ?? '')) : '';
            $selectedContentMedia = function_exists('public_website_media_path_from_id') ? public_website_media_path_from_id((string)($_POST['content_image_media'] ?? '')) : '';
            if ($selectedHeroMedia !== '') $heroImage = $selectedHeroMedia;
            if ($selectedContentMedia !== '') $contentImage = $selectedContentMedia;
            $newHero = website_manager_page_image_upload('hero_image');
            $newContent = website_manager_page_image_upload('content_image');
            if ($newHero !== null) $heroImage = $newHero;
            if ($newContent !== null) $contentImage = $newContent;

            $ctaLabel = substr(trim((string)($_POST['cta_label'] ?? '')), 0, 80);
            $ctaUrl = trim((string)($_POST['cta_url'] ?? ''));
            if ($ctaUrl !== '' && !website_manager_nav_url_valid($ctaUrl)) {
                throw new RuntimeException('Enter a safe button URL, such as appointment-new.php, index.php#contact, mailto:, tel:, or https://.');
            }

            $record = [
                'id' => $id,
                'title' => substr($title, 0, 160),
                'slug' => $slug,
                'nav_label' => substr(trim((string) ($_POST['nav_label'] ?? $title)), 0, 80),
                'nav_order' => max(1, min(999, (int) ($_POST['nav_order'] ?? 60))),
                'status' => ((string) ($_POST['status'] ?? 'draft')) === 'published' ? 'published' : 'draft',
                'show_in_nav' => !empty($_POST['show_in_nav']) ? 1 : 0,
                'excerpt' => substr(trim((string) ($_POST['excerpt'] ?? '')), 0, 360),
                'content' => substr(trim((string) ($_POST['content'] ?? '')), 0, 30000),
                'layout_style' => $layoutStyle,
                'theme_style' => $themeStyle,
                'image_position' => $imagePosition,
                'hero_image' => $heroImage,
                'hero_image_alt' => substr(trim((string)($_POST['hero_image_alt'] ?? $title)), 0, 160),
                'content_image' => $contentImage,
                'content_image_alt' => substr(trim((string)($_POST['content_image_alt'] ?? $title)), 0, 160),
                'cta_label' => $ctaLabel,
                'cta_url' => $ctaUrl,
                'feature_cards' => substr(trim((string)($_POST['feature_cards'] ?? '')), 0, 4000),
                'updated_at' => date('c'),
            ];
            if ($existingIndex === null) $pages[] = $record; else $pages[$existingIndex] = $record;
            public_website_save_pages($pages);
            audit('public_website_page_saved', 'website_page', $id, ['title' => $record['title'], 'slug' => $record['slug'], 'status' => $record['status'], 'layout' => $record['layout_style'], 'hero_image' => $record['hero_image'] !== '']);
            flash('success', 'Public webpage saved. Images and design settings are now applied.');
            website_manager_safe_redirect('?edit=' . rawurlencode($id));
        }

        if ($action === 'delete_page') {
            $id = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) ($_POST['id'] ?? ''));
            $pages = array_values(array_filter($pages, static fn(array $page): bool => $page['id'] !== $id));
            public_website_save_pages($pages);
            audit('public_website_page_deleted', 'website_page', $id);
            flash('success', 'Public webpage deleted.');
            website_manager_safe_redirect();
        }

        if ($action === 'save_nav_link') {
            $id = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) ($_POST['id'] ?? ''));
            $label = substr(trim((string) ($_POST['label'] ?? '')), 0, 80);
            $url = trim((string) ($_POST['url'] ?? ''));
            if ($label === '') throw new RuntimeException('Enter a navigation label.');
            if (!website_manager_nav_url_valid($url)) throw new RuntimeException('Enter a safe navigation URL.');
            $existingIndex = null;
            foreach ($customLinks as $index => $link) {
                if ($id !== '' && $link['id'] === $id) $existingIndex = $index;
            }
            if ($id === '') $id = 'nav_' . bin2hex(random_bytes(6));
            $record = [
                'id' => $id,
                'label' => $label,
                'url' => $url,
                'nav_order' => max(1, min(999, (int) ($_POST['nav_order'] ?? 90))),
                'is_active' => !empty($_POST['is_active']) ? 1 : 0,
            ];
            if ($existingIndex === null) $customLinks[] = $record; else $customLinks[$existingIndex] = $record;
            public_website_save_custom_nav_links($customLinks);
            audit('public_navigation_link_saved', 'website_nav', $id, $record);
            flash('success', 'Navigation link saved.');
            website_manager_safe_redirect('#navigation-links');
        }

        if ($action === 'delete_nav_link') {
            $id = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) ($_POST['id'] ?? ''));
            $customLinks = array_values(array_filter($customLinks, static fn(array $link): bool => $link['id'] !== $id));
            public_website_save_custom_nav_links($customLinks);
            audit('public_navigation_link_deleted', 'website_nav', $id);
            flash('success', 'Navigation link deleted.');
            website_manager_safe_redirect('#navigation-links');
        }

        throw new RuntimeException('Unknown website action.');
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
        website_manager_safe_redirect($editId ? '?edit=' . rawurlencode($editId) : '');
    }
}

$blankPage = [
    'id' => '', 'title' => '', 'slug' => '', 'nav_label' => '', 'nav_order' => 60,
    'status' => 'draft', 'show_in_nav' => 1, 'excerpt' => '',
    'content' => "Write the page content here.\n\nUse short paragraphs. Lines starting with ## become section headings.\n\n- Use dash lines for bullet lists.",
    'layout_style' => 'split', 'theme_style' => 'clinic', 'image_position' => 'right',
    'hero_image' => '', 'hero_image_alt' => '', 'content_image' => '', 'content_image_alt' => '',
    'cta_label' => 'Book an Appointment', 'cta_url' => 'appointment-new.php',
    'feature_cards' => "Convenient visits|Request appointments online and let the clinic confirm the final schedule.\nSecure records|Patient and treatment records stay inside protected clinic access.\nFriendly support|Contact the clinic for urgent concerns or special instructions.",
];
$formPage = array_merge($blankPage, $editingPage ?: []);

render_header('Pages & Navigation');
?>
<div class="tabs"><a href="settings.php">Landing Page Editor</a><a class="active">Pages &amp; Navigation</a><a href="website_media.php">Media Library</a><a href="branding.php">Branding &amp; Identity</a><a href="index.php" target="_blank" rel="noopener">Preview Public Website</a></div>
<section class="website-builder-intro card">
    <div><span class="eyebrow">Page designer</span><h2>Build public pages with images, layout, buttons, and cards</h2><p>Use this for About, promos, branches, FAQs, services, policies, landing sections, or buyer information pages without editing PHP.</p></div>
    <a class="btn ghost" href="website_pages.php">Create Blank Page</a>
</section>
<section class="grid two website-page-manager website-page-designer">
    <form method="post" enctype="multipart/form-data" class="card form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="save_page">
        <input type="hidden" name="id" value="<?= e((string) $formPage['id']) ?>">
        <h2 class="wide"><?= $formPage['id'] ? 'Edit public webpage' : 'Add public webpage' ?></h2>
        <label>Page title<input name="title" required maxlength="160" value="<?= e((string) $formPage['title']) ?>"></label>
        <label>URL slug<input name="slug" maxlength="80" placeholder="about-us" value="<?= e((string) $formPage['slug']) ?>"><small>Example: <code>about-us</code> becomes <code>website-page.php?slug=about-us</code>.</small></label>
        <label>Navigation label<input name="nav_label" maxlength="80" value="<?= e((string) $formPage['nav_label']) ?>"></label>
        <label>Navigation order<input type="number" name="nav_order" min="1" max="999" value="<?= e((string) $formPage['nav_order']) ?>"></label>
        <label>Status<select name="status"><option value="draft" <?= $formPage['status'] === 'draft' ? 'selected' : '' ?>>Draft</option><option value="published" <?= $formPage['status'] === 'published' ? 'selected' : '' ?>>Published</option></select></label>
        <label class="check-label"><input type="checkbox" name="show_in_nav" value="1" <?= !empty($formPage['show_in_nav']) ? 'checked' : '' ?>><span>Show this page in the public navigation</span></label>
        <label class="wide">Short description / SEO excerpt<textarea name="excerpt" rows="3"><?= e((string) $formPage['excerpt']) ?></textarea></label>

        <h3 class="wide form-section-title">Design</h3>
        <label>Page layout<select name="layout_style"><option value="split" <?= $formPage['layout_style'] === 'split' ? 'selected' : '' ?>>Split hero with image</option><option value="centered" <?= $formPage['layout_style'] === 'centered' ? 'selected' : '' ?>>Centered article</option><option value="poster" <?= $formPage['layout_style'] === 'poster' ? 'selected' : '' ?>>Large poster image</option><option value="cards" <?= $formPage['layout_style'] === 'cards' ? 'selected' : '' ?>>Cards / feature page</option></select></label>
        <label>Color mood<select name="theme_style"><option value="clinic" <?= $formPage['theme_style'] === 'clinic' ? 'selected' : '' ?>>Clinic brand</option><option value="soft" <?= $formPage['theme_style'] === 'soft' ? 'selected' : '' ?>>Soft light</option><option value="premium" <?= $formPage['theme_style'] === 'premium' ? 'selected' : '' ?>>Premium dark</option><option value="minimal" <?= $formPage['theme_style'] === 'minimal' ? 'selected' : '' ?>>Minimal white</option></select></label>
        <label>Image position<select name="image_position"><option value="right" <?= $formPage['image_position'] === 'right' ? 'selected' : '' ?>>Right side</option><option value="left" <?= $formPage['image_position'] === 'left' ? 'selected' : '' ?>>Left side</option><option value="top" <?= $formPage['image_position'] === 'top' ? 'selected' : '' ?>>Top banner</option><option value="background" <?= $formPage['image_position'] === 'background' ? 'selected' : '' ?>>Hero background</option></select></label>
        <label>Call-to-action label<input name="cta_label" maxlength="80" value="<?= e((string) $formPage['cta_label']) ?>" placeholder="Book an Appointment"></label>
        <label class="wide">Call-to-action URL<input name="cta_url" maxlength="240" value="<?= e((string) $formPage['cta_url']) ?>" placeholder="appointment-new.php or index.php#contact"><small>Safe links only: local page, anchor, mailto, tel, or https.</small></label>

        <h3 class="wide form-section-title">Images</h3>
        <label>Hero image<input type="file" name="hero_image" accept="image/png,image/jpeg,image/webp"><small>JPG, PNG, or WebP. Maximum 4 MB.</small></label>
        <label>Or choose from Media Library<select name="hero_image_media"><option value="">Keep current / none</option><?php foreach ($mediaItems as $media): ?><option value="<?= e((string)$media['id']) ?>"><?= e((string)$media['label']) ?></option><?php endforeach; ?></select><small><a href="website_media.php">Open Media Library</a></small></label>
        <label>Hero image alt text<input name="hero_image_alt" maxlength="160" value="<?= e((string) $formPage['hero_image_alt']) ?>" placeholder="Describe the image"></label>
        <?php if (!empty($formPage['hero_image'])): ?><div class="wide page-image-current"><img src="<?= e((string) $formPage['hero_image']) ?>" alt=""><label class="check-label"><input type="checkbox" name="remove_hero_image" value="1"><span>Remove current hero image</span></label><small><?= e((string) $formPage['hero_image']) ?></small></div><?php endif; ?>
        <label>Content image<input type="file" name="content_image" accept="image/png,image/jpeg,image/webp"><small>Optional second image shown beside or inside the article.</small></label>
        <label>Or choose content image<select name="content_image_media"><option value="">Keep current / none</option><?php foreach ($mediaItems as $media): ?><option value="<?= e((string)$media['id']) ?>"><?= e((string)$media['label']) ?></option><?php endforeach; ?></select></label>
        <label>Content image alt text<input name="content_image_alt" maxlength="160" value="<?= e((string) $formPage['content_image_alt']) ?>"></label>
        <?php if (!empty($formPage['content_image'])): ?><div class="wide page-image-current"><img src="<?= e((string) $formPage['content_image']) ?>" alt=""><label class="check-label"><input type="checkbox" name="remove_content_image" value="1"><span>Remove current content image</span></label><small><?= e((string) $formPage['content_image']) ?></small></div><?php endif; ?>

        <h3 class="wide form-section-title">Page body</h3>
        <label class="wide">Page content <small>Use blank lines for paragraphs, <code>##</code> for section headings, <code>###</code> for small headings, and dash lines for bullets.</small><textarea name="content" rows="16" required><?= e((string) $formPage['content']) ?></textarea></label>
        <label class="wide">Feature cards <small>One card per line using <code>Title|Description</code>. These appear on cards-style pages and below the article on other layouts.</small><textarea name="feature_cards" rows="5"><?= e((string) $formPage['feature_cards']) ?></textarea></label>
        <div class="wide settings-actions"><button class="btn primary" type="submit">Save Webpage Design</button><?php if ($formPage['id']): ?><a class="btn ghost" target="_blank" rel="noopener" href="website-page.php?preview=1&id=<?= e(rawurlencode((string) $formPage['id'])) ?>">Preview Page</a><a class="btn ghost" href="website_pages.php">Add New Page</a><?php endif; ?></div>
    </form>

    <div class="card table-wrap website-page-list-card">
        <div class="card-head"><div><h2>Public webpages</h2><p>Create branded pages with images, layout, cards, and public navigation placement.</p></div></div>
        <table><thead><tr><th>Page</th><th>Status</th><th>Design</th><th>Actions</th></tr></thead><tbody>
        <?php foreach ($pages as $page): ?>
            <tr>
                <td><strong><?= e((string) $page['title']) ?></strong><br><small>website-page.php?slug=<?= e((string) $page['slug']) ?></small></td>
                <td><span class="badge <?= $page['status'] === 'published' ? 'request-status submitted' : 'request-status needs_verification' ?>"><?= e(ucfirst((string) $page['status'])) ?></span><br><small><?= !empty($page['show_in_nav']) ? 'Shown in nav' : 'Hidden from nav' ?> · Order <?= e((string) $page['nav_order']) ?></small></td>
                <td><small><?= e(ucfirst((string)($page['layout_style'] ?? 'split'))) ?> · <?= e(ucfirst((string)($page['theme_style'] ?? 'clinic'))) ?><?= !empty($page['hero_image']) ? ' · Image' : '' ?></small></td>
                <td><a class="btn ghost" href="website_pages.php?edit=<?= e(rawurlencode((string) $page['id'])) ?>">Edit</a> <a class="btn ghost" target="_blank" rel="noopener" href="website-page.php?preview=1&id=<?= e(rawurlencode((string) $page['id'])) ?>">Preview</a> <form method="post" class="inline-form" onsubmit="return confirm('Delete this public webpage?')"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="delete_page"><input type="hidden" name="id" value="<?= e((string) $page['id']) ?>"><button class="btn danger" type="submit">Delete</button></form></td>
            </tr>
        <?php endforeach; if (!$pages): ?><tr><td colspan="4" class="empty-cell">No custom public pages yet.</td></tr><?php endif; ?>
        </tbody></table>
    </div>
</section>

<section id="navigation-links" class="grid two">
    <form method="post" class="card form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="save_nav_link">
        <h2 class="wide">Add custom navigation link</h2>
        <label>Label<input name="label" maxlength="80" placeholder="Promos"></label>
        <label>URL<input name="url" placeholder="index.php#services or https://example.com"></label>
        <label>Order<input type="number" name="nav_order" min="1" max="999" value="90"></label>
        <label class="check-label"><input type="checkbox" name="is_active" value="1" checked><span>Show in public navigation</span></label>
        <button class="btn primary wide" type="submit">Save Navigation Link</button>
    </form>
    <div class="card table-wrap">
        <h2>Custom navigation links</h2>
        <table><thead><tr><th>Label</th><th>URL</th><th>Order</th><th></th></tr></thead><tbody>
        <?php foreach ($customLinks as $link): ?>
            <tr><td><strong><?= e((string) $link['label']) ?></strong><br><small><?= !empty($link['is_active']) ? 'Shown' : 'Hidden' ?></small></td><td><?= e((string) $link['url']) ?></td><td><?= e((string) $link['nav_order']) ?></td><td><form method="post" class="inline-form" onsubmit="return confirm('Delete this navigation link?')"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="delete_nav_link"><input type="hidden" name="id" value="<?= e((string) $link['id']) ?>"><button class="btn danger" type="submit">Delete</button></form></td></tr>
        <?php endforeach; if (!$customLinks): ?><tr><td colspan="4" class="empty-cell">No custom navigation links yet.</td></tr><?php endif; ?>
        </tbody></table>
    </div>
</section>
<?php render_footer();
