<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php';
use HatiApp\Core\Database;

$message = '';
$message_type = '';
$db = new Database();
$conn = $db->getConnection();
$suppliers = [];

try {
    $stmt = $conn->prepare("SELECT id, supplier_name FROM suppliers ORDER BY supplier_name ASC");
    $stmt->execute();
    $suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Hata: " . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $item_code = $_POST['item_code'] ?? '';
    $item_name = $_POST['item_name'] ?? '';
    $unit = $_POST['unit'] ?? '';
    $category = $_POST['category'] ?? '';
    $brand = $_POST['brand'] ?? '';
    $model = $_POST['model'] ?? '';
    $description = $_POST['description'] ?? '';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $supplier_prices = $_POST['supplier_prices'] ?? [];

    try {
        $conn->beginTransaction();

        $stmt_stock = $conn->prepare("INSERT INTO stock_items (item_code, item_name, unit, category, brand, model, description, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt_stock->execute([$item_code, $item_name, $unit, $category, $brand, $model, $description, $is_active]);
        $stock_item_id = $conn->lastInsertId();

        foreach ($supplier_prices as $supplier_id => $price) {
            if ($price > 0) {
                $stmt_supplier_product = $conn->prepare("INSERT INTO supplier_products (supplier_id, stock_item_id, price) VALUES (?, ?, ?)");
                $stmt_supplier_product->execute([$supplier_id, $stock_item_id, $price]);
            }
        }
        
        $conn->commit();
        
        $message = 'Yeni stok kaydı başarıyla oluşturuldu!';
        $message_type = 'success';
        header('Location: stock.php?status=success&message=' . urlencode($message));
        exit;
    } catch (PDOException $e) {
        $conn->rollBack();
        $message = 'Hata: Stok kaydı oluşturulurken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Yeni Stok Kaydı Ekle</title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="header-actions">
    <h2>Yeni Stok Kaydı Ekle</h2>
    <a href="stock.php">Geri Dön</a>
</div>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<form action="create_stock_item.php" method="POST">
    <div class="form-section-title">Malzeme Bilgileri</div>
    <div class="form-grid">
        <div class="form-group">
            <label for="item_code">Kod *</label>
            <input type="text" id="item_code" name="item_code" required>
        </div>
        <div class="form-group">
            <label for="item_name">Malzeme Adı *</label>
            <input type="text" id="item_name" name="item_name" required>
        </div>
        <div class="form-group">
            <label for="unit">Birim Seçiniz *</label>
            <select id="unit" name="unit" required>
                <option value="">Seçiniz</option>
                <option value="Adet">Adet</option>
                <option value="m">m</option>
                <option value="m2">m²</option>
                <option value="kg">kg</option>
            </select>
        </div>
        <div class="form-group">
            <label for="category">Kategori Seçiniz</label>
            <input type="text" id="category" name="category">
        </div>
        <div class="form-group">
            <label for="brand">Marka Adı</label>
            <input type="text" id="brand" name="brand">
        </div>
        <div class="form-group">
            <label for="model">Model Adı</label>
            <input type="text" id="model" name="model">
        </div>
    </div>
    <div class="form-group full-width">
        <label for="description">Açıklama</label>
        <textarea id="description" name="description" rows="5"></textarea>
    </div>
    <div class="form-group full-width">
        <label>
            <input type="checkbox" name="is_active" checked>
            Bütün Projelerde Aktif Kullanım
        </label>
    </div>

    <div class="form-section-title">Tedarikçi Firma ve Fiyatları</div>
    <div class="form-grid">
        <?php foreach ($suppliers as $supplier): ?>
            <div class="form-group">
                <label for="price_<?php echo $supplier['id']; ?>"><?php echo htmlspecialchars($supplier['supplier_name']); ?></label>
                <input type="number" id="price_<?php echo $supplier['id']; ?>" name="supplier_prices[<?php echo $supplier['id']; ?>]" step="0.01" min="0" placeholder="Fiyat (TL)">
            </div>
        <?php endforeach; ?>
    </div>
    
    <div class="form-actions full-width">
        <button type="submit">Stok Kaydını Oluştur</button>
    </div>
</form>
</main>
</body>
</html>