<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'db_config.php';

if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection failed"]);
    exit();
}

$id = $_POST['id'] ?? null;
$headline = $_POST['headline'] ?? '';
$details = $_POST['details'] ?? '';

try {
    if ($id) {
        $stmt = $pdo->prepare("UPDATE notes SET headline=?, details=? WHERE id=?");
        $stmt->execute([$headline, $details, $id]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO notes (headline, details) VALUES (?, ?)");
        $stmt->execute([$headline, $details]);
    }
    echo json_encode(["status" => "success", "message" => "Operation successful"]);
} catch (PDOException $e) {
    echo json_encode(["status" => "error", "message" => "Database error: " . $e->getMessage()]);
}
?>
