<?php
/**
 * admin_manage_testimonials.php: Admin endpoint to manage testimonials
 * Supports: GET (list), POST (create), PUT (update), DELETE (delete)
 */

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
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;
}

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireAdmin(true);

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

function respond($success, $message, $data = null, $code = 200) {
    http_response_code($code);
    $response = ['success' => $success, 'message' => $message];
    if ($data !== null) $response['data'] = $data;
    echo json_encode($response);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$data = json_decode(file_get_contents('php://input'), true);

try {
    // Ensure testimonials table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS testimonials (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        quote TEXT NOT NULL,
        avatar VARCHAR(50) DEFAULT '👤',
        rating INT DEFAULT 5,
        status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_status (status),
        INDEX idx_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    switch ($method) {
        case 'GET':
            // List all testimonials (admin view, includes pending)
            $status = $_GET['status'] ?? null;
            $sql = "SELECT * FROM testimonials";
            if ($status) {
                $sql .= " WHERE status = :status";
            }
            $sql .= " ORDER BY created_at DESC";
            
            $stmt = $pdo->prepare($sql);
            if ($status) {
                $stmt->bindParam(':status', $status);
            }
            $stmt->execute();
            $testimonials = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            respond(true, 'Testimonials retrieved', ['testimonials' => $testimonials, 'count' => count($testimonials)]);
            break;

        case 'POST':
            // Create new testimonial
            if (!isset($data['name']) || !isset($data['quote'])) {
                respond(false, 'Name and quote are required', null, 400);
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO testimonials (name, quote, avatar, rating, status) 
                VALUES (:name, :quote, :avatar, :rating, :status)
            ");
            $stmt->execute([
                ':name' => trim($data['name']),
                ':quote' => trim($data['quote']),
                ':avatar' => $data['avatar'] ?? '👤',
                ':rating' => isset($data['rating']) ? intval($data['rating']) : 5,
                ':status' => $data['status'] ?? 'approved'
            ]);
            
            respond(true, 'Testimonial created successfully', ['id' => $pdo->lastInsertId()]);
            break;

        case 'PUT':
            // Update existing testimonial
            if (!isset($data['id'])) {
                respond(false, 'Testimonial ID is required', null, 400);
            }
            
            $updateFields = [];
            $params = [':id' => intval($data['id'])];
            
            if (isset($data['name'])) {
                $updateFields[] = 'name = :name';
                $params[':name'] = trim($data['name']);
            }
            if (isset($data['quote'])) {
                $updateFields[] = 'quote = :quote';
                $params[':quote'] = trim($data['quote']);
            }
            if (isset($data['avatar'])) {
                $updateFields[] = 'avatar = :avatar';
                $params[':avatar'] = $data['avatar'];
            }
            if (isset($data['rating'])) {
                $updateFields[] = 'rating = :rating';
                $params[':rating'] = intval($data['rating']);
            }
            if (isset($data['status'])) {
                $updateFields[] = 'status = :status';
                $params[':status'] = $data['status'];
            }
            
            if (empty($updateFields)) {
                respond(false, 'No fields to update', null, 400);
            }
            
            $sql = "UPDATE testimonials SET " . implode(', ', $updateFields) . " WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            respond(true, 'Testimonial updated successfully');
            break;

        case 'DELETE':
            // Delete testimonial
            if (!isset($data['id'])) {
                respond(false, 'Testimonial ID is required', null, 400);
            }
            
            $stmt = $pdo->prepare("DELETE FROM testimonials WHERE id = :id");
            $stmt->execute([':id' => intval($data['id'])]);
            
            respond(true, 'Testimonial deleted successfully');
            break;

        default:
            respond(false, 'Method not allowed', null, 405);
    }
} catch (Exception $e) {
    error_log('Admin testimonials error: ' . $e->getMessage());
    respond(false, 'An error occurred: ' . $e->getMessage(), null, 500);
}
