<?php
include '../../db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $category_id = $_POST['category_id'];
    $product_name = $_POST['product_name'];
    $description = $_POST['description'];
    $price = $_POST['price'];
    $slug = strtolower(str_replace(' ', '-', $product_name));

    // Ensure uploads directory exists
    $upload_dir = "../../uploads/";
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // Sanitize image file name
    $original_name = basename($_FILES["product_image"]["name"]);
    $clean_name = preg_replace("/[^A-Za-z0-9_.]/", "", $original_name);
    $image_name = time() . "_" . $clean_name;
    $target_file = $upload_dir . $image_name;

    // Attempt to move uploaded file
    if (move_uploaded_file($_FILES["product_image"]["tmp_name"], $target_file)) {
        $image_path = "uploads/" . $image_name;

        // Insert into database
        $stmt = $conn->prepare("INSERT INTO products (category_id, product_name, product_image, description, price, slug) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("isssds", $category_id, $product_name, $image_path, $description, $price, $slug);
        $stmt->execute();

        header("Location: list.php?msg=Product added");
        exit;
    } else {
        echo "❌ Failed to upload image. Please check file permissions.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Add Product</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
        background: #f0f2f5;
    }
    .card {
        border: none;
        border-radius: 16px;
        box-shadow: 0 0 25px rgba(0, 0, 0, 0.08);
    }
    .form-label {
        font-weight: 500;
        color: #333;
    }
    .btn-success {
        background-color: #28a745;
        border: none;
    }
    .btn-success:hover {
        background-color: #218838;
    }
    .form-control, .form-select {
        border-radius: 10px;
        padding: 10px 14px;
    }
  </style>
</head>
<body>
<div class="container mt-5">
  <div class="card p-4">
    <h3 class="mb-4 text-center">🛒 Add New Product</h3>
    <form method="POST" enctype="multipart/form-data">
      <div class="row">
        <div class="col-md-6 mb-3">
          <label class="form-label">Select Category</label>
          <select name="category_id" class="form-select" required>
            <option value="">Choose...</option>
            <?php
            $res = $conn->query("SELECT * FROM product_categories");
            while ($cat = $res->fetch_assoc()) {
                echo "<option value='{$cat['id']}'>{$cat['category_name']}</option>";
            }
            ?>
          </select>
        </div>

        <div class="col-md-6 mb-3">
          <label class="form-label">Product Name</label>
          <input type="text" name="product_name" class="form-control" placeholder="e.g. Organic Tomato Seeds" required>
        </div>

        <div class="col-md-6 mb-3">
          <label class="form-label">Upload Image</label>
          <input type="file" name="product_image" class="form-control" required>
        </div>

        <div class="col-md-6 mb-3">
          <label class="form-label">Price (₹)</label>
          <input type="text" name="price" class="form-control" placeholder="e.g. 149" required>
        </div>

        <div class="col-12 mb-3">
          <label class="form-label">Description</label>
          <textarea name="description" class="form-control" rows="4" placeholder="Enter short product details..."></textarea>
        </div>

        <div class="col-12 text-end">
          <button type="submit" class="btn btn-success">➕ Add Product</button>
          <a href="list.php" class="btn btn-secondary ms-2">🔙 Back</a>
        </div>
      </div>
    </form>
  </div>
</div>
</body>
</html>
