<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include __DIR__ . '/../inc/db.php'; // Adjust path if necessary

header('Content-Type: application/json');

// Ensure that both action and customer_id are set
if (isset($_POST['action']) && $_POST['action'] === 'fetch_inquiry_details' && isset($_POST['customer_id'])) {
    $customer_id = $_POST['customer_id'];

    // Check if the customer ID is a valid number
    if (is_numeric($customer_id) && $customer_id > 0) {
        
        // Fetch the inquiry details for the selected customer
        $stmt = $conn->prepare("SELECT i.* FROM inquiries i JOIN customers c ON i.customer_id = c.id WHERE i.customer_id = ? AND i.followup_status = 'done' ORDER BY i.id DESC LIMIT 1");
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $inquiry = $result->fetch_assoc();
            $inquiry['inquiry_id'] = $inquiry['id'];
            unset($inquiry['id']);
            // Return inquiry details in JSON format
            $response = [
                'status' => 'success',
                'data' => $inquiry
            ];
        } else {
            $response = ['status' => 'error', 'message' => 'No inquiry details found for this customer.'];
        }
        
        // Return response as JSON
        echo json_encode($response);
    } else {
        // Handle invalid customer_id
        echo json_encode(['status' => 'error', 'message' => 'Invalid customer ID']);
    }
} else {
    // Handle missing action or customer_id
    echo json_encode(['status' => 'error', 'message' => 'Missing action or customer_id']);
}
exit;
