<?php
/**
 * MSPE Testimonials API
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;

switch ($method) {
    case 'GET':
        if ($id) {
            getTestimonial($id);
        } else {
            getTestimonials();
        }
        break;
        
    case 'POST':
        requireAuth();
        $postData = !empty($_POST) ? $_POST : getRequestBody();
        if (!empty($postData['id'])) {
            updateTestimonial($postData['id']);
        } else {
            createTestimonial();
        }
        break;
        
    case 'PUT':
        requireAuth();
        if (!$id) {
            jsonResponse(['success' => false, 'message' => 'Testimonial ID required'], 400);
        }
        updateTestimonial($id);
        break;
        
    case 'DELETE':
        requireAuth();
        if (!$id) {
            jsonResponse(['success' => false, 'message' => 'ID required'], 400);
        }
        deleteTestimonial($id);
        break;
        
    default:
        jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
}

function getTestimonials() {
    global $db;
    $items = $db->getAll('testimonials');
    
    // Filters
    $status = $_GET['status'] ?? null;
    if ($status) {
        $items = array_filter($items, function($i) use ($status) {
            return $i['status'] === $status;
        });
    }
    
    // Sort by date (newest first)
    usort($items, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    // Public view: only published
    if (!checkAuth()) {
        $items = array_filter($items, function($i) {
            return ($i['status'] ?? 'draft') === 'published';
        });
    }
    
    jsonResponse(['success' => true, 'data' => array_values($items)]);
}

function getTestimonial($id) {
    global $db;
    $item = $db->get('testimonials', $id);
    if (!$item) jsonResponse(['success' => false, 'message' => 'Not found'], 404);
    jsonResponse(['success' => true, 'data' => $item]);
}

function createTestimonial() {
    global $db;
    $data = !empty($_POST) ? $_POST : getRequestBody();
    
    if (empty($data['name']) || empty($data['text'])) {
        jsonResponse(['success' => false, 'message' => 'Name and Text are required'], 400);
    }
    
    // Sanitize text fields
    $data['name'] = sanitize($data['name']);
    $data['company'] = sanitize($data['company'] ?? '');
    $data['role'] = sanitize($data['role'] ?? '');
    $data['text'] = sanitize($data['text']);
    
    // Image upload
    if (!empty($_FILES['photo'])) {
        $upload = handleFileUpload($_FILES['photo'], 'testimonials');
        if ($upload['success']) {
            $data['photo'] = $upload['path'];
        }
    }
    
    $data['status'] = $data['status'] ?? 'pending';
    $data['rating'] = (float)($data['rating'] ?? 5);
    
    $item = $db->insert('testimonials', $data);
    jsonResponse(['success' => true, 'message' => 'Testimonial added', 'data' => $item]);
}

function updateTestimonial($id) {
    global $db;
    $existing = $db->get('testimonials', $id);
    if (!$existing) jsonResponse(['success' => false, 'message' => 'Not found'], 404);
    
    $data = !empty($_POST) ? $_POST : getRequestBody();
    
    if (!empty($_FILES['photo'])) {
        $upload = handleFileUpload($_FILES['photo'], 'testimonials');
        if ($upload['success']) {
            $data['photo'] = $upload['path'];
        }
    }
    
    // Sanitize editable text fields
    if (isset($data['name'])) $data['name'] = sanitize($data['name']);
    if (isset($data['company'])) $data['company'] = sanitize($data['company']);
    if (isset($data['role'])) $data['role'] = sanitize($data['role']);
    if (isset($data['text'])) $data['text'] = sanitize($data['text']);

    $item = $db->update('testimonials', $id, $data);
    jsonResponse(['success' => true, 'message' => 'Testimonial updated', 'data' => $item]);
}

function deleteTestimonial($id) {
    global $db;
    $db->delete('testimonials', $id);
    jsonResponse(['success' => true, 'message' => 'Testimonial deleted']);
}
