<?php
/**
 * ========================================================
 * PHP LOGIC SECTION: Database Fetch, Form Handling, Validation, Image Upload, DB Save
 * ========================================================
 * This section handles all server-side PHP logic.
 * Includes: DB connection, fetching current data, POST processing, validation,
 * image uploads, and database insert/update.
 * UPDATE: Added floating_buttons_json for dynamic floating buttons (unlimited, with number/icon, image, link).
 * UPDATE: Added support for ?id=GET parameter to fetch/edit specific landing page by ID.
 * If ID provided but no row, treat as new (INSERT). Refetch uses ID after save.
 * Added missing $floating_whatsapp_link and $floating_call_link for DB compat (deprecated).
 * UPDATE: HTML sections modularized into sections/ folder for better organization.
 */
// Include required files
include "include/db.php";
include "include/header.php";
// Initialize variables
$errors = [];
$success = '';
// Define all sections for active status handling
$all_sections = [
    'top_offer', 'hero', 'products', 'offer_stack', 'problem', 'solution', 'benefits',
    'video_testimonials', 'image_testimonials', 'how_to_use', 'usage_guide', 'faq',
    'order_form', 'final_cta', 'footer', 'floating_buttons'
];
// GET ID for specific landing page
$landing_id = isset($_GET['id']) && is_numeric($_GET['id']) ? (int)$_GET['id'] : null;
// FETCH CURRENT DATA
$landing_result = null;
$landing = [];
if ($landing_id) {
    // Fetch specific by ID
    $stmt = $conn->prepare("SELECT * FROM manage_landing WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $landing_id);
    $stmt->execute();
    $landing_result = $stmt->get_result();
    $stmt->close();
} else {
    // Fallback to first (for legacy single landing)
    $landing_result = $conn->query("SELECT * FROM manage_landing LIMIT 1");
}
if ($landing_result && $landing_result->num_rows > 0) {
    $landing = $landing_result->fetch_assoc();
    $products = json_decode($landing['products_json'] ?? '[]', true) ?: [];
    $offer_items = json_decode($landing['offer_items_json'] ?? '[]', true) ?: [];
    $problems = json_decode($landing['problems_json'] ?? '[]', true) ?: [];
    $solution_list = json_decode($landing['solution_list_json'] ?? '[]', true) ?: [];
    $benefits = json_decode($landing['benefits_json'] ?? '[]', true) ?: [];
    $video_testimonials = json_decode($landing['video_testimonials_json'] ?? '[]', true) ?: [];
    $image_testimonials = json_decode($landing['image_testimonials_json'] ?? '[]', true) ?: [];
    $how_to_use_steps = json_decode($landing['how_to_use_steps_json'] ?? '[]', true) ?: [];
    $usage_guide_items = json_decode($landing['usage_guide_items_json'] ?? '[]', true) ?: [];
    $faqs = json_decode($landing['faqs_json'] ?? '[]', true) ?: [];
    $footer_links = json_decode($landing['footer_links_json'] ?? '[]', true) ?: [];
    $sections_order = json_decode($landing['sections_order'] ?? '[]', true) ?: $all_sections; // Default order if not set
    $floating_buttons = json_decode($landing['floating_buttons_json'] ?? '[]', true) ?: []; // NEW: Dynamic floating buttons
    // Fetch active statuses from individual columns
    $sections_status = [];
    foreach ($all_sections as $sec) {
        $field = $sec . '_active';
        $sections_status[$sec] = $landing[$field] ?? 1;
    }
} else {
    $landing = [];
    $products = $offer_items = $problems = $solution_list = $benefits = $video_testimonials = $image_testimonials = $how_to_use_steps = $usage_guide_items = $faqs = $footer_links = $floating_buttons = [];
    $sections_order = $all_sections;
    $sections_status = array_fill_keys($all_sections, 1); // All active by default
}
// IMAGE UPLOAD SETTINGS
$upload_dir = "uploads/landing/";
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$max_size = 2 * 1024 * 1024; // 2 MB
if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
// HANDLE FORM
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_landing'])) {
    // LANDING NAME (New)
    $landing_name = trim($_POST['landing_name'] ?? $landing['landing_name'] ?? '');
    // SECTIONS ORDER HANDLING
    $sections_order = [];
    if (isset($_POST['sections_order']) && is_array($_POST['sections_order'])) {
        $sections_order = array_values(array_filter($_POST['sections_order'], function($val) {
            return !empty($val);
        }));
    }
    // SECTIONS STATUS HANDLING (Individual columns from checkboxes)
    $sections_status = [];
    foreach ($all_sections as $sec) {
        $sections_status[$sec] = isset($_POST['section_active'][$sec]) ? 1 : 0;
    }
    // Extract individual variables for binding
    $top_offer_active = $sections_status['top_offer'];
    $hero_active = $sections_status['hero'];
    $products_active = $sections_status['products'];
    $offer_stack_active = $sections_status['offer_stack'];
    $problem_active = $sections_status['problem'];
    $solution_active = $sections_status['solution'];
    $benefits_active = $sections_status['benefits'];
    $video_testimonials_active = $sections_status['video_testimonials'];
    $image_testimonials_active = $sections_status['image_testimonials'];
    $how_to_use_active = $sections_status['how_to_use'];
    $usage_guide_active = $sections_status['usage_guide'];
    $faq_active = $sections_status['faq'];
    $order_form_active = $sections_status['order_form'];
    $final_cta_active = $sections_status['final_cta'];
    $footer_active = $sections_status['footer'];
    $floating_buttons_active = $sections_status['floating_buttons'];
    // TOP OFFER BAR
    $top_offer_text = trim($_POST['top_offer_text'] ?? $landing['top_offer_text'] ?? '');
    $top_offer_timer = trim($_POST['top_offer_timer'] ?? $landing['top_offer_timer'] ?? '');
    // HERO
    $hero_title = trim($_POST['hero_title'] ?? $landing['hero_title'] ?? '');
    $hero_subtitle = trim($_POST['hero_subtitle'] ?? $landing['hero_subtitle'] ?? '');
    $hero_cta_text = trim($_POST['hero_cta_text'] ?? $landing['hero_cta_text'] ?? '');
    $hero_timer = trim($_POST['hero_timer'] ?? $landing['hero_timer'] ?? '');
    $hero_image = $landing['hero_image'] ?? ''; // Keep old
    // PRODUCT SELECTION (Unlimited - Array based) - FIXED: Save old before reset
    $product_section_title = trim($_POST['product_section_title'] ?? $landing['product_section_title'] ?? '');
    $product_subtext = trim($_POST['product_subtext'] ?? $landing['product_subtext'] ?? '');
    $old_products = $products; // FIXED: Save old BEFORE resetting
    $products = []; // Reset to empty, rebuild from POST
    if (isset($_POST['product_badge']) && is_array($_POST['product_badge'])) {
        $count = count($_POST['product_badge']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $products[$index] = [
                'badge' => trim($_POST['product_badge'][$i] ?? ''),
                'title' => trim($_POST['product_title'][$i] ?? ''),
                'desc' => trim($_POST['product_desc'][$i] ?? ''),
                'old_price' => trim($_POST['product_old_price'][$i] ?? ''),
                'price' => trim($_POST['product_price'][$i] ?? ''),
                'image' => $old_products[$index]['image'] ?? '' // Carry over old image
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $products = $old_products;
    }
    // OFFER STACK (Unlimited - Array based) - FIXED: Save old before reset
    $offer_stack_title = trim($_POST['offer_stack_title'] ?? $landing['offer_stack_title'] ?? '');
    $offer_stack_subtext = trim($_POST['offer_stack_subtext'] ?? $landing['offer_stack_subtext'] ?? '');
    $offer_header_title = trim($_POST['offer_header_title'] ?? $landing['offer_header_title'] ?? '');
    $offer_header_p = trim($_POST['offer_header_p'] ?? $landing['offer_header_p'] ?? '');
    $old_offer_items = $offer_items; // FIXED: Save old BEFORE resetting
    $offer_items = []; // Reset to empty, rebuild from POST
    if (isset($_POST['offer_icon']) && is_array($_POST['offer_icon'])) {
        $count = count($_POST['offer_icon']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $offer_items[$index] = [
                'icon' => trim($_POST['offer_icon'][$i] ?? ''),
                'title' => trim($_POST['offer_title'][$i] ?? ''),
                'desc' => trim($_POST['offer_desc'][$i] ?? ''),
                'value' => trim($_POST['offer_value'][$i] ?? '')
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $offer_items = $old_offer_items;
    }
    $offer_total_h4 = trim($_POST['offer_total_h4'] ?? $landing['offer_total_h4'] ?? '');
    $offer_total_value = trim($_POST['offer_total_value'] ?? $landing['offer_total_value'] ?? '');
    $offer_actual_price = trim($_POST['offer_actual_price'] ?? $landing['offer_actual_price'] ?? '');
    $offer_save_amount = trim($_POST['offer_save_amount'] ?? $landing['offer_save_amount'] ?? '');
    // PROBLEM (Unlimited - Array based) - FIXED: Save old before reset
    $problem_section_title = trim($_POST['problem_section_title'] ?? $landing['problem_section_title'] ?? '');
    $old_problems = $problems; // FIXED: Save old BEFORE resetting
    $problems = []; // Reset to empty, rebuild from POST
    if (isset($_POST['problem_title']) && is_array($_POST['problem_title'])) {
        $count = count($_POST['problem_title']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $problems[$index] = [
                'title' => trim($_POST['problem_title'][$i] ?? ''),
                'desc' => trim($_POST['problem_desc'][$i] ?? '')
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $problems = $old_problems;
    }
    // SOLUTION - FIXED: Save old before reset
    $solution_section_title = trim($_POST['solution_section_title'] ?? $landing['solution_section_title'] ?? '');
    $solution_description = trim($_POST['solution_description'] ?? $landing['solution_description'] ?? '');
    $solution_image = $landing['solution_image'] ?? ''; // Keep old
    $old_solution_list = $solution_list; // FIXED: Save old BEFORE resetting
    $solution_list = []; // Reset to empty, rebuild from POST
    if (isset($_POST['solution_list_item']) && is_array($_POST['solution_list_item'])) {
        $count = count($_POST['solution_list_item']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $solution_list[$index] = trim($_POST['solution_list_item'][$i] ?? '');
        }
    } else {
        // Fallback to existing if no POST data
        $solution_list = $old_solution_list;
    }
    $solution_cta_text = trim($_POST['solution_cta_text'] ?? $landing['solution_cta_text'] ?? '');
    // BENEFITS (Unlimited - Array based) - FIXED: Save old before reset
    $benefits_section_title = trim($_POST['benefits_section_title'] ?? $landing['benefits_section_title'] ?? '');
    $old_benefits = $benefits; // FIXED: Save old BEFORE resetting
    $benefits = []; // Reset to empty, rebuild from POST
    if (isset($_POST['benefit_icon']) && is_array($_POST['benefit_icon'])) {
        $count = count($_POST['benefit_icon']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $benefits[$index] = [
                'icon' => trim($_POST['benefit_icon'][$i] ?? ''),
                'title' => trim($_POST['benefit_title'][$i] ?? ''),
                'desc' => trim($_POST['benefit_desc'][$i] ?? '')
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $benefits = $old_benefits;
    }
    // VIDEO TESTIMONIALS (Unlimited - Array based) - FIXED: Save old before reset
    $video_testimonials_title = trim($_POST['video_testimonials_title'] ?? $landing['video_testimonials_title'] ?? '');
    $video_testimonials_subtext = trim($_POST['video_testimonials_subtext'] ?? $landing['video_testimonials_subtext'] ?? '');
    $old_video_testimonials = $video_testimonials; // FIXED: Save old BEFORE resetting
    $video_testimonials = []; // Reset to empty, rebuild from POST
    if (isset($_POST['video_url']) && is_array($_POST['video_url'])) {
        $count = count($_POST['video_url']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $video_testimonials[$index] = [
                'video_url' => trim($_POST['video_url'][$i] ?? ''),
                'caption' => trim($_POST['video_caption'][$i] ?? '')
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $video_testimonials = $old_video_testimonials;
    }
    // IMAGE TESTIMONIALS (Unlimited - Array based) - FIXED: Save old before reset
    $image_testimonials_title = trim($_POST['image_testimonials_title'] ?? $landing['image_testimonials_title'] ?? '');
    $image_testimonials_subtext = trim($_POST['image_testimonials_subtext'] ?? $landing['image_testimonials_subtext'] ?? '');
    $old_image_testimonials = $image_testimonials; // FIXED: Save old BEFORE resetting
    $image_testimonials = []; // Reset to empty, rebuild from POST
    if (isset($_POST['image_caption']) && is_array($_POST['image_caption'])) {
        $count = count($_POST['image_caption']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $image_testimonials[$index] = [
                'caption' => trim($_POST['image_caption'][$i] ?? ''),
                'image' => $old_image_testimonials[$index]['image'] ?? '' // Carry over old image
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $image_testimonials = $old_image_testimonials;
    }
    // HOW TO USE (Unlimited - Array based) - FIXED: Save old before reset
    $how_to_use_title = trim($_POST['how_to_use_title'] ?? $landing['how_to_use_title'] ?? '');
    $how_to_use_subtitle = trim($_POST['how_to_use_subtitle'] ?? $landing['how_to_use_subtitle'] ?? '');
    $old_how_to_use_steps = $how_to_use_steps; // FIXED: Save old BEFORE resetting
    $how_to_use_steps = []; // Reset to empty, rebuild from POST
    if (isset($_POST['step_icon']) && is_array($_POST['step_icon'])) {
        $count = count($_POST['step_icon']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $how_to_use_steps[$index] = [
                'icon' => trim($_POST['step_icon'][$i] ?? ''),
                'title' => trim($_POST['step_title'][$i] ?? ''),
                'desc' => trim($_POST['step_desc'][$i] ?? '')
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $how_to_use_steps = $old_how_to_use_steps;
    }
    // USAGE GUIDE (Unlimited - Array based) - FIXED: Save old before reset
    $usage_guide_title = trim($_POST['usage_guide_title'] ?? $landing['usage_guide_title'] ?? '');
    $old_usage_guide_items = $usage_guide_items; // FIXED: Save old BEFORE resetting
    $usage_guide_items = []; // Reset to empty, rebuild from POST
    if (isset($_POST['usage_title']) && is_array($_POST['usage_title'])) {
        $count = count($_POST['usage_title']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $usage_guide_items[$index] = [
                'title' => trim($_POST['usage_title'][$i] ?? ''),
                'desc' => trim($_POST['usage_desc'][$i] ?? '')
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $usage_guide_items = $old_usage_guide_items;
    }
    // FAQ (Unlimited - Array based) - FIXED: Save old before reset
    $faq_title = trim($_POST['faq_title'] ?? $landing['faq_title'] ?? '');
    $old_faqs = $faqs; // FIXED: Save old BEFORE resetting
    $faqs = []; // Reset to empty, rebuild from POST
    if (isset($_POST['faq_question']) && is_array($_POST['faq_question'])) {
        $count = count($_POST['faq_question']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $faqs[$index] = [
                'question' => trim($_POST['faq_question'][$i] ?? ''),
                'answer' => trim($_POST['faq_answer'][$i] ?? '')
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $faqs = $old_faqs;
    }
    // ORDER FORM
    $order_form_title = trim($_POST['order_form_title'] ?? $landing['order_form_title'] ?? '');
    $order_form_subtext = trim($_POST['order_form_subtext'] ?? $landing['order_form_subtext'] ?? '');
    // FINAL CTA
    $final_cta_title = trim($_POST['final_cta_title'] ?? $landing['final_cta_title'] ?? '');
    $final_cta_button_text = trim($_POST['final_cta_button_text'] ?? $landing['final_cta_button_text'] ?? '');
    // FOOTER
    $footer_text = trim($_POST['footer_text'] ?? $landing['footer_text'] ?? '');
    $footer_copyright = trim($_POST['footer_copyright'] ?? $landing['footer_copyright'] ?? '');
    $footer_links = $footer_links; // Start with existing
    for ($i = 1; $i <= 3; $i++) {
        $footer_links[$i]['text'] = trim($_POST["footer_link_text_$i"] ?? $footer_links[$i]['text'] ?? '');
        $footer_links[$i]['url'] = trim($_POST["footer_link_url_$i"] ?? $footer_links[$i]['url'] ?? '');
    }
    // Legacy Floating Links (Deprecated - Keep for DB compat, no form input)
    $floating_whatsapp_link = $landing['floating_whatsapp_link'] ?? '';
    $floating_call_link = $landing['floating_call_link'] ?? '';
    // FLOATING BUTTONS (NEW: Unlimited - Array based) - FIXED: Save old before reset
    $old_floating_buttons = $floating_buttons; // FIXED: Save old BEFORE resetting
    $floating_buttons = []; // Reset to empty, rebuild from POST
    if (isset($_POST['float_number']) && is_array($_POST['float_number'])) {
        $count = count($_POST['float_number']);
        for ($i = 0; $i < $count; $i++) {
            $index = $i + 1; // 1-based for JSON keys
            $floating_buttons[$index] = [
                'number' => trim($_POST['float_number'][$i] ?? ''), // NEW: Number/Icon input
                'link' => trim($_POST['float_link'][$i] ?? ''), // Link
                'image' => $old_floating_buttons[$index]['image'] ?? '' // Carry over old image
            ];
        }
    } else {
        // Fallback to existing if no POST data
        $floating_buttons = $old_floating_buttons;
    }
    // VALIDATION (Basic required fields)
    if (empty($landing_name)) $errors[] = "Landing page name is required.";
    if (empty($hero_title)) $errors[] = "Hero title is required.";
    if (empty($product_section_title)) $errors[] = "Product section title is required.";
    // IMAGE HANDLING (Hero, Solution, Product Images, Image Testimonials, Floating Button Images)
    // Hero Image
    if (isset($_FILES['hero_image']) && $_FILES['hero_image']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['hero_image']['tmp_name'];
        $file_name = basename($_FILES['hero_image']['name']);
        $file_size = $_FILES['hero_image']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        if (!in_array($file_ext, $allowed)) {
            $errors[] = "Hero image: only JPG, JPEG, PNG & GIF allowed.";
        } elseif ($file_size > $max_size) {
            $errors[] = "Hero image must be ≤ 2 MB.";
        } else {
            $new_name = uniqid("hero_") . '.' . $file_ext;
            $dest = $upload_dir . $new_name;
            if (move_uploaded_file($file_tmp, $dest)) {
                $old_img = $landing['hero_image'] ?? '';
                if (!empty($old_img) && file_exists($upload_dir . $old_img)) @unlink($upload_dir . $old_img);
                $hero_image = $new_name;
            } else {
                $errors[] = "Failed to upload hero image.";
            }
        }
    }
    // Solution Image
    if (isset($_FILES['solution_image']) && $_FILES['solution_image']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['solution_image']['tmp_name'];
        $file_name = basename($_FILES['solution_image']['name']);
        $file_size = $_FILES['solution_image']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        if (!in_array($file_ext, $allowed)) {
            $errors[] = "Solution image: only JPG, JPEG, PNG & GIF allowed.";
        } elseif ($file_size > $max_size) {
            $errors[] = "Solution image must be ≤ 2 MB.";
        } else {
            $new_name = uniqid("solution_") . '.' . $file_ext;
            $dest = $upload_dir . $new_name;
            if (move_uploaded_file($file_tmp, $dest)) {
                $old_img = $landing['solution_image'] ?? '';
                if (!empty($old_img) && file_exists($upload_dir . $old_img)) @unlink($upload_dir . $old_img);
                $solution_image = $new_name;
            } else {
                $errors[] = "Failed to upload solution image.";
            }
        }
    }
    // Product Images (Unlimited - Handle array)
    if (isset($_FILES['product_image']) && is_array($_FILES['product_image']['tmp_name'])) {
        $count = count($_FILES['product_image']['tmp_name']);
        for ($i = 0; $i < $count; $i++) {
            if ($_FILES['product_image']['error'][$i] === UPLOAD_ERR_OK) {
                $file_tmp = $_FILES['product_image']['tmp_name'][$i];
                $file_name = basename($_FILES['product_image']['name'][$i]);
                $file_size = $_FILES['product_image']['size'][$i];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                if (!in_array($file_ext, $allowed)) {
                    $errors[] = "Product image $i: only JPG, JPEG, PNG & GIF allowed.";
                } elseif ($file_size > $max_size) {
                    $errors[] = "Product image $i must be ≤ 2 MB.";
                } else {
                    $new_name = uniqid("product_") . '.' . $file_ext;
                    $dest = $upload_dir . $new_name;
                    if (move_uploaded_file($file_tmp, $dest)) {
                        $index = $i + 1;
                        $old_img = $products[$index]['image'] ?? '';
                        if (!empty($old_img) && file_exists($upload_dir . $old_img)) @unlink($upload_dir . $old_img);
                        $products[$index]['image'] = $new_name;
                    } else {
                        $errors[] = "Failed to upload product image $i.";
                    }
                }
            }
        }
    }
    // Image Testimonials Images (Unlimited - Handle array)
    if (isset($_FILES['image_file']) && is_array($_FILES['image_file']['tmp_name'])) {
        $count = count($_FILES['image_file']['tmp_name']);
        for ($i = 0; $i < $count; $i++) {
            if ($_FILES['image_file']['error'][$i] === UPLOAD_ERR_OK) {
                $file_tmp = $_FILES['image_file']['tmp_name'][$i];
                $file_name = basename($_FILES['image_file']['name'][$i]);
                $file_size = $_FILES['image_file']['size'][$i];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                if (!in_array($file_ext, $allowed)) {
                    $errors[] = "Image testimonial image $i: only JPG, JPEG, PNG & GIF allowed.";
                } elseif ($file_size > $max_size) {
                    $errors[] = "Image testimonial image $i must be ≤ 2 MB.";
                } else {
                    $new_name = uniqid("image_testimonial_") . '.' . $file_ext;
                    $dest = $upload_dir . $new_name;
                    if (move_uploaded_file($file_tmp, $dest)) {
                        $index = $i + 1;
                        $old_img = $image_testimonials[$index]['image'] ?? '';
                        if (!empty($old_img) && file_exists($upload_dir . $old_img)) @unlink($upload_dir . $old_img);
                        $image_testimonials[$index]['image'] = $new_name;
                    } else {
                        $errors[] = "Failed to upload image testimonial image $i.";
                    }
                }
            }
        }
    }
    // NEW: Floating Button Images (Unlimited - Handle array)
    if (isset($_FILES['float_image']) && is_array($_FILES['float_image']['tmp_name'])) {
        $count = count($_FILES['float_image']['tmp_name']);
        for ($i = 0; $i < $count; $i++) {
            if ($_FILES['float_image']['error'][$i] === UPLOAD_ERR_OK) {
                $file_tmp = $_FILES['float_image']['tmp_name'][$i];
                $file_name = basename($_FILES['float_image']['name'][$i]);
                $file_size = $_FILES['float_image']['size'][$i];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                if (!in_array($file_ext, $allowed)) {
                    $errors[] = "Floating button image $i: only JPG, JPEG, PNG & GIF allowed.";
                } elseif ($file_size > $max_size) {
                    $errors[] = "Floating button image $i must be ≤ 2 MB.";
                } else {
                    $new_name = uniqid("float_btn_") . '.' . $file_ext;
                    $dest = $upload_dir . $new_name;
                    if (move_uploaded_file($file_tmp, $dest)) {
                        $index = $i + 1;
                        $old_img = $floating_buttons[$index]['image'] ?? '';
                        if (!empty($old_img) && file_exists($upload_dir . $old_img)) @unlink($upload_dir . $old_img);
                        $floating_buttons[$index]['image'] = $new_name;
                    } else {
                        $errors[] = "Failed to upload floating button image $i.";
                    }
                }
            }
        }
    }
    // SAVE TO DB
    if (empty($errors)) {
        $products_json = json_encode($products);
        $offer_items_json = json_encode($offer_items);
        $problems_json = json_encode($problems);
        $solution_list_json = json_encode($solution_list);
        $benefits_json = json_encode($benefits);
        $video_testimonials_json = json_encode($video_testimonials);
        $image_testimonials_json = json_encode($image_testimonials);
        $how_to_use_steps_json = json_encode($how_to_use_steps);
        $usage_guide_items_json = json_encode($usage_guide_items);
        $faqs_json = json_encode($faqs);
        $footer_links_json = json_encode($footer_links);
        $sections_order_json = json_encode($sections_order);
        $floating_buttons_json = json_encode($floating_buttons); // NEW
        // Bind types: 69 s (landing_name + sections_order + 16 actives + 50 content + 1 floating_buttons_json) + i for id
        $bind_types = str_repeat('s', 69) . 'i';
        $insert_types = str_repeat('s', 69);
        $old_landing_id = $landing['id'] ?? '';
        if (!empty($old_landing_id)) {
            // UPDATE with individual active fields and floating_buttons_json
            $stmt = $conn->prepare("UPDATE manage_landing SET
                landing_name=?,
                sections_order=?,
                top_offer_active=?, hero_active=?, products_active=?, offer_stack_active=?, problem_active=?, solution_active=?, benefits_active=?, video_testimonials_active=?, image_testimonials_active=?, how_to_use_active=?, usage_guide_active=?, faq_active=?, order_form_active=?, final_cta_active=?, footer_active=?, floating_buttons_active=?,
                top_offer_text=?, top_offer_timer=?,
                hero_title=?, hero_subtitle=?, hero_cta_text=?, hero_timer=?, hero_image=?,
                product_section_title=?, product_subtext=?, products_json=?,
                offer_stack_title=?, offer_stack_subtext=?, offer_header_title=?, offer_header_p=?, offer_items_json=?, offer_total_h4=?, offer_total_value=?, offer_actual_price=?, offer_save_amount=?,
                problem_section_title=?, problems_json=?,
                solution_section_title=?, solution_description=?, solution_image=?, solution_list_json=?, solution_cta_text=?,
                benefits_section_title=?, benefits_json=?,
                video_testimonials_title=?, video_testimonials_subtext=?, video_testimonials_json=?,
                image_testimonials_title=?, image_testimonials_subtext=?, image_testimonials_json=?,
                how_to_use_title=?, how_to_use_subtitle=?, how_to_use_steps_json=?,
                usage_guide_title=?, usage_guide_items_json=?,
                faq_title=?, faqs_json=?,
                order_form_title=?, order_form_subtext=?,
                final_cta_title=?, final_cta_button_text=?,
                footer_text=?, footer_copyright=?, footer_links_json=?,
                floating_whatsapp_link=?, floating_call_link=?,
                floating_buttons_json=?
                WHERE id=?");
            $stmt->bind_param($bind_types,
                $landing_name,
                $sections_order_json,
                $top_offer_active, $hero_active, $products_active, $offer_stack_active, $problem_active, $solution_active, $benefits_active, $video_testimonials_active, $image_testimonials_active, $how_to_use_active, $usage_guide_active, $faq_active, $order_form_active, $final_cta_active, $footer_active, $floating_buttons_active,
                $top_offer_text, $top_offer_timer,
                $hero_title, $hero_subtitle, $hero_cta_text, $hero_timer, $hero_image,
                $product_section_title, $product_subtext, $products_json,
                $offer_stack_title, $offer_stack_subtext, $offer_header_title, $offer_header_p, $offer_items_json, $offer_total_h4, $offer_total_value, $offer_actual_price, $offer_save_amount,
                $problem_section_title, $problems_json,
                $solution_section_title, $solution_description, $solution_image, $solution_list_json, $solution_cta_text,
                $benefits_section_title, $benefits_json,
                $video_testimonials_title, $video_testimonials_subtext, $video_testimonials_json,
                $image_testimonials_title, $image_testimonials_subtext, $image_testimonials_json,
                $how_to_use_title, $how_to_use_subtitle, $how_to_use_steps_json,
                $usage_guide_title, $usage_guide_items_json,
                $faq_title, $faqs_json,
                $order_form_title, $order_form_subtext,
                $final_cta_title, $final_cta_button_text,
                $footer_text, $footer_copyright, $footer_links_json,
                $floating_whatsapp_link, $floating_call_link,
                $floating_buttons_json, // NEW
                $old_landing_id
            );
        } else {
            // INSERT with individual active fields and floating_buttons_json (default all 1, but set from POST)
            $stmt = $conn->prepare("INSERT INTO manage_landing (
                landing_name,
                sections_order,
                top_offer_active, hero_active, products_active, offer_stack_active, problem_active, solution_active, benefits_active, video_testimonials_active, image_testimonials_active, how_to_use_active, usage_guide_active, faq_active, order_form_active, final_cta_active, footer_active, floating_buttons_active,
                top_offer_text, top_offer_timer,
                hero_title, hero_subtitle, hero_cta_text, hero_timer, hero_image,
                product_section_title, product_subtext, products_json,
                offer_stack_title, offer_stack_subtext, offer_header_title, offer_header_p, offer_items_json, offer_total_h4, offer_total_value, offer_actual_price, offer_save_amount,
                problem_section_title, problems_json,
                solution_section_title, solution_description, solution_image, solution_list_json, solution_cta_text,
                benefits_section_title, benefits_json,
                video_testimonials_title, video_testimonials_subtext, video_testimonials_json,
                image_testimonials_title, image_testimonials_subtext, image_testimonials_json,
                how_to_use_title, how_to_use_subtitle, how_to_use_steps_json,
                usage_guide_title, usage_guide_items_json,
                faq_title, faqs_json,
                order_form_title, order_form_subtext,
                final_cta_title, final_cta_button_text,
                footer_text, footer_copyright, footer_links_json,
                floating_whatsapp_link, floating_call_link,
                floating_buttons_json
            ) VALUES " . str_repeat('(?,', 68) . '?)');
            $stmt->bind_param($insert_types,
                $landing_name,
                $sections_order_json,
                $top_offer_active, $hero_active, $products_active, $offer_stack_active, $problem_active, $solution_active, $benefits_active, $video_testimonials_active, $image_testimonials_active, $how_to_use_active, $usage_guide_active, $faq_active, $order_form_active, $final_cta_active, $footer_active, $floating_buttons_active,
                $top_offer_text, $top_offer_timer,
                $hero_title, $hero_subtitle, $hero_cta_text, $hero_timer, $hero_image,
                $product_section_title, $product_subtext, $products_json,
                $offer_stack_title, $offer_stack_subtext, $offer_header_title, $offer_header_p, $offer_items_json, $offer_total_h4, $offer_total_value, $offer_actual_price, $offer_save_amount,
                $problem_section_title, $problems_json,
                $solution_section_title, $solution_description, $solution_image, $solution_list_json, $solution_cta_text,
                $benefits_section_title, $benefits_json,
                $video_testimonials_title, $video_testimonials_subtext, $video_testimonials_json,
                $image_testimonials_title, $image_testimonials_subtext, $image_testimonials_json,
                $how_to_use_title, $how_to_use_subtitle, $how_to_use_steps_json,
                $usage_guide_title, $usage_guide_items_json,
                $faq_title, $faqs_json,
                $order_form_title, $order_form_subtext,
                $final_cta_title, $final_cta_button_text,
                $footer_text, $footer_copyright, $footer_links_json,
                $floating_whatsapp_link, $floating_call_link,
                $floating_buttons_json // NEW
            );
        }
        if ($stmt->execute()) {
            $success = "Landing page updated successfully!";
            // Determine ID for refetch (INSERT gets new ID, UPDATE uses old)
            $refetch_id = $old_landing_id ?: $conn->insert_id;
            // Refetch and re-decode using ID
            $refetch_stmt = $conn->prepare("SELECT * FROM manage_landing WHERE id = ? LIMIT 1");
            $refetch_stmt->bind_param('i', $refetch_id);
            $refetch_stmt->execute();
            $landing_result = $refetch_stmt->get_result();
            if ($landing_result->num_rows > 0) {
                $landing = $landing_result->fetch_assoc();
                $products = json_decode($landing['products_json'] ?? '[]', true) ?: [];
                $offer_items = json_decode($landing['offer_items_json'] ?? '[]', true) ?: [];
                $problems = json_decode($landing['problems_json'] ?? '[]', true) ?: [];
                $solution_list = json_decode($landing['solution_list_json'] ?? '[]', true) ?: [];
                $benefits = json_decode($landing['benefits_json'] ?? '[]', true) ?: [];
                $video_testimonials = json_decode($landing['video_testimonials_json'] ?? '[]', true) ?: [];
                $image_testimonials = json_decode($landing['image_testimonials_json'] ?? '[]', true) ?: [];
                $how_to_use_steps = json_decode($landing['how_to_use_steps_json'] ?? '[]', true) ?: [];
                $usage_guide_items = json_decode($landing['usage_guide_items_json'] ?? '[]', true) ?: [];
                $faqs = json_decode($landing['faqs_json'] ?? '[]', true) ?: [];
                $footer_links = json_decode($landing['footer_links_json'] ?? '[]', true) ?: [];
                $sections_order = json_decode($landing['sections_order'] ?? '[]', true) ?: $all_sections;
                $floating_buttons = json_decode($landing['floating_buttons_json'] ?? '[]', true) ?: []; // NEW
                // Refetch active statuses
                $sections_status = [];
                foreach ($all_sections as $sec) {
                    $field = $sec . '_active';
                    $sections_status[$sec] = $landing[$field] ?? 1;
                }
            }
            $refetch_stmt->close();
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
        $stmt->close();
    }
}
?>
<?php
/**
 * ========================================================
 * HTML STRUCTURE SECTION: Main Page Layout and Form Fields
 * ========================================================
 * This section contains the full HTML document, including head, body, and all form elements.
 * PHP echoes are used for dynamic values.
 * UPDATE: Floating Buttons now dynamic with unlimited add/remove, number input, image upload, link.
 * UPDATE: Added "Edit Details" button in Order Form Section that links to edit_details.php with landing ID.
 * UPDATE: External CSS/JS includes for manage_landing.css and .js.
 * UPDATE: All form sections modularized into separate PHP files in sections/ folder.
 */
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Landing Page - <?php echo htmlspecialchars($landing['landing_name'] ?? 'New Landing'); ?></title>
    <!-- External Scripts -->
    <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    <!-- External CSS -->
    <link rel="stylesheet" href="sections/manage_landing.css">
</head>
<body>
<div id="content" class="content p-4 min-h-screen">
    <?php include "include/topnav.php"; ?>
    <div class="max-w-6xl mx-auto my-4">
        <h2 class="text-2xl font-bold text-gray-800 mb-4 text-center">
            Manage Landing Page - <?php echo htmlspecialchars($landing['landing_name'] ?? 'New Landing'); ?>
            (ID: <?php echo $landing_id ?? $landing['id'] ?? 'New'; ?>)
        </h2>
        <?php if ($success): ?>
            <div class="success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if (!empty($errors)): ?>
            <div class="error">
                <?php foreach ($errors as $e): ?>
                    <p><?php echo htmlspecialchars($e); ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <form method="POST" enctype="multipart/form-data" class="space-y-4" id="landingForm">
            <input type="hidden" name="update_landing" value="1">
            <!-- Modular Sections Includes -->
             <?php include "sections/landing_name_section.php"; ?>
            <?php include "sections/sections_order_section.php"; ?>
            <?php include "sections/top_offer_section.php"; ?>
            <?php include "sections/hero_section.php"; ?>
            <?php include "sections/products_section.php"; ?>
            <?php include "sections/offer_stack_section.php"; ?>
            <?php include "sections/problem_section.php"; ?>
            <?php include "sections/solution_section.php"; ?>
            <?php include "sections/benefits_section.php"; ?>
            <?php include "sections/video_testimonials_section.php"; ?>
            <?php include "sections/image_testimonials_section.php"; ?>
            <?php include "sections/how_to_use_section.php"; ?>
            <?php include "sections/usage_guide_section.php"; ?>
            <?php include "sections/faq_section.php"; ?>
            <?php include "sections/order_form_section.php"; ?>
            <?php include "sections/final_cta_section.php"; ?>
            <?php include "sections/footer_section.php"; ?>
            <?php include "sections/floating_buttons_section.php"; ?>
            <!-- SUBMIT -->
            <div class="flex gap-2">
                <button type="submit"
                        class="flex-1 bg-yellow-500 text-white p-2 rounded hover:bg-yellow-600 font-bold">
                    Update Landing Page
                </button>
                <a href="dashboard.php"
                   class="flex-1 bg-gray-600 text-white p-2 rounded text-center font-bold">
                    Back to Dashboard
                </a>
            </div>
        </form>
    </div>
</div>
<!-- JS Counters Inline (Required for External JS) -->
<script>
let productCounter = <?php echo count($products); ?> || 1;
let offerCounter = <?php echo count($offer_items); ?> || 1;
let problemCounter = <?php echo count($problems); ?> || 1;
let solutionCounter = <?php echo count($solution_list); ?> || 1;
let benefitCounter = <?php echo count($benefits); ?> || 1;
let videoTestimonialCounter = <?php echo count($video_testimonials); ?> || 1;
let imageTestimonialCounter = <?php echo count($image_testimonials); ?> || 1;
let stepCounter = <?php echo count($how_to_use_steps); ?> || 1;
let usageCounter = <?php echo count($usage_guide_items); ?> || 1;
let faqCounter = <?php echo count($faqs); ?> || 1;
let floatButtonCounter = <?php echo count($floating_buttons); ?> || 1;
</script>
<!-- External JS -->
<script src="sections/manage_landing.js"></script>
</body>
</html>
<?php
/**
 * ========================================================
 * END OF FILE - Summary of Updates
 * ========================================================
 * Updates Made:
 * 1. Added floating_buttons_json LONGTEXT column handling (SQL: ALTER TABLE manage_landing ADD COLUMN floating_buttons_json LONGTEXT AFTER floating_call_link;).
 * 2. Dynamic form: Unlimited float-btn rows with number input, link input, image upload (carry over old images).
 * 3. PHP: Rebuild $floating_buttons array from POST, handle image uploads in loop, bind to DB (now 69 s params).
 * 4. JS: addFloatButton() and removeFloatButton() with counter, at least one required.
 * 5. CSS: Added .float-btn-row to dynamic rows.
 * 6. Legacy WhatsApp/Call links kept but noted as deprecated; use dynamic for all.
 * 7. Refetch includes new JSON decode. No breaking changes.
 * 8. NEW: Added "Edit Details" button in Order Form Section that opens edit_details.php?id={landing_id} (create edit_details.php separately if needed).
 * 9. UPDATE: ID support via ?id=GET - Fetch by ID if provided, else LIMIT 1. Refetch after save uses correct ID (insert_id for new). Title uses 'New Landing' if empty.
 * 10. FIX: Added $floating_whatsapp_link and $floating_call_link from $landing[] (no form input, deprecated).
 * 11. UPDATE: CSS/JS separated to sections/ folder with includes.
 * 12. UPDATE: All form sections modularized into separate PHP files in sections/ folder (e.g., hero_section.php).
 * SQL for new column (run once): ALTER TABLE manage_landing ADD COLUMN floating_buttons_json LONGTEXT AFTER floating_call_link;
 * In landing render: Loop over json_decode($landing['floating_buttons_json']) to output buttons.
 */
?>