<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CouponDestroyRequest;
use App\Http\Requests\Admin\CouponEditRequest;
use App\Http\Requests\Admin\CouponIndexRequest;
use App\Http\Requests\Admin\CouponShowRequest;
use App\Http\Requests\Admin\CouponStoreRequest;
use App\Http\Requests\Admin\CouponUpdateRequest;
use App\Models\Country;
use App\Models\Coupon;
use App\Models\CouponCriteria;
use App\Models\Currency;
use App\Models\Product;
use App\Models\ProductGroup;
use App\Models\Tld;
use App\Traits\LogsAdminActivity;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class CouponController extends Controller
{
    use LogsAdminActivity;
    /**
     * Kupon listesi sayfasını göster
     */
    public function index(CouponIndexRequest $request)
    {
        $currencies = Currency::all();

        return view('admin.coupons.index', compact('currencies'));
    }

    /**
     * DataTables için kupon verilerini döndür
     */
    public function records(CouponIndexRequest $request): JsonResponse
    {
        $totalRecords = Coupon::count();

        $query = Coupon::with(['currency', 'createdByAdmin'])
            ->select('coupons.*');

        // Arama filtresi
        if ($request->filled('search')) {
            $rawSearch = $request->input('search');
            $search = is_array($rawSearch) ? ($rawSearch['value'] ?? '') : (string) $rawSearch;
            $query->where(function ($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                    ->orWhere('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Tip filtresi
        if ($request->filled('type')) {
            $query->where('type', $request->input('type'));
        }

        // Durum filtresi
        if ($request->filled('status')) {
            $status = $request->input('status');
            switch ($status) {
                case 'active':
                    $query->where('is_active', true)
                        ->where(function ($q) {
                            $q->whereNull('starts_at')
                                ->orWhere('starts_at', '<=', Carbon::now());
                        })
                        ->where(function ($q) {
                            $q->whereNull('expires_at')
                                ->orWhere('expires_at', '>', Carbon::now());
                        })
                        ->where(function ($q) {
                            $q->whereNull('usage_limit')
                                ->orWhereRaw('usage_count < usage_limit');
                        });
                    break;
                case 'inactive':
                    $query->where('is_active', false);
                    break;
                case 'expired':
                    $query->where('expires_at', '<', Carbon::now());
                    break;
                case 'not_started':
                    $query->where('starts_at', '>', Carbon::now());
                    break;
                case 'limit_reached':
                    $query->whereRaw('usage_count >= usage_limit');
                    break;
            }
        }

        // Para birimi filtresi
        if ($request->filled('currency_id')) {
            $query->where('currency_id', $request->input('currency_id'));
        }

        $total = $query->count();

        // Sıralama
        $orderColumn = $request->input('order.0.column', 0);
        $orderDir = $request->input('order.0.dir', 'desc');

        $columns = ['id', 'code', 'name', 'type', 'discount_value', 'currency_id', 'usage_count', 'is_active', 'created_at'];

        if (isset($columns[$orderColumn])) {
            $query->orderBy($columns[$orderColumn], $orderDir);
        } else {
            $query->orderBy('created_at', 'desc');
        }

        // Sayfalama
        $start = $request->input('start', 0);
        $length = $request->input('length', 10);

        $coupons = $query->skip($start)->take($length)->get();

        $data = $coupons->map(function ($coupon) {
            return [
                'id' => $coupon->id,
                'code' => $coupon->code,
                'name' => $coupon->name,
                'type' => $coupon->type,
                'discount_value' => $coupon->discount_value,
                'currency_code' => $coupon->currency?->code ?? '-',
                'min_order_amount' => $coupon->min_order_amount,
                'max_discount_amount' => $coupon->max_discount_amount,
                'usage_count' => $coupon->usage_count,
                'usage_limit' => $coupon->usage_limit,
                'is_active' => $coupon->is_active,
                'status' => $coupon->status,
                'status_badge_class' => $coupon->status_badge_class,
                'starts_at' => $coupon->starts_at?->format('d.m.Y H:i'),
                'expires_at' => $coupon->expires_at?->format('d.m.Y H:i'),
                'created_at' => $coupon->created_at->format('d.m.Y H:i'),
                'created_by_admin' => $coupon->createdByAdmin?->name,
            ];
        });

        return response()->json([
            'draw' => $request->input('draw'),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $total,
            'data' => $data,
        ]);
    }

    /**
     * Kupon oluşturma sayfasını göster
     */
    public function create()
    {
        $currencies = Currency::all();
        $products = Product::all();
        $productGroups = ProductGroup::all();
        $tlds = Tld::all();
        $countries = Country::all();

        return view('admin.coupons.create', compact(
            'currencies', 'products', 'productGroups', 'tlds', 'countries'
        ));
    }

    /**
     * Yeni kupon oluştur
     */
    public function store(CouponStoreRequest $request): JsonResponse
    {
        try {
            $coupon = DB::transaction(function () use ($request) {
                $validated = $request->validated();

                // Kupon oluştur
                $coupon = Coupon::create([
                    'code' => $validated['code'],
                    'name' => $validated['name'],
                    'description' => $validated['description'] ?? null,
                    'type' => $validated['type'],
                    'discount_value' => $validated['discount_value'],
                    'currency_id' => $validated['currency_id'] ?? null,
                    'min_order_amount' => $validated['min_order_amount'] ?? 0,
                    'max_discount_amount' => $validated['max_discount_amount'] ?? null,
                    'usage_limit' => $validated['usage_limit'] ?? null,
                    'is_active' => $validated['is_active'] ?? true,
                    'starts_at' => $validated['starts_at'] ?? null,
                    'expires_at' => $validated['expires_at'] ?? null,
                    'created_by_admin_id' => auth()->id(),
                    // YENİ: Hedefleme alanları
                    'target_type' => $validated['target_type'] ?? 'all',
                    'target_products' => $validated['target_products'] ?? null,
                    'target_groups' => $validated['target_groups'] ?? null,
                    'target_tlds' => $validated['target_tlds'] ?? null,
                ]);

                // Kriterleri oluştur
                if (! empty($validated['criteria'])) {
                    foreach ($validated['criteria'] as $criterionData) {
                        CouponCriteria::create([
                            'coupon_id' => $coupon->id,
                            'criteria_type' => $criterionData['criteria_type'],
                            'criteria_value' => $criterionData['criteria_value'],
                            'criteria_operator' => $criterionData['criteria_operator'],
                            'is_required' => $criterionData['is_required'] ?? true,
                            'order' => $criterionData['order'] ?? 0,
                        ]);
                    }
                }

                return $coupon;
            });

            $this->logCreated($coupon, "Created coupon #{$coupon->id} - {$coupon->code}");

            return response()->json([
                'success' => true,
                'message' => __('admin/coupons.messages_created'),
                'redirect' => route('admin.coupons.index'),
            ]);

        } catch (\Exception $e) {
            \Log::error('Coupon create failed', [
                'admin_id' => auth()->id(),
                'exception' => get_class($e),
                'message' => $e->getMessage(),
                'file' => $e->getFile().':'.$e->getLine(),
            ]);

            return response()->json([
                'success' => false,
                'message' => __('admin/common.messages_coupon_create_error'),
            ], 500);
        }
    }

    /**
     * Kupon düzenleme sayfasını göster
     */
    public function edit(CouponEditRequest $request, Coupon $coupon)
    {
        $currencies = Currency::all();
        $products = Product::all();
        $productGroups = ProductGroup::all();
        $tlds = Tld::all();
        $countries = Country::all();

        return view('admin.coupons.edit', compact('coupon', 'currencies', 'products', 'productGroups', 'tlds', 'countries'));
    }

    /**
     * Kuponu güncelle
     */
    public function update(CouponUpdateRequest $request, Coupon $coupon)
    {
        try {
            DB::transaction(function () use ($request, $coupon) {
                // Ana kupon bilgilerini güncelle - YENİ: hedefleme alanları dahil
                $coupon->update($request->only([
                    'code', 'name', 'description', 'type', 'discount_value',
                    'currency_id', 'min_order_amount', 'max_discount_amount',
                    'usage_limit', 'is_active', 'starts_at', 'expires_at',
                    'target_type', 'target_products', 'target_groups', 'target_tlds',
                ]));

                // Mevcut kriterleri sil
                $coupon->criteria()->delete();

                // Yeni kriterleri ekle
                if ($request->has('criteria')) {
                    foreach ($request->input('criteria') as $criterionData) {
                        if (! empty($criterionData['criteria_type']) && ! empty($criterionData['criteria_value'])) {
                            CouponCriteria::create([
                                'coupon_id' => $coupon->id,
                                'criteria_type' => $criterionData['criteria_type'],
                                'criteria_value' => $criterionData['criteria_value'],
                                'criteria_operator' => $criterionData['criteria_operator'] ?? 'equals',
                                'is_required' => $criterionData['is_required'] ?? true,
                                'order' => $criterionData['order'] ?? 0,
                            ]);
                        }
                    }
                }
            });

            $this->logUpdated($coupon, "Updated coupon #{$coupon->id} - {$coupon->code}");

            return response()->json([
                'success' => true,
                'message' => __('admin/coupons.messages_updated'),
                'redirect' => route('admin.coupons.index'),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => __('admin/common.messages_coupon_update_error'),
            ], 500);
        }
    }

    /**
     * Kuponu sil
     */
    public function destroy(CouponDestroyRequest $request, Coupon $coupon): JsonResponse
    {
        try {
            // Kupon kullanılmış mı kontrol et
            if ($coupon->usage_count > 0) {
                return response()->json([
                    'success' => false,
                    'message' => __('admin/coupons.messages_cannot_delete'),
                ], 422);
            }

            $this->logDeleted($coupon, "Deleted coupon #{$coupon->id} - {$coupon->code}");

            $coupon->delete();

            return response()->json([
                'success' => true,
                'message' => __('admin/coupons.messages_deleted'),
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => __('admin/coupons.messages_delete_error'),
            ], 500);
        }
    }

    /**
     * Kupon detay sayfasını göster
     */
    public function show(CouponShowRequest $request, Coupon $coupon)
    {
        $coupon->load(['criteria', 'currency', 'createdByAdmin', 'usages.client', 'usages.order']);

        return view('admin.coupons.show', compact('coupon'));
    }

    /**
     * Kupon kullanım istatistikleri
     */
    public function statistics(Coupon $coupon): JsonResponse
    {
        $coupon->load(['usages' => function ($query) {
            $query->orderBy('used_at', 'desc')->limit(10);
        }, 'usages.client']);

        $statistics = [
            'total_usage' => $coupon->usage_count,
            'remaining_usage' => $coupon->usage_limit ? $coupon->usage_limit - $coupon->usage_count : null,
            'total_discount' => $coupon->usages->sum('discount_amount'),
            'average_discount' => $coupon->usages->count() > 0 ? $coupon->usages->avg('discount_amount') : 0,
            'recent_usages' => $coupon->usages->map(function ($usage) {
                return [
                    'client_name' => $usage->client->name,
                    'discount_amount' => $usage->discount_amount,
                    'used_at' => $usage->used_at->format('d.m.Y H:i'),
                ];
            }),
        ];

        return response()->json($statistics);
    }
}
