<?php

namespace App\Http\Controllers;

use App\Models\LoyaltyPoint;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoyaltyPointController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $company_id = $request->input('company_id', Auth::user()->company_id);
        $customer_id = $request->input('customer_id');

        $loyaltyPoints = LoyaltyPoint::with(['customer', 'user'])
            ->where('company_id', $company_id);

        if ($customer_id) {
            $loyaltyPoints->where('customer_id', $customer_id);
        }

        $loyaltyPoints = $loyaltyPoints->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('loyalty_points.index', compact('loyaltyPoints'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $company_id = $request->input('company_id', Auth::user()->company_id);
        $customer_id = $request->input('customer_id');

        $customers = Customer::where('company_id', $company_id)->get();
        $customer = $customer_id ? Customer::findOrFail($customer_id) : null;

        return view('loyalty_points.create', compact('customers', 'customer', 'customer_id'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'amount' => 'required|integer',
            'type' => 'required|in:earned,redeemed,expired,adjusted',
            'source' => 'required|string|max:255',
            'description' => 'nullable|string',
            'expiry_date' => 'nullable|date',
            'reference_id' => 'nullable|string|max:255',
            'reference_type' => 'nullable|string|max:255',
        ]);

        $company_id = $request->input('company_id', Auth::user()->company_id);

        $loyaltyPoint = new LoyaltyPoint($validated);
        $loyaltyPoint->company_id = $company_id;
        $loyaltyPoint->user_id = Auth::id();
        $loyaltyPoint->save();

        return redirect()->route('loyalty-points.index')
            ->with('success', 'تم إضافة نقاط الولاء بنجاح');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $loyaltyPoint = LoyaltyPoint::with(['customer', 'user'])
            ->findOrFail($id);

        // التحقق من أن المستخدم ينتمي إلى نفس الشركة
        if ($loyaltyPoint->company_id != Auth::user()->company_id) {
            abort(403, 'غير مصرح لك بعرض هذه النقاط');
        }

        return view('loyalty_points.show', compact('loyaltyPoint'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $loyaltyPoint = LoyaltyPoint::findOrFail($id);

        // التحقق من أن المستخدم ينتمي إلى نفس الشركة
        if ($loyaltyPoint->company_id != Auth::user()->company_id) {
            abort(403, 'غير مصرح لك بتعديل هذه النقاط');
        }

        $company_id = Auth::user()->company_id;
        $customers = Customer::where('company_id', $company_id)->get();

        return view('loyalty_points.edit', compact('loyaltyPoint', 'customers'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $loyaltyPoint = LoyaltyPoint::findOrFail($id);

        // التحقق من أن المستخدم ينتمي إلى نفس الشركة
        if ($loyaltyPoint->company_id != Auth::user()->company_id) {
            abort(403, 'غير مصرح لك بتعديل هذه النقاط');
        }

        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'amount' => 'required|integer',
            'type' => 'required|in:earned,redeemed,expired,adjusted',
            'source' => 'required|string|max:255',
            'description' => 'nullable|string',
            'expiry_date' => 'nullable|date',
            'reference_id' => 'nullable|string|max:255',
            'reference_type' => 'nullable|string|max:255',
        ]);

        $loyaltyPoint->update($validated);

        return redirect()->route('loyalty-points.index')
            ->with('success', 'تم تحديث نقاط الولاء بنجاح');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $loyaltyPoint = LoyaltyPoint::findOrFail($id);

        // التحقق من أن المستخدم ينتمي إلى نفس الشركة
        if ($loyaltyPoint->company_id != Auth::user()->company_id) {
            abort(403, 'غير مصرح لك بحذف هذه النقاط');
        }

        $loyaltyPoint->delete();

        return redirect()->route('loyalty-points.index')
            ->with('success', 'تم حذف نقاط الولاء بنجاح');
    }

    /**
     * عرض نقاط الولاء المرتبطة بعميل معين
     *
     * @param  int  $customerId
     * @return \Illuminate\Http\Response
     */
    public function customerLoyaltyPoints($customerId)
    {
        $customer = Customer::findOrFail($customerId);

        // التحقق من أن المستخدم ينتمي إلى نفس الشركة
        if ($customer->company_id != Auth::user()->company_id) {
            abort(403, 'غير مصرح لك بعرض نقاط ولاء هذا العميل');
        }

        $loyaltyPoints = LoyaltyPoint::with(['user'])
            ->where('customer_id', $customerId)
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        $totalPoints = $customer->getActiveLoyaltyPointsAttribute();

        return view('loyalty_points.customer_loyalty_points', compact('loyaltyPoints', 'customer', 'totalPoints'));
    }
}
