<?php

namespace App\Http\Controllers\Vendor;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VendorCouponController extends Controller
{
    protected function vendor()
    {
        return Auth::user()->vendor;
    }

    public function index()
    {
        if (!Setting::get('vendor_can_create_coupons')) {
            return redirect()->route('vendor.dashboard')
                ->with('error', 'Coupon creation is currently disabled by admin.');
        }

        $coupons = Coupon::where('vendor_id', $this->vendor()->id)
            ->where('created_by', 'vendor')
            ->latest()
            ->paginate(20);

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

    public function create()
    {
        if (!Setting::get('vendor_can_create_coupons')) {
            return redirect()->route('vendor.dashboard')
                ->with('error', 'Coupon creation is currently disabled by admin.');
        }

        $products = $this->vendor()->products()->where('approval_status', 'approved')->get();
        return view('vendor.coupons.create', compact('products'));
    }

    public function store(Request $request)
    {
        if (!Setting::get('vendor_can_create_coupons')) {
            abort(403);
        }

        $data = $request->validate([
            'code' => 'required|string|unique:coupons|max:50',
            'description' => 'nullable|string|max:255',
            'type' => 'required|in:percentage,fixed',
            'value' => 'required|numeric|min:0',
            'max_discount' => 'nullable|numeric|min:0',
            'minimum_order' => 'nullable|numeric|min:0',
            'usage_limit' => 'nullable|integer|min:1',
            'expires_at' => 'nullable|date|after:today',
            'is_active' => 'boolean',
            'scope' => 'required|in:vendor,products',
            'product_ids' => 'required_if:scope,products|nullable|array',
            'product_ids.*' => 'exists:products,id',
        ]);

        $data['vendor_id'] = $this->vendor()->id;
        $data['created_by'] = 'vendor';
        $data['is_active'] = $request->boolean('is_active', true);

        // Convert null values to 0 for numeric fields
        $data['max_discount'] = $data['max_discount'] ?? 0;
        $data['minimum_order'] = $data['minimum_order'] ?? 0;
        $data['usage_limit'] = $data['usage_limit'] ?? 0;

        // Verify products belong to this vendor
        if (!empty($data['product_ids'])) {
            $vendorProductIds = $this->vendor()->products()->pluck('id')->toArray();
            $data['product_ids'] = array_intersect($data['product_ids'], $vendorProductIds);
        }

        $coupon = Coupon::create($data);

        if ($data['scope'] === 'products' && !empty($data['product_ids'])) {
            $coupon->products()->sync($data['product_ids']);
        }

        return redirect()->route('vendor.coupons.index')
            ->with('success', 'Coupon created successfully.');
    }

    public function edit(Coupon $coupon)
    {
        if ($coupon->vendor_id !== $this->vendor()->id) {
            abort(403);
        }

        $products = $this->vendor()->products()->where('approval_status', 'approved')->get();
        $coupon->load('products');
        return view('vendor.coupons.edit', compact('coupon', 'products'));
    }

    public function update(Request $request, Coupon $coupon)
    {
        if ($coupon->vendor_id !== $this->vendor()->id) {
            abort(403);
        }

        $data = $request->validate([
            'description' => 'nullable|string|max:255',
            'type' => 'required|in:percentage,fixed',
            'value' => 'required|numeric|min:0',
            'max_discount' => 'nullable|numeric|min:0',
            'minimum_order' => 'nullable|numeric|min:0',
            'usage_limit' => 'nullable|integer|min:1',
            'expires_at' => 'nullable|date',
            'is_active' => 'boolean',
            'scope' => 'required|in:vendor,products',
            'product_ids' => 'nullable|array',
            'product_ids.*' => 'exists:products,id',
        ]);

        $data['is_active'] = $request->boolean('is_active');
        
        // Convert null values to 0 for numeric fields
        $data['max_discount'] = $data['max_discount'] ?? 0;
        $data['minimum_order'] = $data['minimum_order'] ?? 0;
        $data['usage_limit'] = $data['usage_limit'] ?? 0;
        
        $coupon->update($data);
        $coupon->products()->sync($data['product_ids'] ?? []);

        return redirect()->route('vendor.coupons.index')
            ->with('success', 'Coupon updated.');
    }

    public function destroy(Coupon $coupon)
    {
        if ($coupon->vendor_id !== $this->vendor()->id) {
            abort(403);
        }

        $coupon->products()->detach();
        $coupon->delete();

        return redirect()->route('vendor.coupons.index')
            ->with('success', 'Coupon deleted.');
    }
}
