<?php
// Get available target sites for WordPress cloning

header('Content-Type: application/json');

require_once('../auto-prepend.php');

// Check if user is authenticated
if (!defined('AUTH_USER')) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

// Note: CSRF protection is handled by session authentication
// The nonce parameter is accepted but not validated as other API endpoints
// rely on AUTH_USER authentication which is checked above

require_once('../libs/mysqlmgmt.php');

try {
    // CRITICAL SECURITY: Validate and sanitize source_site_id parameter
    $sourceSiteId = filter_var($_GET['source_site_id'] ?? '', FILTER_VALIDATE_INT);
    if (!$sourceSiteId || $sourceSiteId <= 0) {
        throw new Exception('Invalid source site ID parameter');
    }

    $mysql = new mysqlmgmt();
    $db = $mysql->getMySQLConnection();
    $db->exec("USE whp");

    $isRoot = AUTH_USER === 'root';

    // Get sites that:
    // 1. Have running containers
    // 2. Don't already have WordPress installed
    // 3. Belong to the current user (or all sites if root)
    // 4. Are not the source site

    if ($isRoot) {
        $stmt = $db->prepare("
            SELECT s.id, s.username, sd.fqdn as primary_fqdn, s.site_name
            FROM sites s
            INNER JOIN site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
            WHERE s.id != ?
              AND s.active = 1
              AND EXISTS (SELECT 1 FROM site_containers sc WHERE sc.site_id = s.id AND sc.status = 'running')
              AND NOT EXISTS (SELECT 1 FROM wordpress_sites ws WHERE ws.container_name = CONCAT(sd.fqdn, '-01'))
            ORDER BY s.username, sd.fqdn
        ");
        $stmt->execute([$sourceSiteId]);
    } else {
        $stmt = $db->prepare("
            SELECT s.id, s.username, sd.fqdn as primary_fqdn, s.site_name
            FROM sites s
            INNER JOIN site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
            WHERE s.id != ?
              AND s.username = ?
              AND s.active = 1
              AND EXISTS (SELECT 1 FROM site_containers sc WHERE sc.site_id = s.id AND sc.status = 'running')
              AND NOT EXISTS (SELECT 1 FROM wordpress_sites ws WHERE ws.container_name = CONCAT(sd.fqdn, '-01'))
            ORDER BY sd.fqdn
        ");
        $stmt->execute([$sourceSiteId, AUTH_USER]);
    }

    $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'sites' => $sites
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>