<?php
/**
 * get_testimonials.php: Returns approved testimonials for public display
 * Public endpoint - no authentication required
 */

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once 'config.php';
require_once 'db.php';

try {
    // Check if testimonials table exists
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'testimonials'");
    
    if ($tableCheck && $tableCheck->rowCount() > 0) {
        // Fetch approved testimonials, ordered by created_at descending (newest first)
        $stmt = $pdo->prepare("
            SELECT 
                id, 
                name, 
                quote, 
                avatar, 
                rating,
                created_at 
            FROM testimonials 
            WHERE status = 'approved' 
            ORDER BY created_at DESC 
            LIMIT 20
        ");
        $stmt->execute();
        $testimonials = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Format the response
        echo json_encode([
            "success" => true, 
            "testimonials" => $testimonials,
            "count" => count($testimonials)
        ]);
    } else {
        // Table doesn't exist, return empty array with note
        echo json_encode([
            "success" => true, 
            "testimonials" => [],
            "count" => 0,
            "note" => "Testimonials table not yet created. Run migrations or create testimonials via admin panel."
        ]);
    }
} catch (Exception $e) {
    error_log("Error fetching testimonials: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "error" => "Failed to fetch testimonials",
        "testimonials" => [],
        "count" => 0
    ]);
}
