<?php
// Permission checking is handled by the permission system in auto-prepend.php

require_once('/docker/whp/web/libs/mysqlmgmt.php');

$message = '';
$message_type = '';
$is_root = (defined('AUTH_USER') && AUTH_USER === 'root');

// Initialize database connection
$MySQLMgmt = new mysqlmgmt();
$db = $MySQLMgmt->getMySQLConnection();

if (!$db) {
    $message = 'Database connection failed';
    $message_type = 'danger';
}

// Delete is handled via the API endpoint: /api/site-builder.php?action=delete

// Fetch sites with domain info and site-builder project status
$sites = [];
if ($db) {
    try {
        // Check if site_builder_projects table exists
        $table_exists = false;
        try {
            $db->query("SELECT 1 FROM whp.site_builder_projects LIMIT 1");
            $table_exists = true;
        } catch (PDOException $e) {
            // Table does not exist
        }

        if ($is_root) {
            if ($table_exists) {
                $stmt = $db->query("
                    SELECT s.id AS site_id, s.site_name, s.username, s.active,
                           COALESCE(sd.fqdn, d.domain_name) AS domain,
                           sbp.id AS project_id, sbp.updated_at AS project_updated_at
                    FROM whp.sites s
                    JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                    JOIN whp.domains d ON sd.domain_id = d.id
                    LEFT JOIN whp.site_builder_projects sbp ON s.id = sbp.site_id
                    ORDER BY s.username, domain
                ");
            } else {
                $stmt = $db->query("
                    SELECT s.id AS site_id, s.site_name, s.username, s.active,
                           COALESCE(sd.fqdn, d.domain_name) AS domain,
                           NULL AS project_id, NULL AS project_updated_at
                    FROM whp.sites s
                    JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                    JOIN whp.domains d ON sd.domain_id = d.id
                    ORDER BY s.username, domain
                ");
            }
        } else {
            if ($table_exists) {
                $stmt = $db->prepare("
                    SELECT s.id AS site_id, s.site_name, s.username, s.active,
                           COALESCE(sd.fqdn, d.domain_name) AS domain,
                           sbp.id AS project_id, sbp.updated_at AS project_updated_at
                    FROM whp.sites s
                    JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                    JOIN whp.domains d ON sd.domain_id = d.id
                    LEFT JOIN whp.site_builder_projects sbp ON s.id = sbp.site_id
                    WHERE s.username = ?
                    ORDER BY domain
                ");
                $stmt->execute([AUTH_USER]);
            } else {
                $stmt = $db->prepare("
                    SELECT s.id AS site_id, s.site_name, s.username, s.active,
                           COALESCE(sd.fqdn, d.domain_name) AS domain,
                           NULL AS project_id, NULL AS project_updated_at
                    FROM whp.sites s
                    JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                    JOIN whp.domains d ON sd.domain_id = d.id
                    WHERE s.username = ?
                    ORDER BY domain
                ");
                $stmt->execute([AUTH_USER]);
            }
        }

        $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $message = 'Error loading sites: ' . $e->getMessage();
        $message_type = 'danger';
    }
}
?>

<div class="container-fluid">
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
            <i class="fa fa-<?php echo $message_type === 'danger' ? 'exclamation-triangle' : 'check-circle'; ?> me-2"></i>
            <strong><?php echo $message_type === 'danger' ? 'Error:' : 'Success:'; ?></strong>
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div id="site-builder-alert" class="d-none"></div>

    <!-- Beta Banner -->
    <div class="alert alert-info d-flex align-items-center mb-4" role="alert" style="border-left: 4px solid #0dcaf0;">
        <i class="fa fa-flask fa-lg me-3"></i>
        <div>
            <strong>BETA</strong> &mdash; Site Builder is in beta. Some features are still being refined.
            We'd love your feedback!
            <a href="https://secure.anhonesthost.com/submitticket.php?step=2&amp;deptid=2" target="_blank" class="alert-link ms-1">Submit feedback <i class="fa fa-external-link"></i></a>
        </div>
    </div>

    <!-- Introduction -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="d-flex align-items-start">
                <div class="flex-grow-1">
                    <h5 class="card-title mb-2"><i class="fa fa-paint-brush me-2"></i>Visual Site Builder</h5>
                    <p class="mb-2">Build your website visually with our drag-and-drop editor. Choose from pre-designed templates or start from scratch &mdash; no coding required. Simply select a site below to get started.</p>
                    <ul class="text-muted small mb-2" style="columns: 2; column-gap: 2rem; list-style: none; padding-left: 0;">
                        <li><i class="fa fa-th-large me-1"></i> 50+ drag-and-drop content blocks</li>
                        <li><i class="fa fa-file-o me-1"></i> Multi-page site support with header &amp; footer</li>
                        <li><i class="fa fa-picture-o me-1"></i> Image and video uploads</li>
                        <li><i class="fa fa-mobile me-1"></i> Mobile-responsive preview</li>
                        <li><i class="fa fa-columns me-1"></i> 16 ready-made templates</li>
                        <li><i class="fa fa-code me-1"></i> Custom head code injection</li>
                        <li><i class="fa fa-save me-1"></i> Save drafts &amp; publish when ready</li>
                        <li><i class="fa fa-eyedropper me-1"></i> Full-spectrum color &amp; gradient controls</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <?php if (empty($sites)): ?>
        <!-- Empty state -->
        <div class="card">
            <div class="card-body">
                <div class="text-center py-5">
                    <i class="fa fa-paint-brush fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">You don't have any sites yet.</h5>
                    <p class="text-muted">Create a site first, then come back to build it visually.</p>
                    <a href="index.php?page=sites" class="btn btn-primary">
                        <i class="fa fa-plus me-2"></i>Create a Site
                    </a>
                </div>
            </div>
        </div>
    <?php else: ?>
        <!-- Site card grid -->
        <div class="row g-4">
            <?php foreach ($sites as $site): ?>
                <div class="col-sm-6 col-lg-4 col-xl-3" id="site-card-<?php echo intval($site['site_id']); ?>">
                    <div class="card h-100">
                        <div class="card-body d-flex flex-column">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h5 class="card-title mb-0 text-break">
                                    <?php echo htmlspecialchars($site['domain']); ?>
                                </h5>
                                <?php if ($site['active']): ?>
                                    <span class="badge bg-success ms-2">Active</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary ms-2">Inactive</span>
                                <?php endif; ?>
                            </div>

                            <?php if ($is_root): ?>
                                <small class="text-muted mb-2">
                                    <i class="fa fa-user me-1"></i><?php echo htmlspecialchars($site['username']); ?>
                                </small>
                            <?php endif; ?>

                            <p class="card-text text-muted small mb-3">
                                <?php if (!empty($site['site_name'])): ?>
                                    <?php echo htmlspecialchars($site['site_name']); ?>
                                <?php else: ?>
                                    &nbsp;
                                <?php endif; ?>
                            </p>

                            <div class="mt-auto">
                                <?php if ($site['project_id']): ?>
                                    <p class="text-muted small mb-2">
                                        <i class="fa fa-clock-o me-1"></i>Last edited:
                                        <?php echo whp_local_time($site['project_updated_at'], 'M j, Y g:ia'); ?>
                                    </p>
                                    <div class="d-flex gap-2">
                                        <a href="site-builder/?site_id=<?php echo intval($site['site_id']); ?>"
                                           class="btn btn-primary btn-sm flex-grow-1">
                                            <i class="fa fa-pencil me-2"></i>Edit Site
                                        </a>
                                        <button type="button"
                                                class="btn btn-outline-danger btn-sm"
                                                onclick="deleteProject(<?php echo intval($site['site_id']); ?>, '<?php echo htmlspecialchars(addslashes($site['domain']), ENT_QUOTES); ?>')"
                                                title="Delete project">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </div>
                                <?php else: ?>
                                    <a href="site-builder/?site_id=<?php echo intval($site['site_id']); ?>"
                                       class="btn btn-success btn-sm w-100">
                                        <i class="fa fa-magic me-2"></i>Build Site
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteProjectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    <i class="fa fa-exclamation-triangle text-danger"></i> Delete Site Builder Project
                </h4>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete the site builder project for <strong id="deleteProjectDomain"></strong>?</p>
                <p class="text-muted small">This will remove the visual builder data for this site. The site itself will not be affected.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn" onclick="confirmDelete()">
                    <i class="fa fa-trash me-2"></i>Delete Project
                </button>
            </div>
        </div>
    </div>
</div>

<script>
const csrfToken = '<?php echo get_csrf_token(); ?>';
let deleteSiteId = null;

function deleteProject(siteId, domain) {
    deleteSiteId = siteId;
    document.getElementById('deleteProjectDomain').textContent = domain;
    const modal = new bootstrap.Modal(document.getElementById('deleteProjectModal'));
    modal.show();
}

function confirmDelete() {
    if (!deleteSiteId) return;

    const btn = document.getElementById('confirmDeleteBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin me-2"></i>Deleting...';

    fetch('/api/site-builder.php?action=delete&site_id=' + deleteSiteId, {
        method: 'POST',
        headers: {
            'X-CSRF-Token': csrfToken
        }
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        var modal = bootstrap.Modal.getInstance(document.getElementById('deleteProjectModal'));
        modal.hide();

        btn.disabled = false;
        btn.textContent = '';
        var icon = document.createElement('i');
        icon.className = 'fa fa-trash me-2';
        btn.appendChild(icon);
        btn.appendChild(document.createTextNode('Delete Project'));

        if (data.success) {
            showAlert(data.message || 'Project deleted successfully', 'success');
            // Reload page to reflect changes
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showAlert(data.error || data.message || 'Failed to delete project', 'danger');
        }
    })
    .catch(function(error) {
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteProjectModal'));
        modal.hide();

        btn.disabled = false;
        btn.innerHTML = '<i class="fa fa-trash me-2"></i>Delete Project';

        showAlert('Error: ' + error.message, 'danger');
    });
}

function showAlert(message, type) {
    const alertDiv = document.getElementById('site-builder-alert');
    const icon = type === 'success' ? 'check-circle' : 'exclamation-triangle';
    const label = type === 'success' ? 'Success:' : 'Error:';
    alertDiv.className = 'alert alert-' + type + ' alert-dismissible fade show';
    alertDiv.innerHTML = '<i class="fa fa-' + icon + ' me-2"></i><strong>' + label + '</strong> ' +
        message + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
}
</script>
