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

// Check if user is logged in and is staff
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'staff') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Get JSON input
$data = json_decode(file_get_contents('php://input'), true);

if (!$data || !isset($data['inquiry_id']) || !isset($data['response'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$inquiry_id = intval($data['inquiry_id']);
$response = $data['response'];
$staff_id = $_SESSION['user_id'];

if (!$response || strlen(trim($response)) < 3) {
    echo json_encode(['success' => false, 'message' => 'Response must be at least 3 characters']);
    exit;
}

try {
    // Update inquiry with staff response
    $stmt = $conn->prepare("
        UPDATE inquiries 
        SET response = ?, status = 'responded', updated_at = NOW()
        WHERE id = ?
    ");
    
    $stmt->bind_param('si', $response, $inquiry_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Response sent successfully']);
    } else {
        throw new Exception('Failed to update inquiry');
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
