<?php
/**
 * Testimonials Endpoints
 */

$db = Database::getInstance()->getConnection();

// GET approved testimonials (public)
if ($method === 'GET' && !$id) {
    $stmt = $db->query("SELECT id, full_name, location, message, image_path, created_at FROM testimonials WHERE status = 'approved' ORDER BY created_at DESC");
    jsonResponse($stmt->fetchAll());
}

// GET all testimonials (admin)
if ($method === 'GET' && $id === 'all') {
    requireAuth();
    $stmt = $db->query("SELECT * FROM testimonials ORDER BY created_at DESC");
    jsonResponse($stmt->fetchAll());
}

// POST submit testimonial (public)
if ($method === 'POST' && !$id) {
    $input = getJsonInput();
    $errors = validateRequired($input, ['full_name', 'location', 'message']);
    if (!empty($errors)) {
        jsonResponse(['error' => implode(', ', $errors)], 400);
    }

    $testimonialId = generateUuid();
    $stmt = $db->prepare("INSERT INTO testimonials (id, full_name, location, message, image_path, status, created_at) VALUES (?, ?, ?, ?, ?, 'pending', NOW())");
    $stmt->execute([
        $testimonialId,
        sanitizeString($input['full_name']),
        sanitizeString($input['location']),
        sanitizeString($input['message']),
        isset($input['image_path']) ? $input['image_path'] : null
    ]);
    jsonResponse(['message' => 'Testimonial submitted successfully', 'id' => $testimonialId], 201);
}

// PUT approve/deny/edit testimonial (admin)
if ($method === 'PUT' && $id) {
    requireAuth();
    $input = getJsonInput();
    $updates = [];
    $params = [];

    if (isset($input['status']) && in_array($input['status'], ['pending', 'approved', 'denied'])) {
        $updates[] = 'status = ?';
        $params[] = $input['status'];
    }
    if (isset($input['full_name'])) { $updates[] = 'full_name = ?'; $params[] = sanitizeString($input['full_name']); }
    if (isset($input['location']))  { $updates[] = 'location = ?';  $params[] = sanitizeString($input['location']); }
    if (isset($input['message']))   { $updates[] = 'message = ?';   $params[] = sanitizeString($input['message']); }

    if (empty($updates)) jsonResponse(['error' => 'No fields to update'], 400);

    $params[] = $id;
    $stmt = $db->prepare('UPDATE testimonials SET ' . implode(', ', $updates) . ' WHERE id = ?');
    $stmt->execute($params);

    $stmt = $db->prepare('SELECT * FROM testimonials WHERE id = ?');
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch());
}

// DELETE testimonial (admin)
if ($method === 'DELETE' && $id) {
    requireAuth();
    $stmt = $db->prepare('DELETE FROM testimonials WHERE id = ?');
    $stmt->execute([$id]);
    if ($stmt->rowCount() === 0) jsonResponse(['error' => 'Testimonial not found'], 404);
    jsonResponse(['message' => 'Testimonial deleted']);
}


// POST upload testimonial image (public) - rate limited per IP to prevent
// unauthenticated storage/bandwidth abuse (this endpoint has no login requirement).
if ($method === "POST" && $id === "upload") {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $limitRow = $db->prepare("SELECT upload_count, window_start FROM upload_rate_limits WHERE ip_address = ?");
    $limitRow->execute([$ip]);
    $limit = $limitRow->fetch();

    $windowFresh = $limit && (strtotime($limit['window_start']) > time() - 3600);
    if ($windowFresh && (int)$limit['upload_count'] >= 5) {
        jsonResponse(["error" => "Too many uploads. Please try again later."], 429);
    }

    if (!isset($_FILES["file"])) jsonResponse(["error" => "No file uploaded"], 400);
    $result = handleImageUpload($_FILES["file"]);
    if (isset($result['error'])) jsonResponse(["error" => $result['error']], $result['status']);

    if ($windowFresh) {
        $db->prepare("UPDATE upload_rate_limits SET upload_count = upload_count + 1 WHERE ip_address = ?")->execute([$ip]);
    } else {
        $db->prepare("REPLACE INTO upload_rate_limits (ip_address, upload_count, window_start) VALUES (?, 1, NOW())")->execute([$ip]);
    }

    jsonResponse(["url" => $result['url']]);
}

jsonResponse(['error' => 'Invalid testimonials endpoint'], 404);
