<?php
require_once 'shikanisha.kts.php';

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

try {
    // Check if this is a POST request
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    // Validate required fields exist in POST data
    if (!isset($_POST['page_name']) || !isset($_POST['link']) || !isset($_POST['icon'])) {
        throw new Exception('Missing required fields');
    }

    // Sanitize inputs
    $pageName = $conn->real_escape_string(trim($_POST['page_name']));
    $link = $conn->real_escape_string(trim($_POST['link']));
    $icon = $conn->real_escape_string(trim($_POST['icon']));

    // Validate non-empty values
    if (empty($pageName) || empty($link) || empty($icon)) {
        throw new Exception('All fields are required');
    }

    // Insert into database
    $query = "INSERT INTO pages (page_name, link, icon) VALUES ('$pageName', '$link', '$icon')";
    if ($conn->query($query)) {
        $response = [
            'success' => true,
            'page_id' => $conn->insert_id,
            'message' => 'Page added successfully'
        ];
    } else {
        throw new Exception('Database error: ' . $conn->error);
    }
} catch (Exception $e) {
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
} finally {
    // Close connection and send response
    if (isset($conn)) $conn->close();
    echo json_encode($response);
}
?>