<?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');
}

$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';
    
    // 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 {
                // Logo kolonunun varlığını kontrol et
                $logoColumnExists = columnExists('companies', 'logo');
                
                if ($updatePassword) {
                    $hashedPassword = hashPassword($password);
                    if ($logoColumnExists) {
                        $stmt = $pdo->prepare("
                            UPDATE companies 
                            SET company_name = ?, email = ?, password = ?, logo = ?, phone = ?, whatsapp = ?, address = ?, about = ?, membership_type = ?, status = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([$company_name, $email, $hashedPassword, $logo, $phone, $whatsapp, $address, $about, $membership_type, $status, $id]);
                    } else {
                        $stmt = $pdo->prepare("
                            UPDATE companies 
                            SET company_name = ?, email = ?, password = ?, phone = ?, whatsapp = ?, address = ?, about = ?, membership_type = ?, status = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([$company_name, $email, $hashedPassword, $phone, $whatsapp, $address, $about, $membership_type, $status, $id]);
                    }
                } else {
                    if ($logoColumnExists) {
                        $stmt = $pdo->prepare("
                            UPDATE companies 
                            SET company_name = ?, email = ?, logo = ?, phone = ?, whatsapp = ?, address = ?, about = ?, membership_type = ?, status = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([$company_name, $email, $logo, $phone, $whatsapp, $address, $about, $membership_type, $status, $id]);
                    } else {
                        $stmt = $pdo->prepare("
                            UPDATE companies 
                            SET company_name = ?, email = ?, phone = ?, whatsapp = ?, address = ?, about = ?, membership_type = ?, status = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([$company_name, $email, $phone, $whatsapp, $address, $about, $membership_type, $status, $id]);
                    }
                }
                
                setFlashMessage('success', 'Firma başarıyla güncellendi.');
                redirect('index.php');
            } catch (PDOException $e) {
                $error = 'Firma güncellenirken bir hata oluştu: ' . $e->getMessage();
                // Geliştirme ortamında detaylı hata göster
                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">
                    <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/*">
                        <small class="text-muted">Yeni logo yüklemek için seçin</small>
                    </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>
                </div>
                
                <div class="col-md-6">
                    <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="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="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>
            </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>

