<?php

namespace App\Http\Controllers\Agency\Customer;

use App\Http\Controllers\Controller;
use App\Models\Customer\Customer;
use App\Models\Customer\CustomerActivity;
use App\Models\Customer\CustomerDocument;
use App\Models\Customer\CustomerDocumentType;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CustomerActivityController extends Controller
{
     use AuthorizesRequests;

     // ─── INDEX ────────────────────────────────────────────────────────────────

     public function index(Request $request, Customer $customer)
     {
          $this->authorizeAgency($customer);

          $query = CustomerActivity::where('customer_id', $customer->id)
               ->with(['performedBy', 'assignedTo', 'resolvedBy']);

          // -- Filtreler
          if ($request->filled('type')) {
               $query->byType($request->type);
          }

          if ($request->filled('status')) {
               $query->byStatus($request->status);
          }

          if ($request->filled('priority')) {
               $query->byPriority($request->priority);
          }

          if ($request->boolean('requires_follow_up')) {
               $query->requiresFollowUp();
          }

          if ($request->boolean('overdue')) {
               $query->overdue();
          }

          // -- Tarih aralığı
          if ($request->filled('date_from')) {
               $query->where('activity_date', '>=', $request->date_from);
          }

          if ($request->filled('date_to')) {
               $query->where('activity_date', '<=', $request->date_to . ' 23:59:59');
          }

          // -- Sıralama
          $sortBy = $request->get('sort', 'activity_date');
          $sortDir = $request->get('dir', 'desc');
          $query->orderBy($sortBy, $sortDir);

          $activities = $query->paginate(15)->withQueryString();

          $stats = [
               'total' => CustomerActivity::where('customer_id', $customer->id)->count(),
               'pending' => CustomerActivity::where('customer_id', $customer->id)->pending()->count(),
               'overdue' => CustomerActivity::where('customer_id', $customer->id)->overdue()->count(),
               'follow_up' => CustomerActivity::where('customer_id', $customer->id)->requiresFollowUp()->count(),
               'completed' => CustomerActivity::where('customer_id', $customer->id)->completed()->count(),
          ];

          return view('agency.customers.activities.index', compact('customer', 'activities', 'stats'));
     }

     // ─── CREATE / STORE ───────────────────────────────────────────────────────

     public function create(Customer $customer)
     {
          $this->authorizeAgency($customer);

          $agents = \App\Models\User::byAgency(Auth::user()->currentAgencyId())
               ->active()
               ->orderBy('first_name')
               ->get();

          return view('agency.customers.activities.create', compact('customer', 'agents'));
     }

     public function store(Request $request, Customer $customer)
     {
          $this->authorizeAgency($customer);

          $validated = $request->validate([
               'activity_type' => 'required|string|in:' . implode(',', \App\Enums\ActivityType::values()),
               'subject' => 'nullable|string|max:255',
               'description' => 'nullable|string',
               'direction' => 'nullable|in:inbound,outbound',
               'contact_method' => 'nullable|string|in:phone,email,in_person,whatsapp,sms',
               'duration_minutes' => 'nullable|integer|min:1',
               'outcome' => 'nullable|in:successful,unsuccessful,follow_up_required,no_answer',
               'activity_date' => 'nullable|date',
               'scheduled_date' => 'nullable|date',
               'due_date' => 'nullable|date',
               'reference_no' => 'nullable|string|max:100',
               'location' => 'nullable|string|max:255',
               'meeting_link' => 'nullable|string|max:255',
               'metadata' => 'nullable|array',
               'amount' => 'nullable|numeric|min:0',
               'currency' => 'nullable|string|size:3',
               'assigned_to' => 'nullable|exists:users,id',
               'status' => 'nullable|in:pending,in_progress,completed,cancelled,deferred',
               'priority' => 'nullable|in:low,normal,high,urgent',
               'is_important' => 'boolean',
               'requires_follow_up' => 'boolean',
               'follow_up_date' => 'nullable|date',
               'result' => 'nullable|string',
               'action_taken' => 'nullable|string',
               'next_steps' => 'nullable|string',
               'internal_notes' => 'nullable|string',
               'customer_notes' => 'nullable|string',
               'attachments' => 'nullable|array',
               'attachment' => 'nullable|file|max:10240',
               'tags' => 'nullable|array',
               'complaint_category' => 'nullable|string|max:100',
               'complaint_severity' => 'nullable|in:low,medium,high,critical',
               'booking_reference' => 'nullable|string|max:50',
               'booking_amount' => 'nullable|numeric|min:0',
               'booking_status' => 'nullable|string|max:50',
               'is_visible_to_customer' => 'boolean',
               'is_private' => 'boolean',
          ]);

          $validated['agency_id'] = Auth::user()->currentAgencyId();
          $validated['customer_id'] = $customer->id;
          $validated['status'] = $validated['status'] ?? 'completed';
          $validated['priority'] = $validated['priority'] ?? 'normal';

          // Dosya yükleme kontrolü
          if ($request->hasFile('attachment')) {
               $file = $request->file('attachment');
               $path = $file->store('customers/activities/' . $customer->id, 'public');
               
               $attachments = $validated['attachments'] ?? [];
               $attachments[] = [
                    'name' => $file->getClientOriginalName(),
                    'path' => $path,
                    'size' => $file->getSize(),
                    'mime' => $file->getMimeType(),
                    'uploaded_at' => now()->toDateTimeString(),
               ];
               $validated['attachments'] = $attachments;

               // Müşteri Dökümanları tablosuna da kaydet
               $docType = CustomerDocumentType::where('agency_id', Auth::user()->currentAgencyId())
                    ->where('code', 'other')
                    ->first() ?? CustomerDocumentType::where('agency_id', Auth::user()->currentAgencyId())->first();

               CustomerDocument::create([
                    'agency_id' => Auth::user()->currentAgencyId(),
                    'customer_id' => $customer->id,
                    'document_type_id' => $docType?->id,
                    'file_name' => $file->getClientOriginalName(),
                    'file_path' => $path,
                    'file_size' => $file->getSize(),
                    'mime_type' => $file->getMimeType(),
                    'notes' => 'Aktivite Eki: ' . ($request->subject ?? $validated['activity_type']),
                    'created_by' => Auth::id(),
               ]);
          }

          $activity = CustomerActivity::create($validated);

          if ($request->ajax() || $request->wantsJson()) {
               return response()->json([
                    'success' => true,
                    'message' => 'Aktivite başarıyla oluşturuldu.',
                    'activity' => $activity
               ]);
          }

          return redirect()
               ->route('agency.customers.activities.index', $customer)
               ->with('success', 'Aktivite başarıyla oluşturuldu.');
     }

     // ─── SHOW ─────────────────────────────────────────────────────────────────

     public function show(Customer $customer, CustomerActivity $activity)
     {
          $this->authorizeAgency($customer);
          $this->authorizeActivity($customer, $activity);

          $activity->load(['performedBy', 'assignedTo', 'resolvedBy', 'creator']);

          return view('agency.customers.activities.show', compact('customer', 'activity'));
     }

     // ─── EDIT / UPDATE ────────────────────────────────────────────────────────

     public function edit(Customer $customer, CustomerActivity $activity)
     {
          $this->authorizeAgency($customer);
          $this->authorizeActivity($customer, $activity);

          $agents = \App\Models\User::byAgency(Auth::user()->currentAgencyId())
               ->active()
               ->orderBy('first_name')
               ->get();

          return view('agency.customers.activities.edit', compact('customer', 'activity', 'agents'));
     }

     public function update(Request $request, Customer $customer, CustomerActivity $activity)
     {
          $this->authorizeAgency($customer);
          $this->authorizeActivity($customer, $activity);

          $validated = $request->validate([
               'activity_type' => 'required|string|in:' . implode(',', \App\Enums\ActivityType::values()),
               'subject' => 'nullable|string|max:255',
               'description' => 'nullable|string',
               'direction' => 'nullable|in:inbound,outbound',
               'contact_method' => 'nullable|string|in:phone,email,in_person,whatsapp,sms',
               'duration_minutes' => 'nullable|integer|min:1',
               'outcome' => 'nullable|in:successful,unsuccessful,follow_up_required,no_answer',
               'activity_date' => 'nullable|date',
               'scheduled_date' => 'nullable|date',
               'due_date' => 'nullable|date',
               'reference_no' => 'nullable|string|max:100',
               'location' => 'nullable|string|max:255',
               'meeting_link' => 'nullable|string|max:255',
               'metadata' => 'nullable|array',
               'assigned_to' => 'nullable|exists:users,id',
               'status' => 'nullable|in:pending,in_progress,completed,cancelled,deferred',
               'priority' => 'nullable|in:low,normal,high,urgent',
               'is_important' => 'boolean',
               'requires_follow_up' => 'boolean',
               'follow_up_date' => 'nullable|date',
               'result' => 'nullable|string',
               'action_taken' => 'nullable|string',
               'next_steps' => 'nullable|string',
               'internal_notes' => 'nullable|string',
               'customer_notes' => 'nullable|string',
               'complaint_category' => 'nullable|string|max:100',
               'complaint_severity' => 'nullable|in:low,medium,high,critical',
               'booking_reference' => 'nullable|string|max:50',
               'booking_amount' => 'nullable|numeric|min:0',
               'booking_status' => 'nullable|string|max:50',
               'is_visible_to_customer' => 'boolean',
               'is_private' => 'boolean',
          ]);

          $validated['status'] = $validated['status'] ?? $activity->status;
          $validated['priority'] = $validated['priority'] ?? $activity->priority;
          $activity->update($validated);

          return back()->with('success', 'Aktivite başarıyla güncellendi.');
     }

     // ─── DELETE ───────────────────────────────────────────────────────────────

     public function destroy(Customer $customer, CustomerActivity $activity)
     {
          $this->authorizeAgency($customer);
          $this->authorizeActivity($customer, $activity);

          $activity->delete();

          return redirect()
               ->route('agency.customers.activities.index', $customer)
               ->with('success', 'Aktivite silindi.');
     }

     // ─── QUICK ACTIONS ────────────────────────────────────────────────────────

     /** Tamamlandı olarak işaretle */
     public function complete(Customer $customer, CustomerActivity $activity)
     {
          $this->authorizeAgency($customer);
          $this->authorizeActivity($customer, $activity);

          $activity->markAsCompleted();

          return response()->json([
               'success' => true,
               'message' => 'Aktivite tamamlandı olarak işaretlendi.',
          ]);
     }

     /** Şikayeti çözüme kavuştur */
     public function resolve(Request $request, Customer $customer, CustomerActivity $activity)
     {
          $this->authorizeAgency($customer);
          $this->authorizeActivity($customer, $activity);

          $request->validate([
               'resolution' => 'required|string|max:1000',
          ]);

          $activity->markAsResolved($request->resolution);

          return response()->json([
               'success' => true,
               'message' => 'Şikayet çözüme kavuşturuldu.',
          ]);
     }

     /** Bekleyen follow-up'lar (panel widget için) */
     public function pendingFollowUps(Request $request)
     {
          $agencyId = Auth::user()->currentAgencyId();

          $activities = CustomerActivity::whereHas('customer', fn($q) => $q->byAgency($agencyId))
               ->requiresFollowUp()
               ->whereNotIn('status', ['completed', 'cancelled'])
               ->with(['customer', 'assignedTo'])
               ->orderBy('follow_up_date')
               ->limit(20)
               ->get();

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

     // ─── YARDIMCI ─────────────────────────────────────────────────────────────

     protected function authorizeAgency(Customer $customer): void
     {
          if ($customer->agency_id !== Auth::user()->currentAgencyId()) {
               abort(403, 'Bu müşteriye erişim yetkiniz yok.');
          }
     }

     protected function authorizeActivity(Customer $customer, CustomerActivity $activity): void
     {
          if ($activity->customer_id !== $customer->id) {
               abort(404);
          }
     }
}
