<?php
/**
 * Admin Add Product Page
 * Add new product form
 */

$pageTitle = 'Adaugă Produs';

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../../includes/Product.php';

$productObj = new Product();
$db = Database::getInstance();

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_product') {
    $name = $_POST['name'] ?? '';
    $sku = $_POST['sku'] ?? '';
    $price = floatval($_POST['price'] ?? 0);
    $salePrice = !empty($_POST['sale_price']) ? floatval($_POST['sale_price']) : null;
    $stockQuantity = intval($_POST['stock_quantity'] ?? 0);
    $categoryId = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
    $description = $_POST['description'] ?? '';
    $shortDescription = $_POST['short_description'] ?? '';
    $isActive = isset($_POST['is_active']) ? 1 : 0;
    $isGift = isset($_POST['is_gift']) ? 1 : 0;
    $supplierId = !empty($_POST['supplier_id']) ? intval($_POST['supplier_id']) : null;

    if ($name && $sku && $price > 0) {
        // Check if SKU already exists
        $existing = $db->fetchOne("SELECT id FROM products WHERE sku = ?", [$sku]);
        if ($existing) {
            $error = 'SKU-ul există deja!';
        } else {
            // Generate slug
            $slug = $productObj->generateSlug($name);
            
            // Handle image upload (simplified - just save filename for now)
            $image = '';
            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = __DIR__ . '/../../uploads/products/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                $filename = $slug . '-' . time() . '.' . $ext;
                $targetPath = $uploadDir . $filename;
                if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
                    $image = 'uploads/products/' . $filename;
                }
            }

            $db->execute(
                "INSERT INTO products (name, slug, sku, price, sale_price, stock_quantity, category_id, 
                 description, short_description, image, is_active, is_gift, supplier_id, created_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())",
                [$name, $slug, $sku, $price, $salePrice, $stockQuantity, $categoryId, 
                 $description, $shortDescription, $image, $isActive, $isGift, $supplierId]
            );

            $message = 'Produsul a fost adăugat cu succes!';
            // Clear form data
            $_POST = [];
        }
    } else {
        $error = 'Toate câmpurile obligatorii trebuie completate!';
    }
}

// Get categories for dropdown
$categories = $productObj->getCategories();

// Get suppliers for dropdown
$suppliers = $db->fetchAll("SELECT id, name FROM suppliers ORDER BY name");
?>

<div class="content">
  <div class="px-3 px-xxl-4 py-3 py-lg-4">
    <div class="card mb-3">
      <div class="card-body">
        <div class="row justify-content-between align-items-center">
          <div class="col-md">
            <h5 class="mb-2 mb-md-0">Adaugă produs nou</h5>
          </div>
          <div class="col-auto">
            <a href="/admin/produse" class="btn btn-link text-secondary p-0 me-3 fw-medium">Anulează</a>
            <button type="submit" form="productForm" class="btn btn-primary">Salvează produs</button>
          </div>
        </div>
      </div>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      <?php echo htmlspecialchars($message); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    <?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <?php echo htmlspecialchars($error); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <form id="productForm" method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="add_product">
      <div class="row g-0">
        <div class="col-lg-8 pe-lg-2">
          <div class="card mb-3">
            <div class="card-header bg-body-tertiary">
              <h6 class="mb-0">Informații de bază</h6>
            </div>
            <div class="card-body">
              <div class="row gx-2">
                <div class="col-12 mb-3">
                  <label class="form-label" for="product-name">Nume produs: <span class="text-danger">*</span></label>
                  <input class="form-control" id="product-name" name="name" type="text" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>" required />
                </div>
                <div class="col-12 mb-3">
                  <label class="form-label" for="product-sku">SKU (Cod produs): <span class="text-danger">*</span></label>
                  <input class="form-control" id="product-sku" name="sku" type="text" value="<?php echo htmlspecialchars($_POST['sku'] ?? ''); ?>" required />
                </div>
                <div class="col-12 mb-3">
                  <label class="form-label" for="product-short-description">Rezumat produs:</label>
                  <input class="form-control" id="product-short-description" name="short_description" type="text" value="<?php echo htmlspecialchars($_POST['short_description'] ?? ''); ?>" />
                </div>
              </div>
            </div>
          </div>
          <div class="card mb-3">
            <div class="card-header bg-body-tertiary">
              <h6 class="mb-0">Adaugă imagine</h6>
            </div>
            <div class="card-body">
              <div class="mb-3">
                <input type="file" class="form-control" name="image" accept="image/*" />
                <small class="text-600">Format acceptat: JPG, PNG, GIF. Dimensiune maximă: 5MB</small>
              </div>
            </div>
          </div>
          <div class="card mb-3">
            <div class="card-header bg-body-tertiary">
              <h6 class="mb-0">Descriere</h6>
            </div>
            <div class="card-body">
              <div class="row gx-2">
                <div class="col-12 mb-3">
                  <label class="form-label" for="product-description">Descriere produs:</label>
                  <textarea class="form-control" id="product-description" name="description" rows="6"><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-lg-4 ps-lg-2">
          <div class="sticky-sidebar">
            <div class="card mb-3">
              <div class="card-header bg-body-tertiary">
                <h6 class="mb-0">Categorie</h6>
              </div>
              <div class="card-body">
                <div class="row gx-2">
                  <div class="col-12 mb-3">
                    <label class="form-label" for="product-category">Selectează categorie:</label>
                    <select class="form-select" id="product-category" name="category_id">
                      <option value="">Fără categorie</option>
                      <?php foreach ($categories as $cat): ?>
                      <option value="<?php echo $cat['id']; ?>" <?php echo (isset($_POST['category_id']) && $_POST['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($cat['name']); ?>
                      </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
              </div>
            </div>
            <div class="card mb-3">
              <div class="card-header bg-body-tertiary">
                <h6 class="mb-0">Preț</h6>
              </div>
              <div class="card-body">
                <div class="row gx-2">
                  <div class="col-12 mb-3">
                    <label class="form-label" for="base-price">Preț de bază (RON): <span class="text-danger">*</span></label>
                    <input class="form-control" id="base-price" name="price" type="number" step="0.01" min="0" value="<?php echo htmlspecialchars($_POST['price'] ?? ''); ?>" required />
                  </div>
                  <div class="col-12 mb-3">
                    <label class="form-label" for="sale-price">Preț redus (RON):</label>
                    <input class="form-control" id="sale-price" name="sale_price" type="number" step="0.01" min="0" value="<?php echo htmlspecialchars($_POST['sale_price'] ?? ''); ?>" />
                  </div>
                </div>
              </div>
            </div>
            <div class="card mb-3">
              <div class="card-header bg-body-tertiary">
                <h6 class="mb-0">Stoc</h6>
              </div>
              <div class="card-body">
                <div class="row gx-2">
                  <div class="col-12 mb-3">
                    <label class="form-label" for="stock-quantity">Cantitate în stoc: <span class="text-danger">*</span></label>
                    <input class="form-control" id="stock-quantity" name="stock_quantity" type="number" min="0" value="<?php echo htmlspecialchars($_POST['stock_quantity'] ?? '0'); ?>" required />
                  </div>
                </div>
              </div>
            </div>
            <div class="card mb-3">
              <div class="card-header bg-body-tertiary">
                <h6 class="mb-0">Setări</h6>
              </div>
              <div class="card-body">
                <div class="form-check mb-2">
                  <input class="form-check-input" id="is-active" name="is_active" type="checkbox" value="1" <?php echo (isset($_POST['is_active']) && $_POST['is_active']) ? 'checked' : 'checked'; ?> />
                  <label class="form-check-label" for="is-active">Produs activ</label>
                </div>
                <div class="form-check mb-2">
                  <input class="form-check-input" id="is-gift" name="is_gift" type="checkbox" value="1" <?php echo (isset($_POST['is_gift']) && $_POST['is_gift']) ? 'checked' : ''; ?> />
                  <label class="form-check-label" for="is-gift">Produs cadou</label>
                </div>
                <?php if (!empty($suppliers)): ?>
                <div class="mb-3">
                  <label class="form-label" for="supplier-id">Furnizor:</label>
                  <select class="form-select" id="supplier-id" name="supplier_id">
                    <option value="">Fără furnizor</option>
                    <?php foreach ($suppliers as $supplier): ?>
                    <option value="<?php echo $supplier['id']; ?>" <?php echo (isset($_POST['supplier_id']) && $_POST['supplier_id'] == $supplier['id']) ? 'selected' : ''; ?>>
                      <?php echo htmlspecialchars($supplier['name']); ?>
                    </option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="card mt-3">
        <div class="card-body">
          <div class="row justify-content-between align-items-center">
            <div class="col-md">
              <h5 class="mb-2 mb-md-0">Aproape ai terminat!</h5>
            </div>
            <div class="col-auto">
              <a href="/admin/produse" class="btn btn-link text-secondary p-0 me-3 fw-medium">Anulează</a>
              <button type="submit" class="btn btn-primary">Salvează produs</button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

