<?php
/**
 * Hero Slider Management Handler
 * This file handles all operations on hero slider slides and keeps index.html synchronized
 */

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

$response = [
    'success' => false,
    'message' => '',
    'data' => null
];

if (!isset($_POST['action'])) {
    $response['message'] = 'No action specified';
    echo json_encode($response);
    exit;
}

$action = $_POST['action'];
$index_file = __DIR__ . '/index.php';
$index_php_file = __DIR__ . '/index.php';

// Function to extract all hero slides from index.php
function getHeroSlides() {
    global $index_file, $index_php_file;
    
    // Try to use index.php first, then fall back to index.html
    $file_to_use = file_exists($index_php_file) ? $index_php_file : $index_file;
    
    if (!file_exists($file_to_use)) {
        return [];
    }
    
    $html_content = file_get_contents($file_to_use);
    $slides = [];
    
    // More flexible pattern that matches hero slides in index.php
    // This pattern captures: background image, subtitle, and entire h1 content
    if (preg_match_all(
        '/<div class="swiper-slide">.*?<div class="th-hero-bg" data-bg-src="([^"]+)".*?<span class="sub-title"[^>]*>([^<]*)<\/span>\s*<h1 class="hero-title"[^>]*>(.*?)<\/h1>/s',
        $html_content,
        $matches
    )) {
        for ($i = 0; $i < count($matches[1]); $i++) {
            $subtitle = trim($matches[2][$i]);
            $title_html = $matches[3][$i];
            
            // Parse the title to extract highlight and parts
            $title_part1 = '';
            $highlight = '';
            $title_part2 = '';
            
            // Look for <span class="text-theme">...content...</span>
            if (preg_match('/(.*?)<span class="text-theme">([^<]*)<\/span>(.*)/s', $title_html, $title_parts)) {
                $title_part1 = trim($title_parts[1]);
                $highlight = trim($title_parts[2]);
                $title_part2 = trim($title_parts[3]);
            } else {
                // If no theme span found, use entire title as part1
                $title_part1 = trim($title_html);
            }
            
            $slides[] = [
                'index' => $i,
                'image' => $matches[1][$i],
                'subtitle' => $subtitle,
                'title_part1' => $title_part1,
                'highlight' => $highlight,
                'title_part2' => $title_part2
            ];
        }
    }
    
    return $slides;
}

// Function to get hero slides container in index.php
function getHeroSliderContainer() {
    global $index_file, $index_php_file;
    
    // Try to use index.php first, then fall back to index.html
    $file_to_use = file_exists($index_php_file) ? $index_php_file : $index_file;
    
    $html_content = file_get_contents($file_to_use);
    
    // Find the hero slider container div (contains all swiper-slides)
    if (preg_match(
        '/<div class="swiper-wrapper">\s*(.*?)\s*<\/div>\s*<div class="slider-pagination"><\/div>/s',
        $html_content,
        $matches
    )) {
        return [
            'before' => substr($html_content, 0, strpos($html_content, '<div class="swiper-wrapper">') + strlen('<div class="swiper-wrapper">')),
            'after' => substr($html_content, strpos($html_content, '</div>') + strlen('<\/div>\s*<div class="slider-pagination"><\/div>'), strlen($html_content))
        ];
    }
    
    return null;
}

// Handle different actions
switch ($action) {
    case 'get_slides':
        $slides = getHeroSlides();
        $response['success'] = true;
        $response['data'] = $slides;
        break;
        
    case 'add_slide':
        $image = $_POST['image'] ?? '';
        $title = $_POST['title'] ?? '';
        $highlight = $_POST['highlight'] ?? '';
        $subtitle = $_POST['subtitle'] ?? 'Innovative solutions';
        
        if (!$image || !$title || !$highlight) {
            $response['message'] = 'Missing required fields';
            break;
        }
        
        // Read the index.html file
        $html_content = file_get_contents($index_file);
        
        // Create the new slide HTML
        $new_slide = "
                <div class=\"swiper-slide\">
                    <div class=\"hero-inner\">
                        <div class=\"th-hero-bg\" data-bg-src=\"" . htmlspecialchars($image) . "\"></div>
                        <div class=\"container\" style=\"padding-top: 50px;\">
                            <div class=\"row align-items-end\">
                                <div class=\"col-xl-8\">
                                    <div class=\"hero-style8\"><span class=\"sub-title\" data-ani=\"slideinleft\"
                                            data-ani-delay=\"0.3s\">" . htmlspecialchars($subtitle) . "</span>
                                        <h1 class=\"hero-title\" data-ani=\"slideinleft\" data-ani-delay=\"0.4s\">
                                            " . htmlspecialchars($title) . " <span class=\"text-theme\">" . htmlspecialchars($highlight) . "</span> " . htmlspecialchars(isset($_POST['title_part2']) ? $_POST['title_part2'] : '') . "
                                        </h1>
                                        <div class=\"btn-group justify-content-xl-start justify-content-center\"
                                            data-ani=\"slideinleft\" data-ani-delay=\"0.6s\"><a href=\"contact.html\"
                                                class=\"th-btn style3\">Know More Us</a> <a href=\"project.html\"
                                                class=\"th-btn white-btn\">Explore Projects</a></div>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>";
        
        // Insert the new slide before the closing swiper div
        $pattern = '/(.*<div class="swiper-slide">.*?<\/div>)\s*(\n\s*<\/div>\s*<div class="slider-pagination">)/s';
        if (preg_match($pattern, $html_content, $matches)) {
            $updated_html = $matches[1] . $new_slide . "\n            " . $matches[2];
            $html_content = preg_replace($pattern, $updated_html, $html_content);
            
            if (file_put_contents($index_file, $html_content)) {
                // Also update index.php
                if (file_exists($index_php_file)) {
                    $php_content = file_get_contents($index_php_file);
                    if ($php_content !== false) {
                        $updated_php = $matches[1] . $new_slide . "\n            " . $matches[2];
                        $php_content = preg_replace($pattern, $updated_php, $php_content);
                        
                        if (file_put_contents($index_php_file, $php_content)) {
                            $response['success'] = true;
                            $response['message'] = 'Slide added successfully!';
                            $response['data'] = getHeroSlides();
                        } else {
                            $response['success'] = true;
                            $response['message'] = 'Slide added but PHP file update failed!';
                            $response['data'] = getHeroSlides();
                        }
                    } else {
                        $response['success'] = true;
                        $response['message'] = 'Slide added but could not read PHP file!';
                        $response['data'] = getHeroSlides();
                    }
                } else {
                    $response['success'] = true;
                    $response['message'] = 'Slide added but PHP file not found!';
                    $response['data'] = getHeroSlides();
                }
            } else {
                $response['message'] = 'Failed to write to index.html';
            }
        } else {
            $response['message'] = 'Could not find slider container in index.html';
        }
        break;
        
    case 'edit_slide':
        $slide_index = intval($_POST['slide_index'] ?? -1);
        $image = $_POST['image'] ?? '';
        $title = $_POST['title'] ?? '';
        $highlight = $_POST['highlight'] ?? '';
        $subtitle = $_POST['subtitle'] ?? 'Innovative solutions';
        
        if ($slide_index < 0 || !$image || !$title || !$highlight) {
            $response['message'] = 'Missing required fields';
            break;
        }
        
        $slides = getHeroSlides();
        
        if ($slide_index >= count($slides)) {
            $response['message'] = 'Slide not found';
            break;
        }
        
        $old_slide = $slides[$slide_index];
        $html_content = file_get_contents($index_file);
        
        // Build the old slide pattern to match
        $old_pattern = preg_quote($old_slide['image']) . '.*?' . 
                      preg_quote($old_slide['subtitle']) . '.*?' .
                      preg_quote($old_slide['title_part1']) . '.*?' .
                      preg_quote($old_slide['highlight']);
        
        // Create the new slide HTML
        $new_slide_html = "
                <div class=\"swiper-slide\">
                    <div class=\"hero-inner\">
                        <div class=\"th-hero-bg\" data-bg-src=\"" . htmlspecialchars($image) . "\"></div>
                        <div class=\"container\" style=\"padding-top: 50px;\">
                            <div class=\"row align-items-end\">
                                <div class=\"col-xl-8\">
                                    <div class=\"hero-style8\"><span class=\"sub-title\" data-ani=\"slideinleft\"
                                            data-ani-delay=\"0.3s\">" . htmlspecialchars($subtitle) . "</span>
                                        <h1 class=\"hero-title\" data-ani=\"slideinleft\" data-ani-delay=\"0.4s\">
                                            " . htmlspecialchars($title) . " <span class=\"text-theme\">" . htmlspecialchars($highlight) . "</span> " . htmlspecialchars(isset($_POST['title_part2']) ? $_POST['title_part2'] : '') . "
                                        </h1>
                                        <div class=\"btn-group justify-content-xl-start justify-content-center\"
                                            data-ani=\"slideinleft\" data-ani-delay=\"0.6s\"><a href=\"contact.html\"
                                                class=\"th-btn style3\">Know More Us</a> <a href=\"project.html\"
                                                class=\"th-btn white-btn\">Explore Projects</a></div>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>";
        
        // Find and replace the specific slide - more robust approach
        if (preg_match_all('/<div class="swiper-slide">.*?<\/div>/s', $html_content, $all_slides)) {
            if ($slide_index < count($all_slides[0])) {
                $html_content = str_replace($all_slides[0][$slide_index], $new_slide_html, $html_content);
                
                if (file_put_contents($index_file, $html_content)) {
                    // Also update index.php
                    if (file_exists($index_php_file)) {
                        $php_content = file_get_contents($index_php_file);
                        if ($php_content !== false) {
                            if (preg_match_all('/<div class="swiper-slide">.*?<\/div>/s', $php_content, $php_all_slides)) {
                                if ($slide_index < count($php_all_slides[0])) {
                                    $php_content = str_replace($php_all_slides[0][$slide_index], $new_slide_html, $php_content);
                                    
                                    if (file_put_contents($index_php_file, $php_content)) {
                                        $response['success'] = true;
                                        $response['message'] = 'Slide updated successfully!';
                                        $response['data'] = getHeroSlides();
                                    } else {
                                        $response['success'] = true;
                                        $response['message'] = 'Slide updated but PHP file update failed!';
                                        $response['data'] = getHeroSlides();
                                    }
                                } else {
                                    $response['success'] = true;
                                    $response['message'] = 'Slide updated but PHP slide index out of range!';
                                    $response['data'] = getHeroSlides();
                                }
                            } else {
                                $response['success'] = true;
                                $response['message'] = 'Slide updated but could not find slides in PHP file!';
                                $response['data'] = getHeroSlides();
                            }
                        } else {
                            $response['success'] = true;
                            $response['message'] = 'Slide updated but could not read PHP file!';
                            $response['data'] = getHeroSlides();
                        }
                    } else {
                        $response['success'] = true;
                        $response['message'] = 'Slide updated but PHP file not found!';
                        $response['data'] = getHeroSlides();
                    }
                } else {
                    $response['message'] = 'Failed to write to index.html';
                }
            } else {
                $response['message'] = 'Slide index out of range';
            }
        } else {
            $response['message'] = 'Could not find slides in index.html';
        }
        break;
        
    case 'delete_slide':
        $slide_index = intval($_POST['slide_index'] ?? -1);
        
        if ($slide_index < 0) {
            $response['message'] = 'Invalid slide index';
            break;
        }
        
        $html_content = file_get_contents($index_file);
        
        // Find and extract all slides
        if (preg_match_all('/<div class="swiper-slide">.*?<\/div>/s', $html_content, $all_slides)) {
            if ($slide_index < count($all_slides[0])) {
                // Only allow deletion if there are more than 1 slides
                if (count($all_slides[0]) <= 1) {
                    $response['message'] = 'Cannot delete the last slide';
                    break;
                }
                
                // Remove the slide
                $html_content = str_replace($all_slides[0][$slide_index], '', $html_content);
                
                // Clean up extra whitespace
                $html_content = preg_replace('/\n\s*\n/', "\n", $html_content);
                
                if (file_put_contents($index_file, $html_content)) {
                    // Also update index.php
                    if (file_exists($index_php_file)) {
                        $php_content = file_get_contents($index_php_file);
                        if ($php_content !== false) {
                            if (preg_match_all('/<div class="swiper-slide">.*?<\/div>/s', $php_content, $php_all_slides)) {
                                if ($slide_index < count($php_all_slides[0])) {
                                    if (count($php_all_slides[0]) <= 1) {
                                        $response['success'] = true;
                                        $response['message'] = 'Slide deleted but PHP file has only 1 slide!';
                                        $response['data'] = getHeroSlides();
                                        break;
                                    }
                                    
                                    $php_content = str_replace($php_all_slides[0][$slide_index], '', $php_content);
                                    $php_content = preg_replace('/\n\s*\n/', "\n", $php_content);
                                    
                                    if (file_put_contents($index_php_file, $php_content)) {
                                        $response['success'] = true;
                                        $response['message'] = 'Slide deleted successfully!';
                                        $response['data'] = getHeroSlides();
                                    } else {
                                        $response['success'] = true;
                                        $response['message'] = 'Slide deleted but PHP file update failed!';
                                        $response['data'] = getHeroSlides();
                                    }
                                } else {
                                    $response['success'] = true;
                                    $response['message'] = 'Slide deleted but PHP slide index out of range!';
                                    $response['data'] = getHeroSlides();
                                }
                            } else {
                                $response['success'] = true;
                                $response['message'] = 'Slide deleted but could not find slides in PHP file!';
                                $response['data'] = getHeroSlides();
                            }
                        } else {
                            $response['success'] = true;
                            $response['message'] = 'Slide deleted but could not read PHP file!';
                            $response['data'] = getHeroSlides();
                        }
                    } else {
                        $response['success'] = true;
                        $response['message'] = 'Slide deleted but PHP file not found!';
                        $response['data'] = getHeroSlides();
                    }
                } else {
                    $response['message'] = 'Failed to write to index.html';
                }
            } else {
                $response['message'] = 'Slide index out of range';
            }
        } else {
            $response['message'] = 'Could not find slides in index.html';
        }
        break;
        
    default:
        $response['message'] = 'Unknown action: ' . $action;
}

echo json_encode($response);
?>
