<?php
header('Content-Type: application/json');
require_once '../config.php';

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

// Ensure hero_sliders table exists
$create_table_sql = "CREATE TABLE IF NOT EXISTS hero_sliders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tag VARCHAR(100) NOT NULL,
    title VARCHAR(255) NOT NULL,
    subtitle TEXT NOT NULL,
    button1_text VARCHAR(100),
    button1_url VARCHAR(255),
    button2_text VARCHAR(100),
    button2_url VARCHAR(255),
    image_url VARCHAR(255),
    stat1_icon VARCHAR(100),
    stat1_text VARCHAR(255),
    stat2_icon VARCHAR(100),
    stat2_text VARCHAR(255),
    display_order INT DEFAULT 0,
    status ENUM('active', 'inactive') DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";

$conn->query($create_table_sql);

$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');

if ($action === 'get_all') {
    // Get all hero sliders
    $result = $conn->query("SELECT * FROM hero_sliders ORDER BY display_order ASC");
    $sliders = [];
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $sliders[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'sliders' => $sliders]);

} elseif ($action === 'add') {
    // Add new hero slider
    $tag = $conn->real_escape_string($_POST['tag'] ?? '');
    $title = $conn->real_escape_string($_POST['title'] ?? '');
    $subtitle = $conn->real_escape_string($_POST['subtitle'] ?? '');
    $button1_text = $conn->real_escape_string($_POST['button1_text'] ?? '');
    $button1_url = $conn->real_escape_string($_POST['button1_url'] ?? '');
    $button2_text = $conn->real_escape_string($_POST['button2_text'] ?? '');
    $button2_url = $conn->real_escape_string($_POST['button2_url'] ?? '');
    $image_url = $conn->real_escape_string($_POST['image_url'] ?? '');
    $stat1_icon = $conn->real_escape_string($_POST['stat1_icon'] ?? '');
    $stat1_text = $conn->real_escape_string($_POST['stat1_text'] ?? '');
    $stat2_icon = $conn->real_escape_string($_POST['stat2_icon'] ?? '');
    $stat2_text = $conn->real_escape_string($_POST['stat2_text'] ?? '');
    $display_order = intval($_POST['display_order'] ?? 0);
    $status = ($_POST['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active';

    if (!$title || !$subtitle) {
        echo json_encode(['success' => false, 'message' => 'Title and subtitle are required']);
        exit;
    }

    $sql = "INSERT INTO hero_sliders 
            (tag, title, subtitle, button1_text, button1_url, button2_text, button2_url, image_url, stat1_icon, stat1_text, stat2_icon, stat2_text, display_order, status) 
            VALUES ('$tag', '$title', '$subtitle', '$button1_text', '$button1_url', '$button2_text', '$button2_url', '$image_url', '$stat1_icon', '$stat1_text', '$stat2_icon', '$stat2_text', $display_order, '$status')";

    if ($conn->query($sql) === TRUE) {
        $new_id = $conn->insert_id;
        
        // Get the newly created slider
        $result = $conn->query("SELECT * FROM hero_sliders WHERE id = $new_id");
        $new_slider = $result->fetch_assoc();
        
        echo json_encode(['success' => true, 'message' => 'Hero slider added successfully', 'slider' => $new_slider]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $conn->error]);
    }

} elseif ($action === 'update') {
    // Update hero slider
    $id = intval($_POST['id'] ?? 0);
    
    if (!$id) {
        echo json_encode(['success' => false, 'message' => 'ID is required']);
        exit;
    }

    $tag = $conn->real_escape_string($_POST['tag'] ?? '');
    $title = $conn->real_escape_string($_POST['title'] ?? '');
    $subtitle = $conn->real_escape_string($_POST['subtitle'] ?? '');
    $button1_text = $conn->real_escape_string($_POST['button1_text'] ?? '');
    $button1_url = $conn->real_escape_string($_POST['button1_url'] ?? '');
    $button2_text = $conn->real_escape_string($_POST['button2_text'] ?? '');
    $button2_url = $conn->real_escape_string($_POST['button2_url'] ?? '');
    $image_url = $conn->real_escape_string($_POST['image_url'] ?? '');
    $stat1_icon = $conn->real_escape_string($_POST['stat1_icon'] ?? '');
    $stat1_text = $conn->real_escape_string($_POST['stat1_text'] ?? '');
    $stat2_icon = $conn->real_escape_string($_POST['stat2_icon'] ?? '');
    $stat2_text = $conn->real_escape_string($_POST['stat2_text'] ?? '');
    $display_order = intval($_POST['display_order'] ?? 0);
    $status = ($_POST['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active';

    if (!$title || !$subtitle) {
        echo json_encode(['success' => false, 'message' => 'Title and subtitle are required']);
        exit;
    }

    $sql = "UPDATE hero_sliders SET 
            tag='$tag', title='$title', subtitle='$subtitle', button1_text='$button1_text', button1_url='$button1_url',
            button2_text='$button2_text', button2_url='$button2_url', image_url='$image_url', stat1_icon='$stat1_icon',
            stat1_text='$stat1_text', stat2_icon='$stat2_icon', stat2_text='$stat2_text', display_order=$display_order, status='$status'
            WHERE id=$id";

    if ($conn->query($sql) === TRUE) {
        // Get the updated slider
        $result = $conn->query("SELECT * FROM hero_sliders WHERE id = $id");
        $updated_slider = $result->fetch_assoc();
        
        echo json_encode(['success' => true, 'message' => 'Hero slider updated successfully', 'slider' => $updated_slider]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $conn->error]);
    }

} elseif ($action === 'delete') {
    // Delete hero slider
    $id = intval($_POST['id'] ?? $_GET['id'] ?? 0);
    
    if (!$id) {
        echo json_encode(['success' => false, 'message' => 'ID is required']);
        exit;
    }

    $sql = "DELETE FROM hero_sliders WHERE id=$id";

    if ($conn->query($sql) === TRUE) {
        echo json_encode(['success' => true, 'message' => 'Hero slider deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $conn->error]);
    }

} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
