<?php
require_once '../../config/config.php';
require_once '../../includes/auth.php';

requireAdminLogin();

$id = $_GET['id'] ?? 0;

$stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
$stmt->execute([$id]);
$company = $stmt->fetch();

if (!$company) {
    setFlashMessage('error', 'Firma bulunamadı.');
    redirect('index.php');
}

// Tüm kategorileri getir
$stmt = $pdo->query("SELECT * FROM company_categories WHERE status = 'active' ORDER BY name");
$allCategories = $stmt->fetchAll();

// Mevcut kategorileri getir
$stmt = $pdo->prepare("SELECT category_id FROM company_category_relations WHERE company_id = ?");
$stmt->execute([$id]);
$selectedCategories = $stmt->fetchAll(PDO::FETCH_COLUMN);

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = trim($_POST['company_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $whatsapp = trim($_POST['whatsapp'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $about = trim($_POST['about'] ?? '');
    $membership_type = $_POST['membership_type'] ?? 'free';
    $status = $_POST['status'] ?? 'active';
    
    // Sosyal Medya
    $instagram = trim($_POST['instagram'] ?? '');
    $facebook = trim($_POST['facebook'] ?? '');
    $youtube = trim($_POST['youtube'] ?? '');
    $other_social = trim($_POST['other_social'] ?? '');
    
    // Kategoriler
    $postedCategories = $_POST['categories'] ?? [];
    
    // Logo yükleme
    $logo = $company['logo'] ?? '';
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $upload = uploadImage($_FILES['logo'], 'logos');
        if ($upload['success']) {
            // Eski logoyu sil
            if ($logo) {
                $oldPath = str_replace(UPLOAD_URL, UPLOAD_PATH, $logo);
                deleteImage($oldPath);
            }
            $logo = $upload['url'];
        } else {
            $error = $upload['message'];
        }
    }
    
    // Şifre güncelleme
    $password = $_POST['password'] ?? '';
    $updatePassword = !empty($password);
    
    if (empty($company_name)) {
        $error = 'Firma adı gereklidir.';
    } elseif (empty($email)) {
        $error = 'E-posta adresi gereklidir.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Geçerli bir e-posta adresi giriniz.';
    } else {
        // E-posta kontrolü (kendi ID'si hariç)
        $stmt = $pdo->prepare("SELECT id FROM companies WHERE email = ? AND id != ?");
        $stmt->execute([$email, $id]);
        if ($stmt->fetch()) {
            $error = 'Bu e-posta adresi zaten kullanılıyor.';
        } else {
            try {
                $pdo->beginTransaction();

                // Kolon kontrolü
                $logoColumnExists = columnExists('companies', 'logo');
                $socialColumnsExist = columnExists('companies', 'instagram');
                
                $sql = "UPDATE companies SET 
                        company_name = ?, email = ?, phone = ?, whatsapp = ?, address = ?, about = ?, 
                        membership_type = ?, status = ?";
                $params = [$company_name, $email, $phone, $whatsapp, $address, $about, $membership_type, $status];
                
                if ($updatePassword) {
                    $sql .= ", password = ?";
                    $params[] = hashPassword($password);
                }
                
                if ($logoColumnExists) {
                    $sql .= ", logo = ?";
                    $params[] = $logo;
                }
                
                if ($socialColumnsExist) {
                    $sql .= ", instagram = ?, facebook = ?, youtube = ?, other_social = ?";
                    $params[] = $instagram;
                    $params[] = $facebook;
                    $params[] = $youtube;
                    $params[] = $other_social;
                }
                
                $sql .= " WHERE id = ?";
                $params[] = $id;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                
                // Kategorileri güncelle
                // Önce mevcutları sil
                $stmt = $pdo->prepare("DELETE FROM company_category_relations WHERE company_id = ?");
                $stmt->execute([$id]);
                
                // Yenileri ekle
                if (!empty($postedCategories)) {
                    $stmt = $pdo->prepare("INSERT INTO company_category_relations (company_id, category_id) VALUES (?, ?)");
                    foreach ($postedCategories as $catId) {
                        $stmt->execute([$id, $catId]);
                    }
                }
                
                $pdo->commit();
                
                setFlashMessage('success', 'Firma başarıyla güncellendi.');
                redirect('index.php');
            } catch (PDOException $e) {
                $pdo->rollBack();
                $error = 'Firma güncellenirken bir hata oluştu: ' . $e->getMessage();
                if (defined('DEBUG') && DEBUG) {
                    $error .= '<br><small>' . $e->getTraceAsString() . '</small>';
                }
            }
        }
    }
}

$page_title = 'Firma Düzenle';
include '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Firma Düzenle</h1>
    <a href="index.php" class="btn btn-secondary">
        <i class="fas fa-arrow-left me-2"></i>Geri Dön
    </a>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6">
                    <h5 class="mb-3 border-bottom pb-2">Temel Bilgiler</h5>
                    
                    <div class="mb-3">
                        <label for="logo" class="form-label">Firma Logosu</label>
                        <?php if (!empty($company['logo'])): ?>
                            <div class="mb-2">
                                <img src="<?= e(getImageUrl($company['logo'])) ?>" alt="Logo" class="img-thumbnail" style="max-width: 200px; max-height: 200px; object-fit: contain;">
                            </div>
                        <?php endif; ?>
                        <input type="file" class="form-control" id="logo" name="logo" accept="image/*">
                    </div>
                    
                    <div class="mb-3">
                        <label for="company_name" class="form-label">Firma Adı <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="company_name" name="company_name" value="<?= e($company['company_name']) ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="email" class="form-label">E-posta <span class="text-danger">*</span></label>
                        <input type="email" class="form-control" id="email" name="email" value="<?= e($company['email']) ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password" class="form-label">Yeni Şifre</label>
                        <input type="text" class="form-control" id="password" name="password">
                        <small class="text-muted">Değiştirmek istemiyorsanız boş bırakın</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="phone" class="form-label">Telefon</label>
                        <input type="text" class="form-control" id="phone" name="phone" value="<?= e($company['phone']) ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label for="whatsapp" class="form-label">WhatsApp</label>
                        <input type="text" class="form-control" id="whatsapp" name="whatsapp" value="<?= e($company['whatsapp']) ?>">
                    </div>

                    <h5 class="mb-3 border-bottom pb-2 mt-4">Kategoriler</h5>
                    <div class="mb-3">
                        <div class="card card-body bg-light" style="max-height: 200px; overflow-y: auto;">
                            <?php foreach ($allCategories as $cat): ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="categories[]" 
                                           value="<?= $cat['id'] ?>" id="cat_<?= $cat['id'] ?>"
                                           <?= in_array($cat['id'], $selectedCategories) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="cat_<?= $cat['id'] ?>">
                                        <?= e($cat['name']) ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <h5 class="mb-3 border-bottom pb-2">Detaylar</h5>
                    
                    <div class="mb-3">
                        <label for="address" class="form-label">Adres</label>
                        <textarea class="form-control" id="address" name="address" rows="3"><?= e($company['address']) ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="about" class="form-label">Firma Hakkında</label>
                        <textarea class="form-control" id="about" name="about" rows="5"><?= htmlspecialchars($company['about'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="membership_type" class="form-label">Üyelik Tipi</label>
                            <select class="form-select" id="membership_type" name="membership_type">
                                <option value="free" <?= $company['membership_type'] === 'free' ? 'selected' : '' ?>>Ücretsiz</option>
                                <option value="paid" <?= $company['membership_type'] === 'paid' ? 'selected' : '' ?>>Ücretli</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="status" class="form-label">Durum</label>
                            <select class="form-select" id="status" name="status">
                                <option value="active" <?= $company['status'] === 'active' ? 'selected' : '' ?>>Aktif</option>
                                <option value="inactive" <?= $company['status'] === 'inactive' ? 'selected' : '' ?>>Pasif</option>
                            </select>
                        </div>
                    </div>

                    <h5 class="mb-3 border-bottom pb-2 mt-4">Sosyal Medya</h5>
                    
                    <div class="mb-3">
                        <label for="instagram" class="form-label"><i class="fab fa-instagram text-danger me-1"></i> Instagram</label>
                        <input type="text" class="form-control" id="instagram" name="instagram" value="<?= e($company['instagram'] ?? '') ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label for="facebook" class="form-label"><i class="fab fa-facebook text-primary me-1"></i> Facebook</label>
                        <input type="text" class="form-control" id="facebook" name="facebook" value="<?= e($company['facebook'] ?? '') ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label for="youtube" class="form-label"><i class="fab fa-youtube text-danger me-1"></i> YouTube</label>
                        <input type="text" class="form-control" id="youtube" name="youtube" value="<?= e($company['youtube'] ?? '') ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label for="other_social" class="form-label"><i class="fas fa-link me-1"></i> Diğer</label>
                        <input type="text" class="form-control" id="other_social" name="other_social" value="<?= e($company['other_social'] ?? '') ?>">
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save me-2"></i>Güncelle
                </button>
                <a href="index.php" class="btn btn-secondary">İptal</a>
            </div>
        </form>
    </div>
</div>

<?php include '../includes/footer.php'; ?>

<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
    selector: '#about',
    height: 400,
    language: 'tr',
    plugins: [
        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
        'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
    ],
    toolbar: 'undo redo | blocks | ' +
        'bold italic forecolor | alignleft aligncenter ' +
        'alignright alignjustify | bullist numlist outdent indent | ' +
        'removeformat | help',
    content_style: 'body { font-family: Arial, sans-serif; font-size: 14px }'
});
</script>

