<?php

$page_title = "افزودن محصول";
require 'config/db.php';
require 'includes/header.php';
require 'includes/sidebar.php';
require 'check_admin.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title       = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $weight      = $_POST['weight_gram'] ?? null;
    $price_per_g = $_POST['gold_price_per_gram'] ?? null;
    $making_cost = $_POST['making_cost'] ?? null;
    $final_price = $_POST['final_price'] ?? null;
    $is_special  = isset($_POST['is_special']) ? 1 : 0;

    $stmt = $pdo->prepare("INSERT INTO products 
        (title, description, weight_gram, gold_price_per_gram, making_cost, final_price, is_special)
        VALUES (:title, :description, :weight, :price_per_g, :making_cost, :final_price, :is_special)");
    $stmt->execute([
        ':title' => $title,
        ':description' => $description,
        ':weight' => $weight,
        ':price_per_g' => $price_per_g,
        ':making_cost' => $making_cost,
        ':final_price' => $final_price,
        ':is_special' => $is_special
    ]);

    $product_id = $pdo->lastInsertId();

    if (!empty($_FILES['images']['name'][0])) {
        $upload_dir = 'uploads/products/';
        foreach ($_FILES['images']['name'] as $key => $name) {
            $tmp_name = $_FILES['images']['tmp_name'][$key];
            if ($tmp_name) {
                $ext = pathinfo($name, PATHINFO_EXTENSION);
                $new_name = 'product_' . $product_id . '_' . time() . '_' . $key . '.' . $ext;
                $dest = $upload_dir . $new_name;
                if (move_uploaded_file($tmp_name, $dest)) {
                    $stmtImg = $pdo->prepare("INSERT INTO product_images (product_id, image_path) VALUES (:pid, :path)");
                    $stmtImg->execute([
                        ':pid' => $product_id,
                        ':path' => $dest
                    ]);
                }
            }
        }
    }

    echo "<p>محصول با موفقیت ثبت شد.</p>";
}
?>

<h1>افزودن محصول</h1>

<form action="" method="post" enctype="multipart/form-data">
    <label>عنوان محصول:</label>
    <input type="text" name="title" required>

    <label>توضیحات:</label>
    <textarea name="description" rows="4"></textarea>

    <label>وزن (گرم):</label>
    <input type="number" step="0.01" name="weight_gram">

    <label>قیمت هر گرم طلا:</label>
    <input type="number" step="0.01" name="gold_price_per_gram">

    <label>اجرت (دستمزد):</label>
    <input type="number" step="0.01" name="making_cost">

    <label>قیمت نهایی:</label>
    <input type="number" step="0.01" name="final_price">

    <label>
        <input type="checkbox" name="is_special"> محصول شگفت‌انگیز
    </label>

    <label>تصاویر محصول (چندتا):</label>
    <input type="file" name="images[]" multiple>

    <button type="submit">ثبت محصول</button>
</form>

<?php
require 'includes/footer.php';