<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

$input = hw_input_json();
$type = $input['type'] ?? '';
$items = $input['items'] ?? [];

if (!in_array($type, ['membership', 'product', 'appointment'])) {
    hw_json(['success' => false, 'message' => 'Invalid invoice type'], 422);
}

if (empty($items) || !is_array($items)) {
    hw_json(['success' => false, 'message' => 'Invoice items are required'], 422);
}

try {
    $pdo = hw_db();
    $pdo->beginTransaction();
    
    // Calculate totals
    $subtotal = 0;
    foreach ($items as $item) {
        $subtotal += ($item['quantity'] ?? 1) * ($item['unit_price'] ?? 0);
    }
    
    $taxRate = 0.08; // 8% tax
    $taxAmount = $subtotal * $taxRate;
    $totalAmount = $subtotal + $taxAmount;
    
    // Generate invoice number
    $invoiceNumber = 'INV-' . date('Y') . '-' . str_pad((string)rand(1000, 9999), 4, '0', STR_PAD_LEFT);
    
    // Create invoice
    $stmt = $pdo->prepare("
        INSERT INTO invoices (user_id, invoice_number, type, subtotal, tax_amount, total_amount, due_date) 
        VALUES (?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 30 DAY))
    ");
    $stmt->execute([
        (int)$user['sub'],
        $invoiceNumber,
        $type,
        $subtotal,
        $taxAmount,
        $totalAmount
    ]);
    $invoiceId = (int)$pdo->lastInsertId();
    
    // Add invoice items
    foreach ($items as $item) {
        $quantity = (int)($item['quantity'] ?? 1);
        $unitPrice = (float)($item['unit_price'] ?? 0);
        $totalPrice = $quantity * $unitPrice;
        
        $stmt = $pdo->prepare("
            INSERT INTO invoice_items (invoice_id, description, quantity, unit_price, total_price) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $invoiceId,
            $item['description'] ?? 'Item',
            $quantity,
            $unitPrice,
            $totalPrice
        ]);
    }
    
    // Audit log
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("invoice_id", ?, "amount", ?))')
        ->execute([(int)$user['sub'], 'invoice_created', $invoiceId, $totalAmount]);
    
    $pdo->commit();
    
    hw_json([
        'success' => true,
        'invoice_id' => $invoiceId,
        'invoice_number' => $invoiceNumber,
        'total_amount' => $totalAmount
    ]);
} catch (Throwable $e) {
    $pdo->rollBack();
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}