<?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 = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$db = new Database();
$conn = $db->getConnection();
$stock_items = [];
$suppliers = [];
$categories = [];

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 => $data) {
            $price = (float)($data['price'] ?? 0);
            $price_date = $data['date'] ?? date('Y-m-d');
            
            if ($price > 0) {
                $stmt_supplier_product = $conn->prepare("INSERT INTO supplier_products (supplier_id, stock_item_id, price, price_date) VALUES (?, ?, ?, ?)");
                $stmt_supplier_product->execute([$supplier_id, $stock_item_id, $price, $price_date]);
            }
        }
        
        $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';
    }
}

try {
    $stmt = $conn->prepare("SELECT * FROM stock_items ORDER BY created_at DESC");
    $stmt->execute();
    $stock_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt_suppliers = $conn->prepare("SELECT id, supplier_name FROM suppliers ORDER BY supplier_name ASC");
    $stmt_suppliers->execute();
    $suppliers = $stmt_suppliers->fetchAll(PDO::FETCH_ASSOC);

    $stmt_categories = $conn->prepare("SELECT DISTINCT category FROM stock_items WHERE category IS NOT NULL ORDER BY category ASC");
    $stmt_categories->execute();
    $categories = $stmt_categories->fetchAll(PDO::FETCH_COLUMN);

    // Dashboard istatistiklerini hesapla
    $stats = [
        'total_items' => count($stock_items),
        'active_items' => array_reduce($stock_items, fn($carry, $item) => $carry + ($item['is_active'] ? 1 : 0), 0),
        'inactive_items' => array_reduce($stock_items, fn($carry, $item) => $carry + (!$item['is_active'] ? 1 : 0), 0),
        'total_suppliers' => count($suppliers),
    ];

} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Stok Yönetimi</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>Stok Yönetimi</h2>
    <a href="#new-stock-item">Yeni Stok Kaydı Ekle</a>
</div>

<div class="card-grid-menu">
    <div class="dashboard-card-icon" style="color: var(--primary);">
        <div class="card-icon-svg" style="background-color: #e3f2fd;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128ZM128,40a8,8,0,0,0-8,8V72a8,8,0,0,0,16,0V48A8,8,0,0,0,128,40ZM128,184a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184Z"></path></svg>
        </div>
        <span>Toplam Ürün</span>
        <p class="stat-number"><?php echo $stats['total_items']; ?></p>
    </div>
    <div class="dashboard-card-icon" style="color: var(--accent-green);">
        <div class="card-icon-svg" style="background-color: #e6ffed;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm41.66-136.34-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.68l50.34-50.34a8,8,0,0,1,11.32,11.32Z"></path></svg>
        </div>
        <span>Aktif Ürünler</span>
        <p class="stat-number"><?php echo $stats['active_items']; ?></p>
    </div>
    <div class="dashboard-card-icon" style="color: var(--accent-red);">
        <div class="card-icon-svg" style="background-color: #ffe6e6;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128ZM128,40a8,8,0,0,0-8,8V72a8,8,0,0,0,16,0V48A8,8,0,0,0,128,40ZM128,184a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184Z"></path></svg>
        </div>
        <span>Pasif Ürünler</span>
        <p class="stat-number"><?php echo $stats['inactive_items']; ?></p>
    </div>
    <div class="dashboard-card-icon" style="color: var(--accent-yellow);">
        <div class="card-icon-svg" style="background-color: #fff8e1;">
            <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" viewBox="0 0 256 256"><path d="M232,128a104,104,0,1,1-104-104A104.11,104.11,0,0,1,232,128Zm-8,0a96,96,0,1,0-96,96A96.11,96.11,0,0,0,224,128Zm-96,40a8,8,0,0,1-16,0V128a8,8,0,0,1,16,0Zm0-56a12,12,0,1,1-12-12A12,12,0,0,1,128,112Z"></path></svg>
        </div>
        <span>Tedarikçi Firma</span>
        <p class="stat-number"><?php echo $stats['total_suppliers']; ?></p>
    </div>
</div>
<?php if ($message): ?>
    <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<h3>Mevcut Stok Kayıtları</h3>
<?php if (empty($stock_items)): ?>
    <p>Envanterde kayıtlı ürün bulunmamaktadır.</p>
<?php else: ?>
    <div class="list-card-container">
        <?php foreach ($stock_items as $item): ?>
            <div class="list-card">
                <div class="list-card-content">
                    <div class="list-card-title"><?php echo htmlspecialchars($item['item_name']); ?></div>
                    <div class="list-card-meta">
                        <span>Kod: <?php echo htmlspecialchars($item['item_code']); ?></span> |
                        <span>Kategori: <?php echo htmlspecialchars($item['category']); ?></span> |
                        <span>Marka: <?php echo htmlspecialchars($item['brand'] ?? '-'); ?></span>
                    </div>
                </div>
                <div class="list-card-actions">
                    <?php if ($item['is_active']): ?>
                        <span class="status status-active">Aktif</span>
                    <?php else: ?>
                        <span class="status status-inactive">Pasif</span>
                    <?php endif; ?>
                    <a href="edit_stock.php?id=<?php echo $item['id']; ?>" class="view-btn">Düzenle</a>
                    <a href="delete.php?table=stock_items&id=<?php echo $item['id']; ?>&redirect=stock.php" class="delete-btn" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>
<hr>
<h3 id="new-stock-item">Yeni Stok Kaydı Ekle</h3>
<form action="stock.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 list="category-list" id="category" name="category">
            <datalist id="category-list">
                <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo htmlspecialchars($cat); ?>">
                <?php endforeach; ?>
            </datalist>
        </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>
                <div class="supplier-price-group">
                    <input type="number" name="supplier_prices[<?php echo $supplier['id']; ?>][price]" step="0.01" min="0" placeholder="Fiyat (TL)">
                    <input type="date" name="supplier_prices[<?php echo $supplier['id']; ?>][date]" value="<?php echo date('Y-m-d'); ?>" placeholder="Tarih">
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <div class="form-actions full-width">
        <button type="submit">Stok Kaydını Oluştur</button>
    </div>
</form>
</main>
<style>
    .supplier-price-group {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
</style>
</body>
</html>