<?php
/**
 * Service Quote API
 * Returns service details and associated products/pricing for quote modal
 */
session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../config/db.php';

$serviceId = isset($_GET['service_id']) ? intval($_GET['service_id']) : 0;

if ($serviceId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid service ID']);
    exit;
}

// Fetch service info
$stmt = $connection->prepare("SELECT id, title, image, description, price, area_sqft, duration, status FROM services WHERE id = ? AND is_active = 1");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit;
}

$stmt->bind_param('i', $serviceId);
$stmt->execute();
$result = $stmt->get_result();

if (!$result || $result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Service not found']);
    exit;
}

$service = $result->fetch_assoc();
$stmt->close();

// Fetch associated products
$products = [];
$productStmt = $connection->prepare("SELECT id, product_name, cost, quantity FROM service_products WHERE service_id = ? ORDER BY sort_order ASC, id ASC");
if ($productStmt) {
    $productStmt->bind_param('i', $serviceId);
    $productStmt->execute();
    $productResult = $productStmt->get_result();
    while ($row = $productResult->fetch_assoc()) {
        $products[] = [
            'id' => (int)$row['id'],
            'product_name' => $row['product_name'],
            'cost' => floatval($row['cost']),
            'quantity' => $row['quantity']
        ];
    }
    $productStmt->close();
}

// Fetch tools
$tools = [];
$toolStmt = $connection->prepare("SELECT id, tool_name, tool_description FROM service_tools WHERE service_id = ? ORDER BY id ASC");
if ($toolStmt) {
    $toolStmt->bind_param('i', $serviceId);
    $toolStmt->execute();
    $toolResult = $toolStmt->get_result();
    while ($row = $toolResult->fetch_assoc()) {
        $tools[] = [
            'id' => (int)$row['id'],
            'tool_name' => $row['tool_name'],
            'tool_description' => $row['tool_description']
        ];
    }
    $toolStmt->close();
}

// Calculate totals
$totalProductCost = 0;
foreach ($products as $p) {
    $qty = is_numeric($p['quantity']) ? floatval($p['quantity']) : 1;
    $totalProductCost += $p['cost'] * $qty;
}

echo json_encode([
    'success' => true,
    'service' => [
        'id' => (int)$service['id'],
        'title' => $service['title'],
        'image' => $service['image'],
        'description' => $service['description'],
        'price' => floatval($service['price'] ?? 0),
        'area_sqft' => intval($service['area_sqft'] ?? 0),
        'duration' => $service['duration'] ?? '',
        'status' => $service['status'] ?? 'ACTIVE'
    ],
    'products' => $products,
    'tools' => $tools,
    'total_product_cost' => $totalProductCost,
    'product_count' => count($products)
]);
