<?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;
$db = new Database();
$conn = $db->getConnection();
$message = '';
$message_type = '';
$supplier = null;
$products = [];
$supplier_id = $_REQUEST['id'] ?? 0;
if ($supplier_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT * FROM suppliers WHERE id = ?");
        $stmt->execute([$supplier_id]);
        $supplier = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$supplier) {
            $message = 'Düzenlemek istediğiniz tedarikçi bulunamadı.';
            $message_type = 'error';
        }
        $stmt_products = $conn->prepare("SELECT * FROM supplier_products WHERE supplier_id = ? ORDER BY product_name ASC");
        $stmt_products->execute([$supplier_id]);
        $products = $stmt_products->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $message = 'Hata: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $supplier_id = $_POST['id'] ?? 0;
    if (isset($_POST['action']) && $_POST['action'] === 'update_supplier') {
        $supplier_name = $_POST['supplier_name'] ?? $supplier['supplier_name'];
        $contact_person = $_POST['contact_person'] ?? $supplier['contact_person'];
        $phone = $_POST['phone'] ?? $supplier['phone'];
        $email = $_POST['email'] ?? $supplier['email'];
        $address = $_POST['address'] ?? $supplier['address'];
        try {
            $stmt = $conn->prepare("UPDATE suppliers SET supplier_name = ?, contact_person = ?, phone = ?, email = ?, address = ? WHERE id = ?");
            $stmt->execute([$supplier_name, $contact_person, $phone, $email, $address, $supplier_id]);
            $message = 'Tedarikçi bilgileri başarıyla güncellendi.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Güncelleme sırasında bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'add_product') {
        $product_name = $_POST['product_name'] ?? '';
        $price = $_POST['price'] ?? 0;
        try {
            $stmt = $conn->prepare("INSERT INTO supplier_products (supplier_id, product_name, price) VALUES (?, ?, ?)");
            $stmt->execute([$supplier_id, $product_name, $price]);
            $message = 'Ürün başarıyla eklendi.';
            $message_type = 'success';
            header("Location: edit_supplier.php?id=$supplier_id&status=success&message=" . urlencode($message));
            exit;
        } catch (PDOException $e) {
            $message = 'Ürün eklenirken bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    }
    // Sayfayı yeniden yükleyerek güncel verileri çek
    header("Location: edit_supplier.php?id=$supplier_id&status=$message_type&message=" . urlencode($message));
    exit;
}
if (!$supplier && $supplier_id > 0) {
    echo "Hata: Tedarikçi bulunamadı.";
    exit;
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Tedarikçi Düzenle: <?php echo htmlspecialchars($supplier['supplier_name'] ?? ''); ?></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'; ?>
    <h2>Tedarikçi Firma Düzenle</h2>
    <?php if ($message): ?>
        <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
            <?php echo htmlspecialchars($message); ?>
        </p>
    <?php endif; ?>
    <?php if ($supplier): ?>
    <div class="form-grid">
        <div class="form-section">
            <h3 class="form-section-title">Firma Bilgileri</h3>
            <form action="edit_supplier.php" method="POST">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($supplier['id']); ?>">
                <input type="hidden" name="action" value="update_supplier">
                <div class="form-group">
                    <label for="supplier_name">Firma Adı:</label>
                    <input type="text" id="supplier_name" name="supplier_name" value="<?php echo htmlspecialchars($supplier['supplier_name']); ?>" required>
                </div>
                <div class="form-group">
                    <label for="contact_person">Yetkili Kişi:</label>
                    <input type="text" id="contact_person" name="contact_person" value="<?php echo htmlspecialchars($supplier['contact_person'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label for="phone">Telefon:</label>
                    <input type="text" id="phone" name="phone" value="<?php echo htmlspecialchars($supplier['phone'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label for="email">E-posta:</label>
                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($supplier['email'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label for="address">Adres:</label>
                    <textarea id="address" name="address" rows="3"><?php echo htmlspecialchars($supplier['address'] ?? ''); ?></textarea>
                </div>
                <div class="form-actions">
                    <button type="submit">Bilgileri Güncelle</button>
                </div>
            </form>
        </div>
        <div class="form-section">
            <h3 class="form-section-title">Sağladığı Ürünler</h3>
            <form action="edit_supplier.php" method="POST">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($supplier['id']); ?>">
                <input type="hidden" name="action" value="add_product">
                <div class="form-group">
                    <label for="product_name">Ürün Adı:</label>
                    <input type="text" id="product_name" name="product_name" required>
                </div>
                <div class="form-group">
                    <label for="price">Birim Fiyat (TL):</label>
                    <input type="number" id="price" name="price" step="0.01" min="0" required>
                </div>
                <div class="form-actions">
                    <button type="submit">Ürün Ekle</button>
                </div>
            </form>
            <hr>
            <h4>Mevcut Ürün Listesi</h4>
            <?php if (empty($products)): ?>
                <p>Henüz ürün eklenmemiş.</p>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Ürün Adı</th>
                            <th>Fiyat (TL)</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($product['product_name']); ?></td>
                                <td><?php echo number_format($product['price'], 2, ',', '.'); ?></td>
                                <td>
                                    <a href="delete.php?table=supplier_products&id=<?php echo $product['id']; ?>&redirect=edit_supplier.php?id=<?php echo $supplier['id']; ?>" onclick="return confirm('Bu ürünü silmek istediğinizden emin misiniz?');">Sil</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</main>
</body>
</html>