<?php
session_start();
require_once 'config.php';

// Get request method
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

// Handle different actions
switch ($action) {
    case 'get_all':
        getSliders();
        break;
    case 'get':
        getSlider();
        break;
    case 'create':
        createSlider();
        break;
    case 'update':
        updateSlider();
        break;
    case 'delete':
        deleteSlider();
        break;
    case 'reorder':
        reorderSliders();
        break;
    case 'upload_image':
        uploadSliderImage();
        break;
    default:
        if ($method === 'GET') {
            getSliders();
        } else {
            sendResponse(false, 'Invalid action');
        }
}

// Get all sliders
function getSliders() {
    global $conn;
    $query = "SELECT * FROM sliders ORDER BY display_order ASC";
    $result = $conn->query($query);
    
    if (!$result) {
        sendResponse(false, 'Database error: ' . $conn->error);
    }
    
    $sliders = [];
    while ($row = $result->fetch_assoc()) {
        $sliders[] = $row;
    }
    
    sendResponse(true, 'Sliders retrieved successfully', $sliders);
}

// Get single slider
function getSlider() {
    global $conn;
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$id) {
        sendResponse(false, 'Slider ID is required');
    }
    
    $stmt = $conn->prepare("SELECT * FROM sliders WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Slider not found');
    }
    
    $slider = $result->fetch_assoc();
    sendResponse(true, 'Slider retrieved successfully', $slider);
}

// Create new slider
function createSlider() {
    global $conn;
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    if (!isset($data['image_path']) || !isset($data['headline'])) {
        sendResponse(false, 'Image path and headline are required');
    }
    
    $image_path = $data['image_path'];
    $subheadline = $data['subheadline'] ?? '';
    $headline = $data['headline'];
    $description = $data['description'] ?? '';
    $button_text = $data['button_text'] ?? '';
    $button_link = $data['button_link'] ?? '#';
    $button_style = $data['button_style'] ?? 'btn--primary';
    $display_order = $data['display_order'] ?? 0;
    $is_active = $data['is_active'] ?? 1;
    
    // Get highest display_order if not provided
    if ($display_order === 0) {
        $result = $conn->query("SELECT MAX(display_order) as max_order FROM sliders");
        $row = $result->fetch_assoc();
        $display_order = ($row['max_order'] ?? 0) + 1;
    }
    
    $stmt = $conn->prepare("INSERT INTO sliders (image_path, subheadline, headline, description, button_text, button_link, button_style, display_order, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssssii", $image_path, $subheadline, $headline, $description, $button_text, $button_link, $button_style, $display_order, $is_active);
    
    if ($stmt->execute()) {
        $new_id = $conn->insert_id;
        sendResponse(true, 'Slider created successfully', ['id' => $new_id]);
    } else {
        sendResponse(false, 'Error creating slider: ' . $stmt->error);
    }
}

// Update slider
function updateSlider() {
    global $conn;
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $data['id'] ?? 0;
    
    if (!$id) {
        sendResponse(false, 'Slider ID is required');
    }
    
    $image_path = $data['image_path'] ?? null;
    $subheadline = $data['subheadline'] ?? null;
    $headline = $data['headline'] ?? null;
    $description = $data['description'] ?? null;
    $button_text = $data['button_text'] ?? null;
    $button_link = $data['button_link'] ?? null;
    $button_style = $data['button_style'] ?? null;
    $display_order = $data['display_order'] ?? null;
    $is_active = $data['is_active'] ?? null;
    
    $updates = [];
    $params = [];
    
    if ($image_path !== null) {
        $updates[] = "image_path = ?";
        $params[] = $image_path;
    }
    if ($subheadline !== null) {
        $updates[] = "subheadline = ?";
        $params[] = $subheadline;
    }
    if ($headline !== null) {
        $updates[] = "headline = ?";
        $params[] = $headline;
    }
    if ($description !== null) {
        $updates[] = "description = ?";
        $params[] = $description;
    }
    if ($button_text !== null) {
        $updates[] = "button_text = ?";
        $params[] = $button_text;
    }
    if ($button_link !== null) {
        $updates[] = "button_link = ?";
        $params[] = $button_link;
    }
    if ($button_style !== null) {
        $updates[] = "button_style = ?";
        $params[] = $button_style;
    }
    if ($display_order !== null) {
        $updates[] = "display_order = ?";
        $params[] = $display_order;
    }
    if ($is_active !== null) {
        $updates[] = "is_active = ?";
        $params[] = $is_active;
    }
    
    if (empty($updates)) {
        sendResponse(false, 'No fields to update');
    }
    
    $params[] = $id;
    $query = "UPDATE sliders SET " . implode(", ", $updates) . " WHERE id = ?";
    
    $stmt = $conn->prepare($query);
    
    // Build type string dynamically
    $types = str_repeat('s', count($updates) - count(array_filter([$display_order, $is_active], function($v) { return $v !== null; }))) . 
             str_repeat('i', count(array_filter([$display_order, $is_active], function($v) { return $v !== null; }))) . 'i';
    
    $stmt->bind_param($types, ...$params);
    
    if ($stmt->execute()) {
        sendResponse(true, 'Slider updated successfully');
    } else {
        sendResponse(false, 'Error updating slider: ' . $stmt->error);
    }
}

// Delete slider
function deleteSlider() {
    global $conn;
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $data['id'] ?? 0;
    
    if (!$id) {
        sendResponse(false, 'Slider ID is required');
    }
    
    // Get the image path before deleting
    $stmt = $conn->prepare("SELECT image_path FROM sliders WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Slider not found');
    }
    
    $slider = $result->fetch_assoc();
    
    // Delete the slider
    $stmt = $conn->prepare("DELETE FROM sliders WHERE id = ?");
    $stmt->bind_param("i", $id);
    
    if ($stmt->execute()) {
        // Try to delete the image file if it's a custom upload
        if (strpos($slider['image_path'], 'uploads/sliders/') !== false) {
            $file_path = realpath('../' . $slider['image_path']);
            if ($file_path && file_exists($file_path)) {
                unlink($file_path);
            }
        }
        sendResponse(true, 'Slider deleted successfully');
    } else {
        sendResponse(false, 'Error deleting slider: ' . $stmt->error);
    }
}

// Reorder sliders
function reorderSliders() {
    global $conn;
    $data = json_decode(file_get_contents('php://input'), true);
    $orders = $data['orders'] ?? [];
    
    if (empty($orders)) {
        sendResponse(false, 'Orders data is required');
    }
    
    $conn->begin_transaction();
    
    try {
        foreach ($orders as $order) {
            $id = intval($order['id']);
            $display_order = intval($order['display_order']);
            
            $stmt = $conn->prepare("UPDATE sliders SET display_order = ? WHERE id = ?");
            $stmt->bind_param("ii", $display_order, $id);
            
            if (!$stmt->execute()) {
                throw new Exception('Error updating order');
            }
        }
        
        $conn->commit();
        sendResponse(true, 'Sliders reordered successfully');
    } catch (Exception $e) {
        $conn->rollback();
        sendResponse(false, 'Error reordering sliders: ' . $e->getMessage());
    }
}

// Upload slider image
function uploadSliderImage() {
    // Check if file was uploaded
    if (!isset($_FILES['image'])) {
        sendResponse(false, 'No image file provided');
    }
    
    $file = $_FILES['image'];
    $maxFileSize = 5 * 1024 * 1024; // 5MB
    
    // Validate file
    if ($file['error'] !== UPLOAD_ERR_OK) {
        sendResponse(false, 'File upload error: ' . $file['error']);
    }
    
    if ($file['size'] > $maxFileSize) {
        sendResponse(false, 'File size exceeds maximum allowed size (5MB)');
    }
    
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if (!in_array($file_ext, $allowed_extensions)) {
        sendResponse(false, 'Invalid file type. Allowed types: ' . implode(', ', $allowed_extensions));
    }
    
    // Create upload directory if it doesn't exist
    $upload_dir = '../assets/uploads/sliders/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    // Generate unique filename
    $filename = 'slider_' . time() . '_' . uniqid() . '.' . $file_ext;
    $file_path = $upload_dir . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $file_path)) {
        // Return the relative path
        sendResponse(true, 'Image uploaded successfully', ['path' => 'assets/uploads/sliders/' . $filename]);
    } else {
        sendResponse(false, 'Error moving uploaded file');
    }
}
?>
