<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

// Authenticate
api_authenticate();

// Support JSON POST bodies
if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') === 0) {
    $input = json_decode(file_get_contents('php://input'), true);
    if (is_array($input)) {
        $_POST = array_merge($_POST, $input);
    }
}

// Get ticket_id, user_email, and message
$ticket_id = (int) ($_POST['ticket_id'] ?? 0);
$user_email_raw = $_POST['user_email'] ?? '';
$message = $_POST['message'] ?? '';
if ($ticket_id < 1 || !$user_email_raw || $message === '') {
    echo json_encode(['success' => false, 'error' => 'Missing required fields']);
    exit;
}
$email_validation = validateEmail($user_email_raw);
if (!$email_validation['valid']) {
    echo json_encode(['success' => false, 'error' => 'Invalid user_email', 'email_errors' => $email_validation['errors']]);
    exit;
}
$user_email = $email_validation['sanitized'];
$message = function_exists('cleanHTML') ? cleanHTML($message) : sanitizeInput($message);

// Lookup user_id if user_email matches a user
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$user_email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$user_id = $user ? (int) $user['id'] : null;

// Security: Verify ticket ownership (align with ticket_view / tickets_list)
$stmt_check = $pdo->prepare("SELECT id FROM tickets WHERE id = ? AND (email = ? OR user_id = (SELECT id FROM users WHERE email = ? LIMIT 1))");
$stmt_check->execute([$ticket_id, $user_email, $user_email]);
if (!$stmt_check->fetch()) {
    echo json_encode(['success' => false, 'error' => 'Ticket not found or permission denied']);
    exit;
}

// Insert reply
$stmt = $pdo->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message) VALUES (?, ?, ?)");
$stmt->execute([$ticket_id, $user_id, $message]);
$reply_id = $pdo->lastInsertId();

// Update ticket's updated_at
$stmt = $pdo->prepare("UPDATE tickets SET updated_at = NOW() WHERE id = ?");
$stmt->execute([$ticket_id]);

echo json_encode(['success' => true, 'reply_id' => $reply_id]); 