<?php
/**
 * Rig N Dig - Mobile API v1 / Submit RFQ
 */
header('Content-Type: application/json');
require_once '../../../config/config.php';
require_once '../../../includes/functions.php';
require_once '../api_helper.php';

$user = authenticateAPI();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    apiResponse(false, 'Invalid request method.');
}

// Expecting a JSON body or POST fields
$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

$notes = sanitize($input['notes'] ?? '');
$items = $input['items'] ?? []; // Array of {product_id, quantity, notes}

if (empty($items)) {
    apiResponse(false, 'No products provided for RFQ');
}

try {
    // Generate quote number
    $quoteNum = generateNumber(setting('quote_prefix', 'RFQ-'), 'quotations', 'quote_number');
    $validUntil = date('Y-m-d', strtotime('+30 days'));

    // Create quotation record
    $quoteId = Database::insert(
        "INSERT INTO quotations (quote_number, customer_id, notes, valid_until, status) VALUES (?,?,?,'pending')",
        [$quoteNum, $user['id'], $notes, $validUntil]
    );

    $insertedCount = 0;
    foreach ($items as $item) {
        $pId = (int)($item['product_id'] ?? 0);
        $qty = (int)($item['quantity'] ?? 1);
        $iNotes = sanitize($item['notes'] ?? '');
        
        if ($pId <= 0) continue;

        $p = Database::fetchOne("SELECT name FROM products WHERE id = ?", [$pId]);
        if (!$p) continue;

        Database::insert(
            "INSERT INTO quotation_items (quotation_id, product_id, description, quantity, notes) VALUES (?,?,?,?,?)",
            [$quoteId, $pId, $p['name'], $qty, $iNotes]
        );
        $insertedCount++;
    }

    if ($insertedCount === 0) {
        // Rollback or just error
        Database::execute("DELETE FROM quotations WHERE id = ?", [$quoteId]);
        apiResponse(false, 'Failed to add items to quotation');
    }

    logActivity('customer', $user['id'], 'API RFQ Submitted', "Quote #$quoteNum");
    
    // Optional: Send Email
    sendEmailFromTemplate('rfq_received', $user['email'], [
        'customer_name' => $user['contact_name'], 
        'quote_number' => $quoteNum
    ]);

    apiResponse(true, 'RFQ submitted successfully', [
        'quote_id' => $quoteId,
        'quote_number' => $quoteNum
    ]);

} catch (Exception $e) {
    apiResponse(false, 'Failed to submit RFQ: ' . $e->getMessage());
}
