<?php
require_once 'functions.php';

$message = '';
$error = '';

// Get all clients for dropdown
$clients = getAllClients();

// Get company data for auto-filling issuer
$pdo = getDBConnection();
$company_data = null;
$stmt = $pdo->query("SELECT * FROM company_data LIMIT 1");
$company_data = $stmt->fetch(PDO::FETCH_ASSOC);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $offer_number = sanitizeInput($_POST['offer_number']);
    $issuer = sanitizeInput($_POST['issuer']);
    $recipient = sanitizeInput($_POST['recipient']);
    $offer_date = $_POST['offer_date'];
    
    // Validate required fields
    $validation_error = validateRequired([
        'Номер на офертата' => $offer_number,
        'Издател' => $issuer,
        'Получател' => $recipient,
        'Дата на офертата' => $offer_date
    ]);
    
    if ($validation_error) {
        $error = $validation_error;
    } elseif (!isOfferNumberUnique($offer_number)) {
        $error = "Номерът на офертата вече съществува.";
    } else {
        // Create offer
        $offer_id = addOffer($offer_number, $issuer, $recipient, $offer_date);
        
        if ($offer_id) {
            // Add offer items
            $articles = getAllArticles();
            $total_amount = 0;
            
            foreach ($articles as $article) {
				$image_key = 'image_' . $article['product_id'];
                $quantity_key = 'quantity_' . $article['product_id'];
                $unit_key = 'unit_' . $article['product_id'];
                $price_key = 'price_' . $article['product_id'];
                
                if (isset($_POST[$quantity_key]) && $_POST[$quantity_key] > 0) {
					$image = ($_POST[$image_key]);
                    $quantity = (float)$_POST[$quantity_key];
                    $unit = sanitizeInput($_POST[$unit_key]);
                    $price_per_unit = (float)$_POST[$price_key];
                    
                    if ($quantity > 0 && $price_per_unit >= 0) {
                        addOfferItem($offer_id, $article['product_id'], $image, $quantity, $unit, $price_per_unit);
                        $total_amount += $quantity * $price_per_unit;
                    }
                }
            }
            
            // Update total amount
            updateOfferTotalAmount($offer_id);
            
            $message = "Офертата беше създадена успешно.";
            header('Location: offers.php'); 
			
            // Clear form data
            $_POST = array();
        } else {
            $error = "Грешка при създаване на офертата.";
        }
    }
}

// Generate default offer number
$default_offer_number = generateOfferNumber();

$articles = getAllArticles();
$category = getCat();
?>

<!DOCTYPE html>
<html lang="bg">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Нова оферта - Протоколи за влагане на материали</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="date"], input[type="number"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .article-item {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr 1fr;
            gap: 10px;
            align-items: center;
            padding: 10px;
            border: 1px solid #eee;
            margin-bottom: 10px;
            border-radius: 4px;
            background-color: white;
        }
        .article-name {
            font-weight: bold;
        }
        .btn {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            margin: 5px;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-success {
            background-color: #28a745;
        }
        .btn-success:hover {
            background-color: #218838;
        }
        .btn-secondary {
            background-color: #6c757d;
        }
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid transparent;
            border-radius: 4px;
        }
        .alert-success {
            color: #155724;
            background-color: #d4edda;
            border-color: #c3e6cb;
        }
        .alert-danger {
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }
        @media (max-width: 768px) {
            .nav {
                flex-direction: column;
                align-items: center;
            }
            .article-item {
                grid-template-columns: 1fr;
                gap: 5px;
            }
            .container {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">

<?php
include_once 'header.php';
?>

        <?php if ($message): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-section">
                <h3></h3>
                
                <div class="form-group">
                    <label for="offer_number">Номер на офертата:</label>
                    <input type="text" id="offer_number" name="offer_number" value="<?php echo isset($_POST['offer_number']) ? htmlspecialchars($_POST['offer_number']) : $default_offer_number; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="issuer">Издател:</label>
                    <input type="text" id="issuer" name="issuer" 
                           value="<?php echo isset($_POST['issuer']) ? htmlspecialchars($_POST['issuer']) : ($company_data ? htmlspecialchars($company_data['company_name']) : ''); ?>" required>
                    <?php if ($company_data): ?>
                        <small style="color: #666;">Автоматично попълнено от настройките на фирмата</small>
                    <?php endif; ?>
                </div>
                
                <div class="form-group">
                    <label for="client_select">Избор на клиент:</label>
                    <select id="client_select" name="client_select" onchange="fillClientData()">
                        <option value="">-- Изберете клиент или въведете ръчно --</option>
                        <?php foreach ($clients as $client): ?>
                            <option value="<?php echo $client['id']; ?>" 
                                    data-name="<?php echo htmlspecialchars($client['name']); ?>"
                                    data-address="<?php echo htmlspecialchars($client['address']); ?>"
                                    data-phone="<?php echo htmlspecialchars($client['phone']); ?>"
                                    data-email="<?php echo htmlspecialchars($client['email']); ?>">
                                <strong> <?php echo htmlspecialchars($client['name']); ?> </strong>, <?php echo htmlspecialchars($client['address']); ?> (<?php echo htmlspecialchars($client['phone']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="recipient">Получател:</label>
                    <input type="text" id="recipient" name="recipient" value="<?php echo isset($_POST['recipient']) ? htmlspecialchars($_POST['recipient']) : ''; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="offer_date">Дата на офертата:</label>
                    <input type="date" id="offer_date" name="offer_date"  value="<?php echo isset($_POST['offer_date']) ? $_POST['offer_date'] : date('Y-m-d'); ?>" required>
                </div>
            </div>
			


            <div class="form-section">
                <h3></h3>
                
                <div class="form-group">
                    <label for="article_select">Избор на артикул:</label>
                    <select id="article_select" onchange="addArticleToOffer()">
                        <option value="">-- Изберете артикул за добавяне --</option>
                        <?php foreach ($articles as $article): ?>
                            <option value="<?php echo $article['product_id']; ?>" 
                                    data-name="<?php echo htmlspecialchars($article['name']); ?>"
									data-image="<?php echo htmlspecialchars($article['image']); ?>"
                                    data-unit="<?php echo htmlspecialchars($article['unit']); ?>"
                                    data-price="<?php echo number_format($article['price'], 2, '.', ''); ?>">
                                <?php echo htmlspecialchars($article['model']); ?> / <?php echo htmlspecialchars($article['name']); ?> - <?php echo number_format($article['price'], 2, '.', ''); ?> лв.
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div id="selected-articles">
                    <h4>Избрани артикули:</h4>
                    <div id="articles-list"></div>
                </div>
            </div>

            <button type="submit" class="btn btn-success">Създай оферта</button>
            <a href="offers.php" class="btn btn-secondary">Отказ</a>
        </form>
    </div>

    <script>
        let selectedArticles = [];
        
        function fillClientData() {
            const select = document.getElementById('client_select');
            const selectedOption = select.options[select.selectedIndex];
            
            if (selectedOption.value) {
                // Fill recipient field with client name
                document.getElementById('recipient').value = selectedOption.getAttribute('data-name');
            } else {
                // Clear recipient field if no client selected
                document.getElementById('recipient').value = '';
            }
        }
        
        function addArticleToOffer() {
            const select = document.getElementById('article_select');
            const selectedOption = select.options[select.selectedIndex];
            
            if (selectedOption.value) {
                const articleId = selectedOption.value;
                const articleName = selectedOption.getAttribute('data-name');
				const articleImage = selectedOption.getAttribute('data-image');
                const articleUnit = selectedOption.getAttribute('data-unit');
                const articlePrice = selectedOption.getAttribute('data-price');
                
                // Check if article is already added
                if (selectedArticles.find(a => a.id === articleId)) {
                    alert('Този артикул вече е добавен!');
                    return;
                }
                
                // Add to selected articles array
                selectedArticles.push({
                    id: articleId,
                    name: articleName,
					image: articleImage,
                    unit: articleUnit,
                    price: articlePrice
                });
                
                // Update display
                updateArticlesList();
                
                // Reset select
                select.selectedIndex = 0;
            }
        }
			
        function updateArticlesList() {
            const container = document.getElementById('articles-list');
            container.innerHTML = '';
            
            selectedArticles.forEach((article, index) => {
                const articleDiv = document.createElement('div');
                articleDiv.className = 'article-item';
                articleDiv.innerHTML = `
                    <div class="article-name">
                        ${article.name}
                        <button type="button" onclick="removeArticle(${index})" style="margin-left: 10px; background: #dc3545; color: white; border: none; padding: 2px 8px; border-radius: 3px;">Премахни</button>
                    </div>
                    <div>
					<input type="hidden" name="image_${article.id}" value="${article.image}">
					    <img src="${article.image}" style="width: 150px;" >
                    </div>
                    <div>
                        <label>Кол.:</label>
                        <input type="number" name="quantity_${article.id}" step="1" min="0" required>
                    </div>
                        <input type="hidden" name="unit_${article.id}" value="бр.">
            
                    <div>
                        <label>Ед. Цена:</label>
                        <input type="number" name="price_${article.id}" step="0.01" min="0" value="${article.price}">
                    </div>
                `;
                container.appendChild(articleDiv);
            });
        }
        
        function removeArticle(index) {
            selectedArticles.splice(index, 1);
            updateArticlesList();
        }
    </script>
</body>
</html>

