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

requireAdminLogin();

$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 = '';
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $upload = uploadImage($_FILES['logo'], 'logos');
        if ($upload['success']) {
            $logo = $upload['url'];
        } else {
            $error = $upload['message'];
        }
    }
    
    // Şifre oluştur
    $password = $_POST['password'] ?? '';
    if (empty($password)) {
        $password = bin2hex(random_bytes(8)); // Rastgele şifre
    }
    
    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ü
        $stmt = $pdo->prepare("SELECT id FROM companies WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            $error = 'Bu e-posta adresi zaten kullanılıyor.';
        } else {
            try {
                $hashedPassword = hashPassword($password);
                
                // Logo kolonunun varlığını kontrol et
                $logoColumnExists = columnExists('companies', 'logo');
                
                if ($logoColumnExists) {
                    $stmt = $pdo->prepare("
                        INSERT INTO companies (company_name, email, password, logo, phone, whatsapp, address, about, membership_type, status)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$company_name, $email, $hashedPassword, $logo, $phone, $whatsapp, $address, $about, $membership_type, $status]);
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO companies (company_name, email, password, phone, whatsapp, address, about, membership_type, status)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$company_name, $email, $hashedPassword, $phone, $whatsapp, $address, $about, $membership_type, $status]);
                }
                
                $companyId = $pdo->lastInsertId();
                
                // Şifreyi gönder (burada e-posta gönderme işlemi yapılabilir)
                // TODO: E-posta gönderme fonksiyonu eklenebilir
                
                setFlashMessage('success', 'Firma başarıyla oluşturuldu. Şifre: ' . $password);
                redirect('index.php');
            } catch (PDOException $e) {
                $error = 'Firma oluşturulurken bir hata oluştu.';
            }
        }
    }
}

$page_title = 'Yeni Firma Ekle';
include '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Yeni Firma Ekle</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>
                        <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" 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" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password" class="form-label">Şifre</label>
                        <input type="text" class="form-control" id="password" name="password">
                        <small class="text-muted">Boş bırakılırsa otomatik şifre oluşturulur</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="phone" class="form-label">Telefon</label>
                        <input type="text" class="form-control" id="phone" name="phone">
                    </div>
                    
                    <div class="mb-3">
                        <label for="whatsapp" class="form-label">WhatsApp</label>
                        <input type="text" class="form-control" id="whatsapp" name="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"></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"></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">Ücretsiz</option>
                            <option value="paid">Ü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">Aktif</option>
                            <option value="inactive">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>Kaydet
                </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>

