<?php
require_once 'functions.php';

// Get all clients and articles for dropdowns
$clients = getAllClients();
$articles = getAllArticles();
// $protocol_types = getProtocolTypes();

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

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $issuer = sanitizeInput($_POST['issuer']);
    $executor = sanitizeInput($_POST['executor']);
    $protocol_date = sanitizeInput($_POST['protocol_date']);
   // $protocol_type = sanitizeInput($_POST['protocol_type']);
    
    $validation_error = validateRequired([
        'Възложител' => $issuer,
        'Изпълнител' => $executor,
        'Дата на протокола' => $protocol_date,
     //   'Тип протокол' => $protocol_type
    ]);
    
    if ($validation_error) {
        $error = $validation_error;
    } else {
        // Validate that at least one article is selected
        $has_articles = false;
        if (isset($_POST['articles']) && is_array($_POST['articles'])) {
            foreach ($_POST['articles'] as $article_id => $data) {
                if (!empty($data['quantity']) && $data['quantity'] > 0) {
                    $has_articles = true;
                    break;
                }
            }
        }
        
        if (!$has_articles) {
            $error = "Моля, добавете поне един артикул с количество.";
        } else {
            // Create protocol
            $protocol_id = addProtocolWithType($issuer, $executor, $protocol_date);
            
            if ($protocol_id) {
                // Add protocol items
                $items_added = 0;
                foreach ($_POST['articles'] as $article_id => $data) {
                    if (!empty($data['quantity']) && $data['quantity'] > 0) {
                        $quantity = (float)$data['quantity'];
                        $unit = sanitizeInput($data['unit']);
                        
                        if (addProtocolItem($protocol_id, $article_id, $quantity, $unit)) {
                            $items_added++;
                        }
                    }
                }
                
                if ($items_added > 0) {
                    $message = "Протоколът беше създаден успешно с $items_added артикула.";
                    // Clear form data
                    $_POST = array();
                } else {
                    $error = "Протоколът беше създаден, но не бяха добавени артикули.";
                }
            } else {
                $error = "Грешка при създаване на протокола.";
            }
        }
    }
}

$articles = getAllArticles();
?>

<!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;
        }
        .nav {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        .nav a {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        .nav a:hover {
            background-color: #0056b3;
        }
        .nav a.active {
            background-color: #28a745;
        }
        .form-container {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 30px;
        }
        .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;
        }
        .articles-section {
            margin-top: 30px;
        }
        .article-item {
            background-color: #fff;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 5px;
        }
        .article-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        .article-name {
            flex: 2;
            min-width: 200px;
            font-weight: bold;
        }
        .quantity-input {
            flex: 1;
            min-width: 100px;
        }
        .unit-input {
            flex: 1;
            min-width: 100px;
        }
        .btn {
            background-color: #007bff;
            color: white;
            padding: 8px 16px;
            text-decoration: none;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            margin: 2px;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-success {
            background-color: #28a745;
        }
        .btn-success:hover {
            background-color: #218838;
        }
        .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-row {
                flex-direction: column;
                align-items: stretch;
            }
            .container {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Създаване на нов протокол</h1>
        
        <div class="nav">
            <a href="index.php">Начало</a>
            <a href="articles.php">Управление на артикули</a>
            <a href="protocols.php">Протоколи</a>
            <a href="add_protocol.php" class="active">Нов протокол</a>
            <a href="offers.php">Оферти</a>
            <a href="clients.php">Клиенти</a>
            <a href="company_settings.php">Настройки на фирмата</a>
        </div>
        
        <?php if ($message): ?>
            <div class="alert alert-success"><?php echo $message; ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <form method="POST">
            <div class="form-container">
                <h3>Основна информация за протокола</h3>
                
                <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']); ?>">
                                <?php echo htmlspecialchars($client['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </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']) : ''; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="executor">Изпълнител:</label>
                    <input type="text" id="executor" name="executor" 
                           value="<?php echo isset($_POST['executor']) ? htmlspecialchars($_POST['executor']) : ($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="protocol_date">Дата на протокола:</label>
                    <input type="date" id="protocol_date" name="protocol_date" value="<?php echo isset($_POST['protocol_date']) ? $_POST['protocol_date'] : date('Y-m-d'); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="protocol_type">Тип протокол:</label>
                   
                        <option value="">Изберете тип протокол</option>
                        <?php foreach ($protocol_types as $type): ?>
                            <option value="<?php echo htmlspecialchars($type); ?>" 
                                <?php echo (isset($_POST['protocol_type']) && $_POST['protocol_type'] == $type) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($type); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="articles-section">
                <h3>Артикули за влагане</h3>
                
                <div class="form-group">
                    <label for="article_select">Избор на артикул:</label>
                    <select id="article_select" onchange="addArticleToProtocol()">
                        <option value="">-- Изберете артикул за добавяне --</option>
                        <?php foreach ($articles as $article): ?>
                            <option value="<?php echo $article['id']; ?>" 
                                    data-name="<?php echo htmlspecialchars($article['name']); ?>"
                                    data-unit="<?php echo htmlspecialchars($article['unit']); ?>">
                                <?php echo htmlspecialchars($article['name']); ?> (<?php echo htmlspecialchars($article['unit']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div id="selected-articles">
                    <h4>Избрани артикули:</h4>
                    <div id="articles-list"></div>
                </div>
                
                <div style="text-align: center; margin-top: 30px;">
                    <button type="submit" class="btn btn-success">Създай протокол</button>
                    <a href="protocols.php" class="btn">Отказ</a>
                </div>
            </div>
        </form>
    </div>

    <script>
        let selectedArticles = [];
        
        function fillClientData() {
            const select = document.getElementById('client_select');
            const selectedOption = select.options[select.selectedIndex];
            
            if (selectedOption.value) {
                // Fill issuer field with client name
                document.getElementById('issuer').value = selectedOption.getAttribute('data-name');
            } else {
                // Clear issuer field if no client selected
                document.getElementById('issuer').value = '';
            }
        }
        
        function addArticleToProtocol() {
            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 articleUnit = selectedOption.getAttribute('data-unit');
                
                // 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,
                    unit: articleUnit
                });
                
                // 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-row">
                        <div class="article-name">
                            ${article.name} (${article.unit})
                            <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 class="quantity-input">
                            <label>Количество:</label>
                            <input type="number" name="articles[${article.id}][quantity]" step="0.01" min="0" required>
                        </div>
                        <div class="unit-input">
                            <label>Мерна единица:</label>
                            <input type="text" name="articles[${article.id}][unit]" value="${article.unit}">
                        </div>
                    </div>
                `;
                container.appendChild(articleDiv);
            });
        }
        
        function removeArticle(index) {
            selectedArticles.splice(index, 1);
            updateArticlesList();
        }
    </script>
</body>
</html>

