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

requireAdminLogin();

$id = (int) ($_GET['id'] ?? 0);

if ($id <= 0) {
    setFlashMessage('error', 'Geçersiz firma ID.');
    redirect('index.php');
}

try {
    $pdo->beginTransaction();

    // 1. Resimleri fiziksel olarak sil
    $stmt = $pdo->prepare("SELECT image_url FROM company_images WHERE company_id = ?");
    $stmt->execute([$id]);
    $images = $stmt->fetchAll();

    foreach ($images as $img) {
        $path = $img['image_url'];
        // URL ise path'e çevir (basitçe uploads kısmını al)
        if (strpos($path, 'uploads/') !== false) {
            $parts = explode('uploads/', $path);
            $relativePath = 'uploads/' . end($parts);
            $fullPath = ROOT_PATH . '/' . $relativePath;
            if (file_exists($fullPath)) {
                unlink($fullPath);
            }
        }
    }

    // Logo'yu sil
    $stmt = $pdo->prepare("SELECT logo FROM companies WHERE id = ?");
    $stmt->execute([$id]);
    $company = $stmt->fetch();
    if ($company && !empty($company['logo'])) {
        $path = $company['logo'];
        if (strpos($path, 'uploads/') !== false) {
            $parts = explode('uploads/', $path);
            $relativePath = 'uploads/' . end($parts);
            $fullPath = ROOT_PATH . '/' . $relativePath;
            if (file_exists($fullPath)) {
                unlink($fullPath);
            }
        }
    }

    // 2. İlişkili verileri veritabanından sil
    // Not: Foreign key constraint'ler varsa otomatik silinir (ON DELETE CASCADE)
    // Ancak emin olmak için manuel siliyoruz.

    $pdo->prepare("DELETE FROM company_images WHERE company_id = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM services WHERE company_id = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM reviews WHERE company_id = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM company_category_relations WHERE company_id = ?")->execute([$id]);

    // 3. Firmayı sil
    $stmt = $pdo->prepare("DELETE FROM companies WHERE id = ?");
    $stmt->execute([$id]);

    $pdo->commit();
    setFlashMessage('success', 'Firma ve tüm verileri başarıyla silindi.');

} catch (Exception $e) {
    $pdo->rollBack();
    setFlashMessage('error', 'Firma silinirken hata oluştu: ' . $e->getMessage());
}

redirect('index.php');
