<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) { jsonResponse(false, 'Unauthorized', [], 401); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonResponse(false, 'Invalid method.'); }

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) { jsonResponse(false, 'Invalid CSRF token.'); }

$db = Database::getInstance();
$action = $_POST['action'] ?? 'save';
$testId = (int) ($_POST['testimonial_id'] ?? 0);

if ($action === 'delete') {
    $db->delete('testimonials', 'id = ?', [$testId]);
    jsonResponse(true, 'Testimonial deleted.');
}

$name = trim($_POST['name'] ?? '');
$content = trim($_POST['content'] ?? '');
if (empty($name) || empty($content)) { jsonResponse(false, 'Name and content are required.'); }

$upload = new Upload();
$imagePath = null;
if (!empty($_FILES['image']['name'])) {
    $result = $upload->uploadFile($_FILES['image'], 'testimonials');
    if ($result['success']) {
        $imagePath = $result['path'];
    } else {
        jsonResponse(false, 'Image upload failed: ' . implode(', ', $result['errors']));
    }
}

$data = [
    'name' => $name,
    'restaurant_name' => trim($_POST['restaurant_name'] ?? ''),
    'role' => trim($_POST['role'] ?? ''),
    'content' => $content,
    'rating' => (int) ($_POST['rating'] ?? 5),
    'is_active' => isset($_POST['is_active']) ? 1 : 0,
    'sort_order' => (int) ($_POST['sort_order'] ?? 0),
];

if ($imagePath) { $data['image'] = $imagePath; }

if ($testId > 0) {
    $data['updated_at'] = date('Y-m-d H:i:s');
    $db->update('testimonials', $data, 'id = ?', [$testId]);
    jsonResponse(true, 'Testimonial updated.');
} else {
    $data['created_at'] = date('Y-m-d H:i:s');
    $db->insert('testimonials', $data);
    jsonResponse(true, 'Testimonial created.');
}
