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

requireCompanyLogin();

$companyId = $_SESSION['company_id'];

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

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = trim($_POST['company_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $whatsapp = trim($_POST['whatsapp'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $about = trim($_POST['about'] ?? '');
    $instagram = trim($_POST['instagram'] ?? '');
    $facebook = trim($_POST['facebook'] ?? '');
    $youtube = trim($_POST['youtube'] ?? '');
    $other_social = trim($_POST['other_social'] ?? '');
    
    // 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.';
    } else {
        try {
            // Logo kolonunun varlığını kontrol et
            $logoColumnExists = columnExists('companies', 'logo');
            $socialColumnsExist = columnExists('companies', 'instagram');
            
            if ($updatePassword) {
                $hashedPassword = hashPassword($password);
                if ($logoColumnExists && $socialColumnsExist) {
                    $stmt = $pdo->prepare("
                        UPDATE companies 
                        SET company_name = ?, logo = ?, phone = ?, whatsapp = ?, address = ?, about = ?, 
                            instagram = ?, facebook = ?, youtube = ?, other_social = ?, password = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([$company_name, $logo, $phone, $whatsapp, $address, $about, 
                        $instagram, $facebook, $youtube, $other_social, $hashedPassword, $companyId]);
                } elseif ($logoColumnExists) {
                    $stmt = $pdo->prepare("
                        UPDATE companies 
                        SET company_name = ?, logo = ?, phone = ?, whatsapp = ?, address = ?, about = ?, password = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([$company_name, $logo, $phone, $whatsapp, $address, $about, $hashedPassword, $companyId]);
                } else {
                    $stmt = $pdo->prepare("
                        UPDATE companies 
                        SET company_name = ?, phone = ?, whatsapp = ?, address = ?, about = ?, password = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([$company_name, $phone, $whatsapp, $address, $about, $hashedPassword, $companyId]);
                }
            } else {
                if ($logoColumnExists && $socialColumnsExist) {
                    $stmt = $pdo->prepare("
                        UPDATE companies 
                        SET company_name = ?, logo = ?, phone = ?, whatsapp = ?, address = ?, about = ?, 
                            instagram = ?, facebook = ?, youtube = ?, other_social = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([$company_name, $logo, $phone, $whatsapp, $address, $about, 
                        $instagram, $facebook, $youtube, $other_social, $companyId]);
                } elseif ($logoColumnExists) {
                    $stmt = $pdo->prepare("
                        UPDATE companies 
                        SET company_name = ?, logo = ?, phone = ?, whatsapp = ?, address = ?, about = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([$company_name, $logo, $phone, $whatsapp, $address, $about, $companyId]);
                } else {
                    $stmt = $pdo->prepare("
                        UPDATE companies 
                        SET company_name = ?, phone = ?, whatsapp = ?, address = ?, about = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([$company_name, $phone, $whatsapp, $address, $about, $companyId]);
                }
            }
            
            setFlashMessage('success', 'Profil bilgileri başarıyla güncellendi.');
            redirect('profile.php');
        } catch (PDOException $e) {
            $error = 'Profil güncellenirken bir hata oluştu: ' . $e->getMessage();
            if (defined('DEBUG') && DEBUG) {
                $error .= '<br><small>' . $e->getTraceAsString() . '</small>';
            }
        }
    }
}

// Firma resimleri
$stmt = $pdo->prepare("SELECT * FROM company_images WHERE company_id = ? ORDER BY sort_order");
$stmt->execute([$companyId]);
$images = $stmt->fetchAll();

$page_title = 'Profil';
include 'includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Profil Bilgileri</h1>
</div>

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

<div class="row">
    <div class="col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Firma Bilgileri</h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data" id="profileForm">
                    <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($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">Firma logonuzu yükleyin (PNG, JPG, GIF, WebP)</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 class="form-label">E-posta</label>
                        <input type="text" class="form-control" value="<?= e($company['email']) ?>" disabled>
                        <small class="text-muted">E-posta adresi değiştirilemez. Değiştirmek için admin ile iletişime geçin.</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password" class="form-label">Yeni Şifre</label>
                        <input type="password" 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 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="6"><?= htmlspecialchars($company['about'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                    </div>
                    
                    <?php if ($company['membership_type'] === 'paid'): ?>
                        <hr class="my-4">
                        <h5 class="mb-3"><i class="fas fa-share-alt me-2"></i>Sosyal Medya Hesapları (Gold Üyelik)</h5>
                        
                        <div class="mb-3">
                            <label for="instagram" class="form-label">
                                <i class="fab fa-instagram me-2 text-danger"></i>Instagram
                            </label>
                            <input type="url" class="form-control" id="instagram" name="instagram" 
                                value="<?= e($company['instagram'] ?? '') ?>" 
                                placeholder="https://instagram.com/firmaniz">
                        </div>
                        
                        <div class="mb-3">
                            <label for="facebook" class="form-label">
                                <i class="fab fa-facebook me-2 text-primary"></i>Facebook
                            </label>
                            <input type="url" class="form-control" id="facebook" name="facebook" 
                                value="<?= e($company['facebook'] ?? '') ?>" 
                                placeholder="https://facebook.com/firmaniz">
                        </div>
                        
                        <div class="mb-3">
                            <label for="youtube" class="form-label">
                                <i class="fab fa-youtube me-2 text-danger"></i>YouTube
                            </label>
                            <input type="url" class="form-control" id="youtube" name="youtube" 
                                value="<?= e($company['youtube'] ?? '') ?>" 
                                placeholder="https://youtube.com/@firmaniz">
                        </div>
                        
                        <div class="mb-3">
                            <label for="other_social" class="form-label">
                                <i class="fas fa-link me-2"></i>Diğer Sosyal Medya
                            </label>
                            <input type="url" class="form-control" id="other_social" name="other_social" 
                                value="<?= e($company['other_social'] ?? '') ?>" 
                                placeholder="https://...">
                            <small class="text-muted">Twitter, LinkedIn, TikTok vb.</small>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Sosyal medya hesapları</strong> sadece Gold üyelik paketinde mevcuttur. 
                            Gold üyeliğe geçmek için admin ile iletişime geçin.
                        </div>
                    <?php endif; ?>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Kaydet
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Üyelik Bilgileri</h5>
            </div>
            <div class="card-body">
                <p><strong>Üyelik Tipi:</strong><br>
                    <span class="badge bg-<?= $company['membership_type'] === 'paid' ? 'success' : 'secondary' ?>">
                        <?= $company['membership_type'] === 'paid' ? 'Ücretli' : 'Ücretsiz' ?>
                    </span>
                </p>
                <p><strong>Durum:</strong><br>
                    <span class="badge bg-<?= $company['status'] === 'active' ? 'success' : 'secondary' ?>">
                        <?= $company['status'] === 'active' ? 'Aktif' : 'Pasif' ?>
                    </span>
                </p>
            </div>
        </div>
    </div>
</div>

<!-- Firma Resimleri -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Firma Resimleri (Maksimum 10)</h5>
        <?php if (count($images) < MAX_COMPANY_IMAGES): ?>
            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#uploadImageModal">
                <i class="fas fa-plus me-1"></i>Resim Ekle
            </button>
        <?php endif; ?>
    </div>
    <div class="card-body">
        <?php if (empty($images)): ?>
            <p class="text-muted">Henüz resim eklenmemiş.</p>
        <?php else: ?>
            <div class="row">
                <?php foreach ($images as $image): ?>
                    <div class="col-md-3 mb-3">
                        <div class="position-relative">
                            <img src="<?= e($image['image_url']) ?>" alt="" class="img-thumbnail w-100" style="height: 200px; object-fit: cover;">
                            <a href="delete-image.php?id=<?= $image['id'] ?>" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-2 btn-delete" onclick="return confirm('Bu resmi silmek istediğinize emin misiniz?')">
                                <i class="fas fa-trash"></i>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Resim Yükleme Modal -->
<div class="modal fade" id="uploadImageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Resim Yükle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="upload-image.php" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="image" class="form-label">Resim Seç</label>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*" required>
                        <small class="text-muted">Maksimum 10 resim yükleyebilirsiniz.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn btn-primary">Yükle</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<!-- CKEditor (Ücretsiz) -->
<script src="https://cdn.ckeditor.com/ckeditor5/41.0.0/classic/ckeditor.js"></script>
<script>
let editorInstance;

ClassicEditor
    .create(document.querySelector('#about'), {
        language: 'tr',
        toolbar: {
            items: [
                'heading', '|',
                'bold', 'italic', 'link', '|',
                'bulletedList', 'numberedList', '|',
                'insertImage', 'insertTable', '|',
                'undo', 'redo', '|',
                'sourceEditing'
            ]
        },
        simpleUpload: {
            uploadUrl: 'upload-editor-image.php',
            withCredentials: false,
            headers: {
                'X-CSRF-TOKEN': 'CSRF-Token'
            }
        }
    })
    .then(editor => {
        editorInstance = editor;
    })
    .catch(error => {
        console.error(error);
    });

// Form gönderilmeden önce editor içeriğini textarea'ya yaz
document.getElementById('profileForm')?.addEventListener('submit', function() {
    if (editorInstance) {
        const content = editorInstance.getData();
        document.getElementById('about').value = content;
    }
});
</script>
