<?php
/**
 * Broker - Manage Leads (Respond to Inquiries)
 * POST: Allows broker to respond to customer inquiries
 */

header('Content-Type: application/json');
require_once '../../config.php';
require_once __DIR__ . '/broker-identity.php';

$session_role = $_SESSION['role'] ?? ($_SESSION['user_role'] ?? '');
if (!isset($_SESSION['user_id']) || $session_role !== 'broker') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$session_broker_id = (int)$_SESSION['user_id'];
$brokerCtx = resolveBrokerContext($conn, $session_broker_id);
$broker_id = (int)$brokerCtx['property_broker_id'];
$fallback_broker_id = $session_broker_id !== $broker_id ? $session_broker_id : 0;
$data = json_decode(file_get_contents('php://input'), true);

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

$inquiry_id = (int)$data['inquiry_id'];
$action = $data['action']; // 'respond', 'convert', 'disqualify'
$response_message = $data['response'] ?? null;

try {
    // Verify broker owns this inquiry
    $stmt = $conn->prepare("
        SELECT i.id
        FROM inquiries i
        JOIN properties p ON p.id = i.property_id
        WHERE i.id = ? AND (
            i.assigned_to = ?
            OR i.broker_id = ?
            OR (? > 0 AND i.broker_id = ?)
            OR p.broker_id = ?
            OR (? > 0 AND p.broker_id = ?)
        )
        LIMIT 1
    ");
    $stmt->bind_param('iiiiiiii', $inquiry_id, $session_broker_id, $broker_id, $fallback_broker_id, $fallback_broker_id, $broker_id, $fallback_broker_id, $fallback_broker_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Inquiry not found']);
        $stmt->close();
        exit;
    }
    $stmt->close();

    if ($action === 'respond') {
        if (!$response_message) {
            echo json_encode(['success' => false, 'message' => 'Response message required']);
            exit;
        }
        $stmt = $conn->prepare("UPDATE inquiries SET status = 'responded', message = ? WHERE id = ?");
        $stmt->bind_param('si', $response_message, $inquiry_id);
        $stmt->execute();
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Inquiry response sent']);
    } 
    else if ($action === 'convert') {
        $stmt = $conn->prepare("UPDATE inquiries SET status = 'approved' WHERE id = ?");
        $stmt->bind_param('i', $inquiry_id);
        $stmt->execute();
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Lead converted']);
    } 
    else if ($action === 'disqualify') {
        $stmt = $conn->prepare("UPDATE inquiries SET status = 'declined' WHERE id = ?");
        $stmt->bind_param('i', $inquiry_id);
        $stmt->execute();
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Lead disqualified']);
    }
    else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
