<?php
include "include/db.php";
include "include/header.php";
$errors = [];
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_landing'])) {
    $landing_name = trim($_POST['landing_name'] ?? '');
    if (empty($landing_name)) $errors[] = "Landing Name is required.";
  
    if (empty($errors)) {
        // Check for duplicate name
        $check_sql = "SELECT COUNT(*) FROM manage_landing WHERE landing_name = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param('s', $landing_name);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        $count = $check_result->fetch_row()[0];
        $check_stmt->close();
        if ($count > 0) {
            $errors[] = "Landing Name '{$landing_name}' already exists. Please choose a unique name.";
        }
    }

    $file_paths = []; // Array to store file paths as JSON
    if (empty($errors)) {
        // Handle multiple file uploads
        if (isset($_FILES['css_files']) && !empty($_FILES['css_files']['name'][0])) {
            $upload_dir = 'upload_design/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            // Section mapping for file names (handle variations like hyphens/underscores)
            $section_map = [
                'css_global' => ['global-styles', 'global', 'css_global'],
                'css_top_offer' => ['top-offer', 'top_offer', 'css_top_offer'],
                'css_hero' => ['hero', 'css_hero'],
                'css_product_selection' => ['product-selection', 'product_selection', 'css_product_selection'],
                'css_offer_stack' => ['offer-stack', 'offer_stack', 'css_offer_stack'],
                'css_problem_solution_benefits' => ['problem-solution-benefits', 'problem_solution_benefits', 'css_problem_solution_benefits'],
                'css_testimonials' => ['testimonials', 'css_testimonials'],
                'css_how_to_use' => ['how-to-use', 'how_to_use', 'css_how_to_use'],
                'css_usage_faq' => ['usage-faq', 'usage_faq', 'css_usage_faq'],
                'css_order_form' => ['order-form', 'order_form', 'css_order_form'],
                'css_final_cta_footer' => ['final-cta-footer', 'final_cta_footer', 'css_final_cta_footer'],
                'css_floating_buttons' => ['floating-buttons', 'floating_buttons', 'css_floating_buttons']
            ];

            $counter = 1;
            foreach ($_FILES['css_files']['name'] as $key => $filename) {
                if ($_FILES['css_files']['error'][$key] === UPLOAD_ERR_OK) {
                    $file_tmp = $_FILES['css_files']['tmp_name'][$key];
                    $file_size = $_FILES['css_files']['size'][$key];
                    $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

                    if (!in_array($file_ext, ['css', 'json'])) {
                        $errors[] = "Only CSS and JSON files are allowed. Skipped: " . $filename;
                        continue;
                    }
                    if ($file_size > 2097152) { // 2MB limit
                        $errors[] = "File size must be less than 2MB. Skipped: " . $filename;
                        continue;
                    }

                    // Generate unique filename
                    $unique_id = uniqid('file_' . time() . '_');
                    $new_filename = $unique_id . '_' . $counter . '_' . $filename;
                    $upload_path = $upload_dir . $new_filename;

                    if (move_uploaded_file($file_tmp, $upload_path)) {
                        // Map to section
                        $matched_section = null;
                        $clean_filename = strtolower(str_replace(['.css', '.json'], '', pathinfo($filename, PATHINFO_FILENAME)));
                        foreach ($section_map as $section => $variants) {
                            if (in_array($clean_filename, $variants)) {
                                $matched_section = $section;
                                break;
                            }
                        }
                        // If no match, use generic key
                        if (!$matched_section) {
                            $matched_section = 'custom_' . $counter;
                        }

                        $file_paths[$matched_section] = $upload_path;
                        $counter++;
                    } else {
                        $errors[] = "Failed to upload: " . $filename;
                    }
                }
            }
        }
    }

    if (empty($errors)) {
        // Insert landing_name and file_paths as JSON
        $file_paths_json = json_encode($file_paths, JSON_UNESCAPED_SLASHES);
        $sql = "INSERT INTO manage_landing (landing_name, file_paths) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param('ss', $landing_name, $file_paths_json);
            if ($stmt->execute()) {
                $success = "Landing Page '{$landing_name}' added successfully! File paths saved: " . htmlspecialchars($file_paths_json) . ". Redirecting...";
                echo "<script>setTimeout(() => location.href='landing_list.php', 2000);</script>";
            } else {
                $errors[] = "DB Insert Error: " . $stmt->error;
                // Clean up uploaded files if DB fails
                foreach ($file_paths as $path) {
                    if (file_exists($path)) unlink($path);
                }
            }
            $stmt->close();
        } else {
            $errors[] = "DB Prepare Error: " . $conn->error;
            // Clean up uploaded files if DB fails
            foreach ($file_paths as $path) {
                if (file_exists($path)) unlink($path);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Landing Page</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; background: #f3f4f6; }
        .content { transition: margin-left 0.3s; }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        .error { background: #FEE2E2; color: #DC2626; padding: 1rem; border-radius: 8px; }
        .success { background: #ECFDF5; color: #10B981; padding: 1rem; border-radius: 8px; text-align: center; font-weight: bold; }
        .file-input-wrapper { position: relative; overflow: hidden; display: inline-block; width: 100%; }
        .file-input-wrapper input[type=file] { position: absolute; left: -9999px; }
        .file-input-label { display: flex; flex-direction: column; align-items: center; padding: 2rem; border: 2px dashed #d1d5db; border-radius: 0.5rem; text-align: center; cursor: pointer; transition: background-color 0.2s; }
        .file-input-label:hover { background-color: #f3f4f6; }
        @media (min-width: 769px) { .content { margin-left: 250px; } }
    </style>
</head>
<body>
<div id="content" class="content p-6 min-h-screen">
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-50">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-xs mx-4">
            <input type="text" placeholder="Search..." class="w-full p-2 rounded-md bg-white text-gray-900">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" class="w-10 h-10 rounded-full">
                <span>Admin</span>
            </div>
        </div>
    </nav>
    <div class="max-w-4xl mx-auto my-8">
        <div class="bg-white p-8 rounded-xl shadow-lg">
            <h2 class="text-3xl font-bold text-center mb-8">Add New Landing Page</h2>
            <?php if ($success): ?>
                <div class="success mb-6"><?php echo $success; ?></div>
            <?php endif; ?>
            <?php if (!empty($errors)): ?>
                <div class="error mb-6">
                    <ul class="list-disc pl-6 space-y-1">
                        <?php foreach ($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
            <?php if (!$success): ?>
            <form method="POST" enctype="multipart/form-data" class="space-y-6">
                <input type="hidden" name="add_landing" value="1">
                <div>
                    <label class="block font-semibold mb-2">Landing Name <span class="text-red-500">*</span></label>
                    <input type="text" name="landing_name" value="<?php echo htmlspecialchars($_POST['landing_name'] ?? ''); ?>"
                           class="w-full p-3 border rounded-lg" required>
                </div>
                <div class="border-t pt-6">
                    <h3 class="text-xl font-bold mb-4">Upload CSS/JSON Files (Multiple, Optional)</h3>
                    <p class="text-gray-600 mb-4">Select multiple CSS/JSON files for sections (e.g., global-styles.json, hero.css). They will be renamed uniquely and paths saved in DB as JSON.</p>
                    <div class="file-input-wrapper">
                        <input type="file" name="css_files[]" accept=".css,.json" multiple id="css_files">
                        <label for="css_files" class="file-input-label">
                            <i class="fas fa-file-code text-4xl text-blue-500 mb-4"></i>
                            <span class="text-lg font-medium">Click to select multiple CSS/JSON files</span>
                            <span class="text-sm text-gray-500 mt-1">Max size: 2MB per file (.css/.json only)</span>
                        </label>
                    </div>
                    <div id="selected-files" class="mt-2 p-2 bg-gray-50 rounded border hidden">
                        <p class="text-sm font-medium mb-1">Selected Files:</p>
                        <ul id="file-list" class="text-sm space-y-1"></ul>
                    </div>
                </div>
              
                <div class="flex gap-4 mt-8">
                    <button type="submit" class="flex-1 bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-3 rounded-lg">
                        Add Landing & Upload Files
                    </button>
                    <a href="landing_list.php" class="flex-1 bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 rounded-lg text-center">
                        Cancel
                    </a>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>
<script>
document.getElementById('css_files').addEventListener('change', function(e) {
    const selectedDiv = document.getElementById('selected-files');
    const fileList = document.getElementById('file-list');
    fileList.innerHTML = '';
    if (e.target.files.length > 0) {
        Array.from(e.target.files).forEach(file => {
            const li = document.createElement('li');
            li.textContent = file.name;
            fileList.appendChild(li);
        });
        selectedDiv.classList.remove('hidden');
    } else {
        selectedDiv.classList.add('hidden');
    }
});
</script>
<?php include "include/footer.php"; $conn->close(); ?>
</body>
</html>