<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class DepartmentController extends Controller
{
    public function index()
    {
        $departments = Department::withCount(['jobPostings', 'applications'])
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return view('admin.departmanlar.index', compact('departments'));
    }

    public function create()
    {
        return view('admin.departmanlar.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name'                      => 'required|string|max:100',
            'description'               => 'nullable|string|max:2000',
            'cover_image'               => 'nullable|image|mimes:jpg,jpeg,png,webp|max:5120',
            'is_active'                 => 'boolean',
            'accepts_open_applications' => 'boolean',
            'sort_order'                => 'integer|min:0',
        ]);

        $data = $request->only(['name', 'description', 'sort_order']);
        $data['slug']                      = Str::slug($request->name);
        $data['is_active']                 = $request->boolean('is_active', true);
        $data['accepts_open_applications'] = $request->boolean('accepts_open_applications');

        if ($request->hasFile('cover_image')) {
            $file = $request->file('cover_image');
            if ($file->isValid()) {
                $path = $file->store('departments', 'public');
                if ($path) {
                    $data['cover_image'] = $path;
                } else {
                    Log::error('Departman görseli kaydedilemedi (store false döndü)');
                    return back()->withInput()->with('error', 'Görsel kaydedilemedi, lütfen tekrar deneyin.');
                }
            } else {
                Log::error('Departman görseli geçersiz: ' . $file->getErrorMessage());
                return back()->withInput()->with('error', 'Yüklenen görsel geçersiz: ' . $file->getErrorMessage());
            }
        }

        Department::create($data);

        return redirect()->route('admin.departmanlar.index')
            ->with('success', 'Departman oluşturuldu.');
    }

    public function show(Department $departman)
    {
        $departman->loadCount(['jobPostings', 'applications']);
        return view('admin.departmanlar.show', compact('departman'));
    }

    public function edit(Department $departman)
    {
        return view('admin.departmanlar.edit', compact('departman'));
    }

    public function update(Request $request, Department $departman)
    {
        $request->validate([
            'name'                      => 'required|string|max:100',
            'description'               => 'nullable|string|max:2000',
            'cover_image'               => 'nullable|image|mimes:jpg,jpeg,png,webp|max:5120',
            'is_active'                 => 'boolean',
            'accepts_open_applications' => 'boolean',
            'sort_order'                => 'integer|min:0',
        ]);

        $data = $request->only(['name', 'description', 'sort_order']);
        $data['slug']                      = Str::slug($request->name);
        $data['is_active']                 = $request->boolean('is_active');
        $data['accepts_open_applications'] = $request->boolean('accepts_open_applications');

        // Mevcut görseli kaldır
        if ($request->boolean('remove_cover_image') && $departman->cover_image) {
            Storage::disk('public')->delete($departman->cover_image);
            $data['cover_image'] = null;
        }

        // Yeni görsel yükle
        if ($request->hasFile('cover_image')) {
            $file = $request->file('cover_image');
            if ($file->isValid()) {
                // Eskiyi sil
                if ($departman->cover_image) {
                    Storage::disk('public')->delete($departman->cover_image);
                }
                $path = $file->store('departments', 'public');
                if ($path) {
                    $data['cover_image'] = $path;
                } else {
                    Log::error('Departman görseli güncellenemedi (store false döndü)');
                    return back()->withInput()->with('error', 'Görsel kaydedilemedi, lütfen tekrar deneyin.');
                }
            } else {
                Log::error('Departman görseli geçersiz (update): ' . $file->getErrorMessage());
                return back()->withInput()->with('error', 'Yüklenen görsel geçersiz: ' . $file->getErrorMessage());
            }
        }

        $departman->update($data);

        return redirect()->route('admin.departmanlar.index')
            ->with('success', 'Departman güncellendi.');
    }

    public function destroy(Department $departman)
    {
        // Kapak görseli sil
        if ($departman->cover_image) {
            Storage::disk('public')->delete($departman->cover_image);
        }

        // Banner görseli sil (varsa)
        if ($departman->cover_image_banner) {
            Storage::disk('public')->delete($departman->cover_image_banner);
        }

        $departman->delete();

        return back()->with('success', 'Departman silindi.');
    }

    public function toggleActive(Department $departman)
    {
        $newState = ! $departman->is_active;
        $departman->update(['is_active' => $newState]);

        return back()->with('success', $newState ? 'Departman aktif edildi.' : 'Departman pasif edildi.');
    }

    public function toggleOpenApplications(Department $departman)
    {
        $newState = ! $departman->accepts_open_applications;
        $departman->update(['accepts_open_applications' => $newState]);

        return back()->with('success', $newState
            ? 'Açık başvuru aktif edildi.'
            : 'Açık başvuru kapatıldı.');
    }
}