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

requireCompanyLogin();

$companyId = $_SESSION['company_id'];
$id = (int)($_GET['id'] ?? 0);
$error = '';

$stmt = $pdo->prepare("SELECT * FROM services WHERE id = ? AND company_id = ?");
$stmt->execute([$id, $companyId]);
$service = $stmt->fetch();

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

// Hizmet kategorileri
$serviceCategories = [];
try {
    $stmt = $pdo->query("SELECT * FROM service_categories WHERE status = 'active' ORDER BY name");
    $serviceCategories = $stmt->fetchAll();
} catch (PDOException $e) {
    $serviceCategories = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $service_category_id = (int)($_POST['service_category_id'] ?? 0);
    $status = $_POST['status'] ?? 'active';

    // Resim yükleme
    $image = $service['image'];
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload = uploadImage($_FILES['image'], 'services');
        if ($upload['success']) {
            if (!empty($image)) {
                $oldPath = str_replace(UPLOAD_URL, UPLOAD_PATH, $image);
                deleteImage($oldPath);
            }
            $image = $upload['url'];
        } else {
            $error = $upload['message'];
        }
    }

    if (empty($title)) {
        $error = 'Hizmet başlığı gereklidir.';
    } elseif (empty($description)) {
        $error = 'Açıklama gereklidir.';
    } else {
        try {
            $stmt = $pdo->prepare("
                UPDATE services
                SET service_category_id = ?, title = ?, description = ?, price = ?, image = ?, status = ?
                WHERE id = ? AND company_id = ?
            ");
            $stmt->execute([
                $service_category_id ?: null,
                $title,
                $description,
                $price !== '' ? $price : null,
                $image,
                $status,
                $id,
                $companyId
            ]);

            setFlashMessage('success', 'Hizmet başarıyla güncellendi.');
            redirect('index.php');
        } catch (PDOException $e) {
            $error = 'Hizmet güncellenirken bir hata oluştu.';
            if (defined('DEBUG') && DEBUG) {
                $error .= ' ' . $e->getMessage();
            }
        }
    }
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Hizmet 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-8">
                    <div class="mb-3">
                        <label for="title" class="form-label">Hizmet Başlığı <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" value="<?= e($_POST['title'] ?? $service['title']) ?>" required>
                    </div>

                    <div class="mb-3">
                        <label for="description" class="form-label">Açıklama <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="description" name="description" rows="6" required><?= e($_POST['description'] ?? $service['description']) ?></textarea>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="image" class="form-label">Hizmet Görseli</label>
                        <?php if (!empty($service['image'])): ?>
                            <div class="mb-2">
                                <img src="<?= e(getImageUrl($service['image'])) ?>" alt="" class="img-thumbnail w-100" style="max-height: 200px; object-fit: cover;">
                            </div>
                        <?php endif; ?>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*">
                    </div>

                    <div class="mb-3">
                        <label for="service_category_id" class="form-label">Kategori</label>
                        <?php $selectedCat = (string)($_POST['service_category_id'] ?? $service['service_category_id']); ?>
                        <select class="form-select" id="service_category_id" name="service_category_id">
                            <option value="">Kategori seçin</option>
                            <?php foreach ($serviceCategories as $cat): ?>
                                <option value="<?= (int)$cat['id'] ?>" <?= (string)$cat['id'] === $selectedCat ? 'selected' : '' ?>>
                                    <?= e($cat['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="price" class="form-label">Fiyat</label>
                        <input type="number" step="0.01" class="form-control" id="price" name="price" value="<?= e($_POST['price'] ?? $service['price']) ?>" placeholder="₺">
                    </div>

                    <div class="mb-3">
                        <label for="status" class="form-label">Durum</label>
                        <?php $statusVal = ($_POST['status'] ?? $service['status'] ?? 'active'); ?>
                        <select class="form-select" id="status" name="status">
                            <option value="active" <?= $statusVal === 'active' ? 'selected' : '' ?>>Aktif</option>
                            <option value="inactive" <?= $statusVal === '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'; ?>


