<?php
require_once 'functions.php';

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $name = sanitizeInput($_POST['name']);
				$image = sanitizeInput($_POST['name'].".jpg");
                $unit = sanitizeInput($_POST['unit']);
                $price = (float)$_POST['price'];
                
                $validation_error = validateRequired(['Име' => $name, 'Мерна единица' => $unit]);
                if ($validation_error) {
                    $error = $validation_error;
                } elseif ($price < 0) {
                    $error = "Цената не може да бъде отрицателна.";
                } else {
                    if (addArticle($name, $image, $unit, $price)) {
                        $message = "Артикулът беше добавен успешно.";
                    } else {
                        $error = "Грешка при добавяне на артикула.";
                    }
                }
                break;
                
            case 'update':
                $id = (int)$_POST['id'];
                $name = sanitizeInput($_POST['name']);
				$image = ($_POST['name']. '.jpg');
                $unit = sanitizeInput($_POST['unit']);
                $price = (float)$_POST['price'];
                
                $validation_error = validateRequired(['Име' => $name, 'Мерна единица' => $unit]);
                if ($validation_error) {
                    $error = $validation_error;
                } elseif ($price < 0) {
                    $error = "Цената не може да бъде отрицателна.";
                } else {
                    if (updateArticle($id, $name, $image, $unit, $price)) {
                        $message = "Артикулът беше обновен успешно.";
                    } else {
                        $error = "Грешка при обновяване на артикула.";
                    }
                }
                break;
                
            case 'delete':
                $id = (int)$_POST['id'];
                if (deleteArticle($id)) {
                    $message = "Артикулът беше изтрит успешно.";
                } else {
                    $error = "Грешка при изтриване на артикула.";
                }
                break;
        }
    }
}

// Get article for editing
$edit_article = null;
if (isset($_GET['edit'])) {
    $edit_article = getArticleById((int)$_GET['edit']);
}

$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;
        }

        .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"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .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-danger {
            background-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
        }
        .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;
            }
            table {
                font-size: 14px;
            }
            .container {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
          
      <?php
   include_once 'header.php';
   ?>
        
        <?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; ?>
        
        <div class="form-container">
            <h3><?php echo $edit_article ? 'Редактиране на артикул' : 'Добавяне на нов артикул'; ?></h3>
            <form method="POST">
                <input type="hidden" name="action" value="<?php echo $edit_article ? 'update' : 'add'; ?>">
                <?php if ($edit_article): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_article['id']; ?>">
                <?php endif; ?>
                
                <div class="form-group">
                    <label for="name">Име на артикула:</label>
                    <input type="text" id="name" name="name" value="<?php echo $edit_article ? htmlspecialchars($edit_article['name']) : ''; ?>" required>
                </div>
				<input type="hidden" id="image" name="image" value="<?php echo $edit_article ? htmlspecialchars($edit_article['name']) : ''; ?>" required>
           
	            <div class="form-group">
                    <label for="unit">Мерна единица:</label>
                    <input type="text" id="unit" name="unit" value="<?php echo $edit_article ? htmlspecialchars($edit_article['unit']) : ''; ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="price">Цена (лв.):</label>
                    <input type="number" id="price" name="price" step="0.01" min="0" value="<?php echo $edit_article ? number_format($edit_article['price'], 2, '.', '') : '0.00'; ?>" required>
                </div>
                
                <button type="submit" class="btn btn-success">
                    <?php echo $edit_article ? 'Обнови артикул' : 'Добави артикул'; ?>
                </button>
				  <a href="articles.php" class="btn">Отказ</a>
				
				
                <?php if ($edit_article): ?>
                    <a href="articles.php" class="btn">Отказ</a>
                <?php endif; ?>
            </form>
        </div>
        