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

// Auto Create Table if not exists
$createTableSQL = "
CREATE TABLE IF NOT EXISTS imagesliders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    image_url TEXT NOT NULL,
    activity_link TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
$conn->query($createTableSQL);

// Read type
$type = isset($_POST['type']) ? $_POST['type'] : 'add';

if ($type === 'delete') {

    // 🔹 Delete slider by ID
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM imagesliders WHERE id = ?");
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Slider deleted successfully."]);
        } else {
            echo json_encode(["success" => false, "error" => "Failed to delete slider."]);
        }

        $stmt->close();
    } else {
        echo json_encode(["success" => false, "error" => "Missing or invalid ID."]);
    }

} elseif ($type === 'edit') {

    // 🔹 Update slider info by ID
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $image_url = isset($_POST['image_url']) ? $_POST['image_url'] : '';
    $activity_link = isset($_POST['activity_link']) ? $_POST['activity_link'] : '';

    if ($id > 0 && !empty($image_url) && !empty($activity_link)) {
        $stmt = $conn->prepare("UPDATE imagesliders SET image_url = ?, activity_link = ? WHERE id = ?");
        $stmt->bind_param("ssi", $image_url, $activity_link, $id);

        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Slider updated successfully."]);
        } else {
            echo json_encode(["success" => false, "error" => "Failed to update slider."]);
        }

        $stmt->close();
    } else {
        echo json_encode(["success" => false, "error" => "Missing ID, image_url, or activity_link."]);
    }

} else {

    // 🔹 Default: Add new slider
    $image_url = isset($_POST['image_url']) ? $_POST['image_url'] : '';
    $activity_link = isset($_POST['activity_link']) ? $_POST['activity_link'] : '';

    if (!empty($image_url) && !empty($activity_link)) {
        $stmt = $conn->prepare("INSERT INTO imagesliders (image_url, activity_link) VALUES (?, ?)");
        $stmt->bind_param("ss", $image_url, $activity_link);

        if ($stmt->execute()) {
            echo json_encode(["success" => true, "message" => "Slider added successfully."]);
        } else {
            echo json_encode(["success" => false, "error" => "Failed to insert data."]);
        }

        $stmt->close();
    } else {
        echo json_encode(["success" => false, "error" => "Missing image_url or activity_link."]);
    }
}

$conn->close();
?>