<?php
/**
 * Hero Slider API Handler
 * Handles AJAX requests for add, edit, delete, and retrieve operations
 */

// Set JSON header first, before any output
header('Content-Type: application/json');

require_once 'config.php';
session_start();

// Create upload directory if it doesn't exist
$upload_dir = 'assets/uploads/hero-slider/';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'get_all':
        getHeroSlides();
        break;
    case 'get_one':
        getSingleSlide();
        break;
    case 'add':
        addHeroSlide();
        break;
    case 'edit':
        editHeroSlide();
        break;
    case 'delete':
        deleteHeroSlide();
        break;
    case 'reorder':
        reorderSlides();
        break;
    default:
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}

// Helper function to handle image upload
function handleImageUpload($fieldName = 'slide_bg_image') {
    global $upload_dir;
    
    if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] === UPLOAD_ERR_NO_FILE) {
        return null; // No image uploaded
    }
    
    $file = $_FILES[$fieldName];
    
    // Validate file
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $max_size = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($file['type'], $allowed_types)) {
        return ['error' => 'Invalid file type. Only JPG, PNG, GIF, and WebP are allowed'];
    }
    
    if ($file['size'] > $max_size) {
        return ['error' => 'File size exceeds 5MB limit'];
    }
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['error' => 'Upload error: ' . $file['error']];
    }
    
    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'slider_' . time() . '_' . uniqid() . '.' . $extension;
    $filepath = $upload_dir . $filename;
    
    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $filepath)) {
        return ['error' => 'Failed to move uploaded file'];
    }
    
    return ['filename' => $filename, 'filepath' => $filepath];
}

function getHeroSlides() {
    global $conn;
    
    // Check if table exists first
    $tableCheck = $conn->query("SHOW TABLES LIKE 'hero_slider'");
    if (!$tableCheck || $tableCheck->num_rows === 0) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database table not found. Please run the setup SQL file.']);
        exit();
    }
    
    $query = "SELECT * FROM hero_slider ORDER BY slide_order ASC";
    $result = $conn->query($query);
    
    if (!$result) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        exit();
    }
    
    $slides = [];
    while ($row = $result->fetch_assoc()) {
        $slides[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $slides]);
}

function getSingleSlide() {
    global $conn;
    
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid slide ID']);
        exit();
    }
    
    $query = "SELECT * FROM hero_slider WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Slide not found']);
        exit();
    }
    
    $slide = $result->fetch_assoc();
    echo json_encode(['success' => true, 'data' => $slide]);
}

function addHeroSlide() {
    global $conn;
    
    $title = $conn->real_escape_string($_POST['title'] ?? '');
    $description = $conn->real_escape_string($_POST['description'] ?? '');
    $badge = $conn->real_escape_string($_POST['badge'] ?? '');
    $badge_icon = $conn->real_escape_string($_POST['badge_icon'] ?? 'fa-star');
    $button_1_text = $conn->real_escape_string($_POST['button_1_text'] ?? '');
    $button_1_url = $conn->real_escape_string($_POST['button_1_url'] ?? '');
    $button_1_type = $conn->real_escape_string($_POST['button_1_type'] ?? 'primary');
    $button_2_text = $conn->real_escape_string($_POST['button_2_text'] ?? '');
    $button_2_url = $conn->real_escape_string($_POST['button_2_url'] ?? '');
    $button_2_type = $conn->real_escape_string($_POST['button_2_type'] ?? 'secondary');
    $stat_1_number = isset($_POST['stat_1_number']) ? intval($_POST['stat_1_number']) : 0;
    $stat_1_label = $conn->real_escape_string($_POST['stat_1_label'] ?? '');
    $stat_2_number = isset($_POST['stat_2_number']) ? intval($_POST['stat_2_number']) : 0;
    $stat_2_label = $conn->real_escape_string($_POST['stat_2_label'] ?? '');
    $stat_3_number = isset($_POST['stat_3_number']) ? intval($_POST['stat_3_number']) : 0;
    $stat_3_label = $conn->real_escape_string($_POST['stat_3_label'] ?? '');
    $slide_order = isset($_POST['slide_order']) ? intval($_POST['slide_order']) : 1;
    $is_active = isset($_POST['is_active']) ? intval($_POST['is_active']) : 1;
    
    // Handle background image upload
    $slide_bg_image = '';
    $bg_image_result = handleImageUpload('slide_bg_image');
    if (is_array($bg_image_result) && isset($bg_image_result['error'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Background image error: ' . $bg_image_result['error']]);
        exit();
    } elseif (is_array($bg_image_result) && isset($bg_image_result['filename'])) {
        $slide_bg_image = $bg_image_result['filename'];
    }
    
    // Handle hero image upload
    $slide_hero_image = '';
    $hero_image_result = handleImageUpload('slide_hero_image');
    if (is_array($hero_image_result) && isset($hero_image_result['error'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Hero image error: ' . $hero_image_result['error']]);
        exit();
    } elseif (is_array($hero_image_result) && isset($hero_image_result['filename'])) {
        $slide_hero_image = $hero_image_result['filename'];
    }
    
    // Validate required fields
    if (empty($title) || empty($description)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Title and description are required']);
        exit();
    }
    
    $query = "INSERT INTO hero_slider (title, description, badge, badge_icon, button_1_text, button_1_url, button_1_type, button_2_text, button_2_url, button_2_type, stat_1_number, stat_1_label, stat_2_number, stat_2_label, stat_3_number, stat_3_label, slide_bg_image, slide_hero_image, slide_order, is_active) 
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Prepare error: ' . $conn->error]);
        exit();
    }
    
    $stmt->bind_param('sssssssssssississiii', $title, $description, $badge, $badge_icon, $button_1_text, $button_1_url, $button_1_type, $button_2_text, $button_2_url, $button_2_type, $stat_1_number, $stat_1_label, $stat_2_number, $stat_2_label, $stat_3_number, $stat_3_label, $slide_bg_image, $slide_hero_image, $slide_order, $is_active);
    
    if ($stmt->execute()) {
        $id = $conn->insert_id;
        echo json_encode(['success' => true, 'message' => 'Slide added successfully', 'id' => $id]);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error adding slide: ' . $stmt->error]);
    }
    
    $stmt->close();
}

function editHeroSlide() {
    global $conn;
    
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid slide ID']);
        exit();
    }
    
    $title = $conn->real_escape_string($_POST['title'] ?? '');
    $description = $conn->real_escape_string($_POST['description'] ?? '');
    $badge = $conn->real_escape_string($_POST['badge'] ?? '');
    $badge_icon = $conn->real_escape_string($_POST['badge_icon'] ?? 'fa-star');
    $button_1_text = $conn->real_escape_string($_POST['button_1_text'] ?? '');
    $button_1_url = $conn->real_escape_string($_POST['button_1_url'] ?? '');
    $button_1_type = $conn->real_escape_string($_POST['button_1_type'] ?? 'primary');
    $button_2_text = $conn->real_escape_string($_POST['button_2_text'] ?? '');
    $button_2_url = $conn->real_escape_string($_POST['button_2_url'] ?? '');
    $button_2_type = $conn->real_escape_string($_POST['button_2_type'] ?? 'secondary');
    $stat_1_number = isset($_POST['stat_1_number']) ? intval($_POST['stat_1_number']) : 0;
    $stat_1_label = $conn->real_escape_string($_POST['stat_1_label'] ?? '');
    $stat_2_number = isset($_POST['stat_2_number']) ? intval($_POST['stat_2_number']) : 0;
    $stat_2_label = $conn->real_escape_string($_POST['stat_2_label'] ?? '');
    $stat_3_number = isset($_POST['stat_3_number']) ? intval($_POST['stat_3_number']) : 0;
    $stat_3_label = $conn->real_escape_string($_POST['stat_3_label'] ?? '');
    $slide_order = isset($_POST['slide_order']) ? intval($_POST['slide_order']) : 1;
    $is_active = isset($_POST['is_active']) ? intval($_POST['is_active']) : 1;
    
    // Handle background image upload
    $slide_bg_image = null;
    $bg_image_result = handleImageUpload('slide_bg_image');
    if (is_array($bg_image_result) && isset($bg_image_result['error'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Background image error: ' . $bg_image_result['error']]);
        exit();
    } elseif (is_array($bg_image_result) && isset($bg_image_result['filename'])) {
        $slide_bg_image = $bg_image_result['filename'];
    }
    
    // Handle hero image upload
    $slide_hero_image = null;
    $hero_image_result = handleImageUpload('slide_hero_image');
    if (is_array($hero_image_result) && isset($hero_image_result['error'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Hero image error: ' . $hero_image_result['error']]);
        exit();
    } elseif (is_array($hero_image_result) && isset($hero_image_result['filename'])) {
        $slide_hero_image = $hero_image_result['filename'];
    }
    
    // Validate required fields
    if (empty($title) || empty($description)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Title and description are required']);
        exit();
    }
    
    // Build update query based on which images are being updated
    $updateFields = [];
    $updateFields[] = 'title=?';
    $updateFields[] = 'description=?';
    $updateFields[] = 'badge=?';
    $updateFields[] = 'badge_icon=?';
    $updateFields[] = 'button_1_text=?';
    $updateFields[] = 'button_1_url=?';
    $updateFields[] = 'button_1_type=?';
    $updateFields[] = 'button_2_text=?';
    $updateFields[] = 'button_2_url=?';
    $updateFields[] = 'button_2_type=?';
    $updateFields[] = 'stat_1_number=?';
    $updateFields[] = 'stat_1_label=?';
    $updateFields[] = 'stat_2_number=?';
    $updateFields[] = 'stat_2_label=?';
    $updateFields[] = 'stat_3_number=?';
    $updateFields[] = 'stat_3_label=?';
    
    // Delete old images if new ones are being uploaded
    if ($slide_bg_image !== null) {
        $updateFields[] = 'slide_bg_image=?';
        $old_result = $conn->query("SELECT slide_bg_image FROM hero_slider WHERE id=$id");
        if ($old_result && $row = $old_result->fetch_assoc()) {
            if (!empty($row['slide_bg_image'])) {
                $old_path = 'assets/uploads/hero-slider/' . $row['slide_bg_image'];
                if (file_exists($old_path)) {
                    unlink($old_path);
                }
            }
        }
    }
    
    if ($slide_hero_image !== null) {
        $updateFields[] = 'slide_hero_image=?';
        $old_result = $conn->query("SELECT slide_hero_image FROM hero_slider WHERE id=$id");
        if ($old_result && $row = $old_result->fetch_assoc()) {
            if (!empty($row['slide_hero_image'])) {
                $old_path = 'assets/uploads/hero-slider/' . $row['slide_hero_image'];
                if (file_exists($old_path)) {
                    unlink($old_path);
                }
            }
        }
    }
    
    $updateFields[] = 'slide_order=?';
    $updateFields[] = 'is_active=?';
    
    $query = "UPDATE hero_slider SET " . implode(', ', $updateFields) . " WHERE id=?";
    
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Prepare error: ' . $conn->error]);
        exit();
    }
    
    // Build bind_param string and values array
    $bindTypes = 'sssssssssssissi';
    $values = [$title, $description, $badge, $badge_icon, $button_1_text, $button_1_url, $button_1_type, $button_2_text, $button_2_url, $button_2_type, $stat_1_number, $stat_1_label, $stat_2_number, $stat_2_label, $stat_3_number, $stat_3_label];
    
    if ($slide_bg_image !== null) {
        $bindTypes .= 's';
        $values[] = $slide_bg_image;
    }
    
    if ($slide_hero_image !== null) {
        $bindTypes .= 's';
        $values[] = $slide_hero_image;
    }
    
    $bindTypes .= 'ii';
    $values[] = $slide_order;
    $values[] = $is_active;
    $values[] = $id;
    
    // Call bind_param with dynamic values
    $stmt->bind_param($bindTypes, ...$values);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Slide updated successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error updating slide: ' . $stmt->error]);
    }
    
    $stmt->close();
}

function deleteHeroSlide() {
    global $conn;
    
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid slide ID']);
        exit();
    }
    
    // Get both image paths before deleting
    $result = $conn->query("SELECT slide_bg_image, slide_hero_image FROM hero_slider WHERE id=$id");
    if ($result && $row = $result->fetch_assoc()) {
        // Delete background image
        if (!empty($row['slide_bg_image'])) {
            $image_path = 'assets/uploads/hero-slider/' . $row['slide_bg_image'];
            if (file_exists($image_path)) {
                unlink($image_path);
            }
        }
        
        // Delete hero image
        if (!empty($row['slide_hero_image'])) {
            $image_path = 'assets/uploads/hero-slider/' . $row['slide_hero_image'];
            if (file_exists($image_path)) {
                unlink($image_path);
            }
        }
    }
    
    $query = "DELETE FROM hero_slider WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Slide deleted successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error deleting slide: ' . $stmt->error]);
    }
    
    $stmt->close();
}

function reorderSlides() {
    global $conn;
    
    $slides = $_POST['slides'] ?? [];
    
    if (empty($slides)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'No slides provided']);
        exit();
    }
    
    foreach ($slides as $index => $id) {
        $id = intval($id);
        $order = $index + 1;
        
        $query = "UPDATE hero_slider SET slide_order = ? WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('ii', $order, $id);
        $stmt->execute();
        $stmt->close();
    }
    
    echo json_encode(['success' => true, 'message' => 'Slides reordered successfully']);
}
?>
