<?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_id']) || !isset($_POST['page_name']) || !isset($_POST['link']) || !isset($_POST['icon'])) {
        throw new Exception('Missing required fields');
    }

    // Sanitize inputs
    $pageId = $conn->real_escape_string(trim($_POST['page_id']));
    $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($pageId) || empty($pageName) || empty($link) || empty($icon)) {
        throw new Exception('All fields are required');
    }

    // Update database record
    $query = "UPDATE pages SET page_name = '$pageName', link = '$link', icon = '$icon' WHERE page_id = '$pageId'";
    if ($conn->query($query)) {
        $response = [
            'success' => true,
            'message' => 'Page updated 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);
}
?>