<?php
require_once '../config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendResponse(false, 'Only GET method allowed', null, 405);
}

try {
    $user = validateToken($conn);
    
    $customer_id = intval($_GET['customer_id'] ?? 0);
    $type = sanitizeInput($_GET['type'] ?? 'permanent'); // 'permanent' or 'temporary'
    
    if (empty($customer_id)) {
        sendResponse(false, 'Customer ID is required', null, 400);
    }
    
    $table = ($type === 'temporary') ? 'customers' : 'permanentcustomer';
    
    // Get customer details
    $stmt = $conn->prepare("SELECT * FROM $table WHERE id = ?");
    $stmt->bind_param("i", $customer_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($customer = $result->fetch_assoc()) {
        // Get customer's orders/invoices if any
        $orderStmt = $conn->prepare("SELECT * FROM invoices WHERE customer_id = ? AND customer_type = ? ORDER BY created_at DESC");
        $orderStmt->bind_param("is", $customer_id, $type);
        $orderStmt->execute();
        $orderResult = $orderStmt->get_result();
        
        $orders = [];
        while ($order = $orderResult->fetch_assoc()) {
            $orders[] = $order;
        }
        
        $customer['orders'] = $orders;
        $customer['total_orders'] = count($orders);
        
        sendResponse(true, 'Customer details retrieved successfully', $customer);
    } else {
        sendResponse(false, 'Customer not found', null, 404);
    }
    
    $stmt->close();
} catch (Exception $e) {
    sendResponse(false, 'Failed to get customer details: ' . $e->getMessage(), null, 500);
}
?>
