<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Offer;
use App\Models\Category;
use Illuminate\Http\Request;

class OfferController extends Controller
{
    /**
     * Display offer listing
     */
    public function index(Request $request)
    {
        $query = Offer::with(['venue.business', 'category']);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                    ->orWhereHas('venue', function($q2) use ($search) {
                        $q2->where('name', 'like', "%{$search}%");
                    });
            });
        }

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

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        if ($request->filled('discount_type')) {
            $query->where('discount_type', $request->discount_type);
        }

        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $offers = $query->paginate(20);

        $stats = [
            'total' => Offer::count(),
            'active' => Offer::where('status', 'active')->count(),
            'expired' => Offer::where('status', 'expired')->count(),
            'featured' => Offer::where('is_featured', true)->count(),
            'total_redemptions' => Offer::sum('redemption_count'),
        ];

        $categories = Category::all();

        return view('admin.offers.index', compact('offers', 'stats', 'categories'));
    }

    /**
     * Show offer details
     */
    public function show($id)
    {
        $offer = Offer::with([
            'venue.business',
            'category',
            'redemptions.user'
        ])->findOrFail($id);

        $recentRedemptions = $offer->redemptions()
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        return view('admin.offers.show', compact('offer', 'recentRedemptions'));
    }

    /**
     * Approve offer
     */
    public function approve($id)
    {
        $offer = Offer::findOrFail($id);

        $offer->update([
            'approval_status' => 'approved',
            'status' => 'active'
        ]);

        // Create notification
        \App\Models\Notification::create([
            'notifiable_type' => 'App\\Models\\User',
            'notifiable_id' => $offer->venue->business->owner_id,
            'type' => 'offer_approved',
            'data' => json_encode([
                'title' => 'Offer Approved',
                'message' => "Your offer '{$offer->title}' has been approved and is now active.",
                'offer_id' => $offer->id
            ])
        ]);

        // Log audit
        \App\Models\AuditLog::logAction(
            'approve_offer',
            $offer,
            null,
            ['status' => 'approved']
        );

        return response()->json([
            'success' => true,
            'message' => 'Offer approved successfully'
        ]);
    }

    /**
     * Reject offer
     */
    public function reject(Request $request, $id)
    {
        $request->validate([
            'reason' => 'required|string'
        ]);

        $offer = Offer::findOrFail($id);

        $offer->update([
            'approval_status' => 'rejected',
            'status' => 'inactive',
            'rejection_reason' => $request->reason
        ]);

        // Create notification
        \App\Models\Notification::create([
            'notifiable_type' => 'App\\Models\\User',
            'notifiable_id' => $offer->venue->business->owner_id,
            'type' => 'offer_rejected',
            'data' => json_encode([
                'title' => 'Offer Rejected',
                'message' => "Your offer '{$offer->title}' has been rejected. Reason: {$request->reason}",
                'offer_id' => $offer->id
            ])
        ]);

        // Log audit
        \App\Models\AuditLog::logAction(
            'reject_offer',
            $offer,
            null,
            ['status' => 'rejected', 'reason' => $request->reason]
        );

        return response()->json([
            'success' => true,
            'message' => 'Offer rejected successfully'
        ]);
    }

    /**
     * Pause offer
     */
    public function pause($id)
    {
        $offer = Offer::findOrFail($id);

        $offer->update([
            'status' => 'paused'
        ]);

        // Create notification
        \App\Models\Notification::create([
            'notifiable_type' => 'App\\Models\\User',
            'notifiable_id' => $offer->venue->business->owner_id,
            'type' => 'offer_paused',
            'data' => json_encode([
                'title' => 'Offer Paused',
                'message' => "Your offer '{$offer->title}' has been paused by admin.",
                'offer_id' => $offer->id
            ])
        ]);

        // Log audit
        \App\Models\AuditLog::logAction(
            'pause_offer',
            $offer,
            null,
            ['status' => 'paused']
        );

        return response()->json([
            'success' => true,
            'message' => 'Offer paused successfully'
        ]);
    }

    /**
     * Suspend offer
     */
    public function suspend(Request $request, $id)
    {
        $offer = Offer::findOrFail($id);

        $offer->update([
            'status' => 'suspended'
        ]);

        // Create notification
        \App\Models\Notification::create([
            'notifiable_type' => 'App\\Models\\User',
            'notifiable_id' => $offer->venue->business->owner_id,
            'type' => 'offer_suspended',
            'data' => json_encode([
                'title' => 'Offer Suspended',
                'message' => "Your offer '{$offer->title}' has been suspended.",
                'offer_id' => $offer->id
            ])
        ]);

        // Log audit
        \App\Models\AuditLog::logAction(
            'suspend_offer',
            $offer,
            null,
            ['status' => 'suspended']
        );

        return response()->json([
            'success' => true,
            'message' => 'Offer suspended successfully'
        ]);
    }

    /**
     * Activate offer
     */
    public function activate($id)
    {
        $offer = Offer::findOrFail($id);

        $offer->update([
            'status' => 'active'
        ]);

        // Create notification
        \App\Models\Notification::create([
            'notifiable_type' => 'App\\Models\\User',
            'notifiable_id' => $offer->venue->business->owner_id,
            'type' => 'offer_activated',
            'data' => json_encode([
                'title' => 'Offer Activated',
                'message' => "Your offer '{$offer->title}' has been activated.",
                'offer_id' => $offer->id
            ])
        ]);

        // Log audit
        \App\Models\AuditLog::logAction(
            'activate_offer',
            $offer,
            null,
            ['status' => 'active']
        );

        return response()->json([
            'success' => true,
            'message' => 'Offer activated successfully'
        ]);
    }

    /**
     * Toggle featured status
     */
    public function toggleFeatured($id)
    {
        $offer = Offer::findOrFail($id);

        $offer->update([
            'is_featured' => !$offer->is_featured
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Featured status updated',
            'is_featured' => $offer->is_featured
        ]);
    }

    /**
     * Update offer status
     */
    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:active,inactive,expired'
        ]);

        $offer = Offer::findOrFail($id);

        $offer->update([
            'status' => $request->status
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Offer status updated',
            'status' => $offer->status
        ]);
    }

    /**
     * Delete offer
     */
    public function destroy($id)
    {
        $offer = Offer::findOrFail($id);

        // Check if offer has redemptions
        if ($offer->redemptions()->count() > 0) {
            return response()->json([
                'success' => false,
                'message' => 'Cannot delete offer with redemption history'
            ], 400);
        }

        $offer->delete();

        return response()->json([
            'success' => true,
            'message' => 'Offer deleted successfully'
        ]);
    }

    /**
     * Bulk actions
     */
    public function bulkAction(Request $request)
    {
        $request->validate([
            'action' => 'required|in:activate,deactivate,expire,feature,unfeature,delete',
            'offer_ids' => 'required|array',
            'offer_ids.*' => 'exists:offers,id'
        ]);

        $offers = Offer::whereIn('id', $request->offer_ids);

        switch ($request->action) {
            case 'activate':
                $offers->update(['status' => 'active']);
                $message = 'Offers activated successfully';
                break;
            case 'deactivate':
                $offers->update(['status' => 'inactive']);
                $message = 'Offers deactivated successfully';
                break;
            case 'expire':
                $offers->update(['status' => 'expired']);
                $message = 'Offers expired successfully';
                break;
            case 'feature':
                $offers->update(['is_featured' => true]);
                $message = 'Offers featured successfully';
                break;
            case 'unfeature':
                $offers->update(['is_featured' => false]);
                $message = 'Offers unfeatured successfully';
                break;
            case 'delete':
                $offers->delete();
                $message = 'Offers deleted successfully';
                break;
        }

        return response()->json([
            'success' => true,
            'message' => $message
        ]);
    }

    /**
     * Export offers
     */
    public function export()
    {
        $offers = Offer::with(['venue.business', 'category'])->get();

        $csv = "ID,Title,Business,Venue,Discount,Status,Redemptions,Valid From,Valid Until\n";

        foreach ($offers as $offer) {
            $csv .= sprintf(
                "%d,%s,%s,%s,%s %s,%s,%d,%s,%s\n",
                $offer->id,
                $offer->title,
                $offer->venue->business->business_name,
                $offer->venue->name,
                $offer->discount_value,
                $offer->discount_type,
                $offer->status,
                $offer->redemption_count,
                $offer->valid_from->format('Y-m-d'),
                $offer->valid_until->format('Y-m-d')
            );
        }

        return response($csv)
            ->header('Content-Type', 'text/csv')
            ->header('Content-Disposition', 'attachment; filename="offers.csv"');
    }
    /**
     * Show edit form
     */
    public function edit($id)
    {
        $offer = Offer::with(['venue.business', 'category'])->findOrFail($id);
        $categories = Category::where('is_active', true)->get();
        $venues = \App\Models\Venue::where('status', 'active')->get();

        return view('admin.offers.edit', compact('offer', 'categories', 'venues'));
    }

    /**
     * Update offer
     */
    public function update(Request $request, $id)
    {
        $offer = Offer::findOrFail($id);

        $validated = $request->validate([
            'venue_id' => 'required|exists:venues,id',
            'category_id' => 'required|exists:categories,id',
            'title' => 'required|string|max:255',
            'title_ar' => 'nullable|string|max:255',
            'description' => 'required|string',
            'description_ar' => 'nullable|string',
            'discount_type' => 'required|in:percentage,fixed,buy_x_get_y,free_item',
            'discount_value' => 'required|numeric|min:0',
            'minimum_purchase' => 'nullable|numeric|min:0',
            'max_discount_amount' => 'nullable|numeric|min:0',
            'terms_conditions' => 'nullable|string',
            'terms_conditions_ar' => 'nullable|string',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'redemption_limit' => 'nullable|integer|min:0',
            'user_redemption_limit' => 'nullable|integer|min:0',
            'status' => 'required|in:active,inactive,expired',
            'is_featured' => 'boolean',
        ]);

        $offer->update($validated);

        // Log audit
        \App\Models\AuditLog::logAction(
            'update_offer',
            $offer,
            null,
            [
                'admin_id' => auth()->id(),
                'changes' => $validated
            ]
        );

        return redirect()->route('admin.offers.show', $offer->id)
            ->with('success', 'Offer updated successfully!');
    }
    /**
     * Create offer
     */
    public function create($venueID)
    {
        $venue = \App\Models\Venue::findOrFail($venueID);
        $categories = Category::where('is_active', true)->get();

        return view('admin.offers.create', compact('venue', 'categories'));
    }

}

