<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1;

// Check if master admin
$isMaster = isset($adminData['is_master']) && $adminData['is_master'];
if (!$isMaster) {
    header('Location: dashboard.php?error=' . urlencode('Access denied. Master admin only.'));
    exit;
}

$db = new Database();
$siteManager = new SiteManager($db);

// Handle AJAX request for getting site data (must be before any HTML output)
if (isset($_GET['get_site']) && is_numeric($_GET['get_site'])) {
    $siteId = (int)$_GET['get_site'];
    $stmt = $db->getConnection()->prepare("SELECT * FROM sites WHERE id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    
    header('Content-Type: application/json');
    if ($site) {
        echo json_encode(['success' => true, 'site' => $site]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Site not found']);
    }
    exit;
}

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'add_site':
                    $stmt = $db->getConnection()->prepare("
                        INSERT INTO sites (site_code, site_name, domain, primary_color, secondary_color, accent_color, background_color, text_color, site_title, site_description, is_active)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $_POST['site_code'],
                        $_POST['site_name'], 
                        $_POST['domain'],
                        $_POST['primary_color'] ?? '#25d366',
                        $_POST['secondary_color'] ?? '#1ba94c',
                        $_POST['accent_color'] ?? '#40e788',
                        $_POST['background_color'] ?? '#0a1a0f',
                        $_POST['text_color'] ?? '#ffffff',
                        $_POST['site_title'],
                        $_POST['site_description'],
                        isset($_POST['is_active']) ? 1 : 0
                    ]);
                    $message = "Site berhasil ditambahkan!";
                    $messageType = "success";
                    
                    // Log activity
                    $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'ADD_SITE', 
                        "Added site: " . $_POST['site_name'], 'master');
                    break;
                    
                case 'update_site':
                    $stmt = $db->getConnection()->prepare("
                        UPDATE sites SET 
                            site_name = ?, domain = ?, primary_color = ?, secondary_color = ?, accent_color = ?, 
                            background_color = ?, text_color = ?, site_title = ?, site_description = ?, 
                            is_active = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $_POST['site_name'],
                        $_POST['domain'],
                        $_POST['primary_color'],
                        $_POST['secondary_color'],
                        $_POST['accent_color'],
                        $_POST['background_color'],
                        $_POST['text_color'],
                        $_POST['site_title'],
                        $_POST['site_description'],
                        isset($_POST['is_active']) ? 1 : 0,
                        $_POST['site_id']
                    ]);
                    $message = "Site berhasil diupdate!";
                    $messageType = "success";
                    
                    // Log activity
                    $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_SITE', 
                        "Updated site: " . $_POST['site_name'], 'master');
                    break;
                    
                case 'delete_site':
                    // Get site info for logging
                    $siteStmt = $db->getConnection()->prepare("SELECT site_name FROM sites WHERE id = ?");
                    $siteStmt->execute([$_POST['site_id']]);
                    $siteInfo = $siteStmt->fetch();
                    
                    $stmt = $db->getConnection()->prepare("DELETE FROM sites WHERE id = ?");
                    $stmt->execute([$_POST['site_id']]);
                    $message = "Site berhasil dihapus!";
                    $messageType = "success";
                    
                    // Log activity
                    $siteName = $siteInfo ? $siteInfo['site_name'] : 'Unknown';
                    $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'DELETE_SITE', 
                        "Deleted site: $siteName", 'master');
                    break;
            }
        }
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// Get all sites
$sites = [];
try {
    $stmt = $db->getConnection()->prepare("SELECT * FROM sites ORDER BY created_at DESC");
    $stmt->execute();
    $sites = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error getting sites: " . $e->getMessage());
}

// Set page variables for template
$pageTitle = 'Kelola Situs';
$pageDescription = 'Manajemen multi-site dan konfigurasi';
$headerActions = '
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addSiteModal">
        <i class="bi bi-plus-circle me-1"></i>
        Tambah Situs
    </button>
';

// Set flash messages
if ($messageType === 'success') {
    $_SESSION['success_message'] = $message;
} elseif ($messageType === 'error') {
    $_SESSION['error_message'] = $message;
}

// Include sidebar template
include 'admin-sidebar-template.php';
?>

<!-- Sites Content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-globe me-2"></i>
                    Daftar Situs
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($sites)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-globe display-4 text-muted"></i>
                    <h5 class="mt-3">Belum ada Situs</h5>
                    <p class="text-muted">Klik tombol "Tambah Situs" untuk menambahkan situs pertama</p>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Site Code</th>
                                <th>Nama Situs</th>
                                <th>Domain</th>
                                <th>Theme Colors</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($sites as $site): ?>
                            <tr>
                                <td>
                                    <span class="badge bg-primary"><?php echo htmlspecialchars($site['site_code']); ?></span>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($site['site_name']); ?></strong>
                                    <br>
                                    <small class="text-muted"><?php echo htmlspecialchars($site['site_title'] ?? ''); ?></small>
                                </td>
                                <td>
                                    <a href="http://<?php echo htmlspecialchars($site['domain']); ?>" target="_blank" class="text-decoration-none">
                                        <?php echo htmlspecialchars($site['domain']); ?>
                                        <i class="bi bi-box-arrow-up-right ms-1"></i>
                                    </a>
                                </td>
                                <td>
                                    <div class="d-flex gap-1">
                                        <span class="badge" style="background-color: <?php echo htmlspecialchars($site['primary_color']); ?>; color: white;">Primary</span>
                                        <span class="badge" style="background-color: <?php echo htmlspecialchars($site['secondary_color']); ?>; color: white;">Secondary</span>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge bg-<?php echo $site['is_active'] ? 'success' : 'danger'; ?>">
                                        <?php echo $site['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <small><?php echo date('d/m/Y', strtotime($site['created_at'])); ?></small>
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-sm btn-outline-primary" 
                                                onclick="editSite(<?php echo $site['id']; ?>)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" 
                                                onclick="deleteSite(<?php echo $site['id']; ?>, '<?php echo htmlspecialchars($site['site_name']); ?>')">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Add Site Modal -->
<div class="modal fade" id="addSiteModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tambah Situs Baru</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_site">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Site Code *</label>
                            <input type="text" class="form-control" name="site_code" required maxlength="10" style="text-transform: uppercase;">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nama Situs *</label>
                            <input type="text" class="form-control" name="site_name" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Domain *</label>
                            <input type="text" class="form-control" name="domain" required placeholder="example.com">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Site Title</label>
                            <input type="text" class="form-control" name="site_title">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Site Description</label>
                        <textarea class="form-control" name="site_description" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="border-bottom pb-2">Theme Colors</h6>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Primary Color</label>
                                <input type="color" class="form-control form-control-color" name="primary_color" value="#25d366">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Secondary Color</label>
                                <input type="color" class="form-control form-control-color" name="secondary_color" value="#1ba94c">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Accent Color</label>
                                <input type="color" class="form-control form-control-color" name="accent_color" value="#40e788">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Background Color</label>
                                <input type="color" class="form-control form-control-color" name="background_color" value="#0a1a0f">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active_add" checked>
                        <label class="form-check-label" for="is_active_add">
                            Active
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Tambah Situs</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Site Modal -->
<div class="modal fade" id="editSiteModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Situs</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="editSiteForm">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_site">
                    <input type="hidden" name="site_id" id="edit_site_id">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Site Code *</label>
                            <input type="text" class="form-control" name="site_code" id="edit_site_code" required maxlength="10" style="text-transform: uppercase;">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nama Situs *</label>
                            <input type="text" class="form-control" name="site_name" id="edit_site_name" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Domain *</label>
                            <input type="text" class="form-control" name="domain" id="edit_domain" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Site Title</label>
                            <input type="text" class="form-control" name="site_title" id="edit_site_title">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Site Description</label>
                        <textarea class="form-control" name="site_description" id="edit_site_description" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="border-bottom pb-2">Theme Colors</h6>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Primary Color</label>
                                <input type="color" class="form-control form-control-color" name="primary_color" id="edit_primary_color">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Secondary Color</label>
                                <input type="color" class="form-control form-control-color" name="secondary_color" id="edit_secondary_color">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Accent Color</label>
                                <input type="color" class="form-control form-control-color" name="accent_color" id="edit_accent_color">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Background Color</label>
                                <input type="color" class="form-control form-control-color" name="background_color" id="edit_background_color">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active">
                        <label class="form-check-label" for="edit_is_active">
                            Active
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Situs</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
// Additional JavaScript for sites
$additionalJS = '
<script>
function editSite(id) {
    // Get site data via AJAX or from existing data
    fetch("sites.php?get_site=" + id)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const site = data.site;
                document.getElementById("edit_site_id").value = site.id;
                document.getElementById("edit_site_code").value = site.site_code;
                document.getElementById("edit_site_name").value = site.site_name;
                document.getElementById("edit_domain").value = site.domain;
                document.getElementById("edit_site_title").value = site.site_title || "";
                document.getElementById("edit_site_description").value = site.site_description || "";
                document.getElementById("edit_primary_color").value = site.primary_color;
                document.getElementById("edit_secondary_color").value = site.secondary_color;
                document.getElementById("edit_accent_color").value = site.accent_color;
                document.getElementById("edit_background_color").value = site.background_color;
                document.getElementById("edit_is_active").checked = site.is_active == 1;
                
                new bootstrap.Modal(document.getElementById("editSiteModal")).show();
            } else {
                showNotification("Error loading site data", "danger");
            }
        })
        .catch(error => {
            console.error("Error:", error);
            showNotification("Error loading site data", "danger");
        });
}

function deleteSite(id, name) {
    if (confirm("Apakah Anda yakin ingin menghapus situs: " + name + "?")) {
        const form = document.createElement("form");
        form.method = "POST";
        form.innerHTML = `
            <input type="hidden" name="action" value="delete_site">
            <input type="hidden" name="site_id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Auto uppercase site code
document.addEventListener("DOMContentLoaded", function() {
    const codeInputs = document.querySelectorAll("input[name=site_code]");
    codeInputs.forEach(input => {
        input.addEventListener("input", function() {
            this.value = this.value.toUpperCase();
        });
    });
});
</script>';

include 'admin-sidebar-footer.php';
?>