<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'config.php';

function check_input($par) {
    $par = trim($par);
    $par = stripslashes($par);
    $par = htmlspecialchars($par);
    return $par;
}

$response = [];
$data = [];
$suc = "Success";

try {
    // Check if database connection is valid
    if ($con->connect_error) {
        throw new Exception("Database connection failed: " . $con->connect_error);
    }

    // Query to fetch testimonials
    $sql = "SELECT * FROM testimonials ORDER BY id DESC LIMIT 50";
    $result = $con->query($sql);

    if ($result && $result->num_rows > 0) {
        // Fetch testimonials and store in data array
        while ($rows = mysqli_fetch_assoc($result)) {
            $data[] = $rows;
        }
    } else {
        $suc = "No Testimonials";
        $data = []; // Return an empty array for no results
    }
} catch (Exception $e) {
    $suc = "Error: Server error - " . $e->getMessage();
    $data = []; // Return an empty array in case of error
}

// Close the database connection
if (isset($con) && $con !== null) {
    $con->close();
}

// JSON response
$response = [
    'success' => $suc,
    'data' => $data,
];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($response);
?>
