<?php

namespace App\Http\Controllers;

use App\Models\PaymentType;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class PaymentTypeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = PaymentType::query();

        // Filter by type if provided
        if ($request->has('type')) {
            $query->byType($request->type);
        }

        // Filter by status if provided
        if ($request->has('status')) {
            if ($request->status == 'active') {
                $query->active();
            } elseif ($request->status == 'inactive') {
                $query->inactive();
            }
        }

        $paymentTypes = $query->with(['admin', 'customer'])
            ->orderBy('created_at', 'desc')
            ->paginate(15);

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


    public function customerPaymentTypelist()
    {
        $admin = PaymentType::query()->where("type", "admin");
        $admin->active();
        $admin->select(["name", "value", "id"]);
        $admins =  $admin->get()->toArray();
        $customer = auth("customer")->user();
        $dd = [];
        foreach ($admins as $key => $value) {
            // return $value;
            // $value =
            $dx = [];
            $paymentt = PaymentType::where("customer_id", $customer->id)->where("name", $value["name"])->first();
            if ($paymentt == null) {
                $dx["name"] = $value["name"];
                $dx["value"] = $paymentt["value"] ?? "";
                $dd[] = $dx;
            }

            if ($paymentt != null) {
                $dx["name"] = $value["name"];
                $dx["value"] = $paymentt["value"] ?? "";
                $dd[] = $dx;
            }
        }
        return response()->json([
            'success' => true,
            'data' => $dd
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'value' => 'required|string|min:0',
            'type' => 'required|in:admin,member',
            'admin_id' => 'nullable|exists:admins,id',
            'customer_id' => 'nullable|exists:customers,id',
            'isActive' => 'boolean'
        ]);

        $paymentType = PaymentType::create($validated);

        return response()->json([
            'success' => true,
            'message' => 'Payment type created successfully.',
            'data' => $paymentType->load(['admin', 'customer'])
        ], 201);
    }


    public function submitPaymentStore(Request $request)
    {
        $validated = $request->validate([
            'paymentypes' => 'required|array',
            'paymentypes.*' => 'required|array', // Validate each item in the paymentypes array
        ]);

        $createdPaymentTypes = [];
        $customer = auth("customer")->user();

        foreach ($validated['paymentypes'] as $paymentData) {
            // Assuming PaymentType::createUpdate expects individual payment data, not wrapped in array
            $paymentData["type"] = "member";
            $paymentData["customer_id"] = $customer->id;
            $paymentType = PaymentType::where("customer_id",  $customer->id)->where("type", "member")->where("name", $paymentData["name"])->first();

            if ($paymentType == null) {
                $data = [
                    "type" => "member",
                    "customer_id" => $customer->id,
                    "admin_id" => null,
                    "name" => $paymentData["name"],
                    "value" => $paymentData["value"],
                    "isActive" => true
                ];
                PaymentType::create($data);
            }

            if ($paymentType != null) {
                $data = [
                    "type" => "member",
                    "customer_id" => $customer->id,
                    "admin_id" => null,
                    "name" => $paymentData["name"],
                    "value" => $paymentData["value"],
                    "isActive" => true
                ];
                $paymentType->update($data);
            }
            return response()->json([
                'success' => true,
                'message' => 'Payment types processed successfully.',
                'paymentType' => $paymentType
            ], 201);
        }

        return response()->json([
            'success' => true,
            'message' => 'Payment types processed successfully.',
            'data' => collect($createdPaymentTypes)->map(function ($paymentType) {
                return $paymentType->load(['admin', 'customer']);
            })
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(PaymentType $paymentType)
    {
        $paymentType->load(['admin', 'customer']);

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, PaymentType $paymentType)
    {
        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'value' => 'sometimes|required',
            'type' => 'sometimes|required|in:admin,member',
            'admin_id' => 'nullable|exists:admins,id',
            'customer_id' => 'nullable|exists:customers,id',
            'isActive' => 'boolean'
        ]);

        $paymentType->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Payment type updated successfully.',
            'data' => $paymentType->load(['admin', 'customer'])
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(PaymentType $paymentType)
    {
        $paymentType->delete();

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

    /**
     * Activate a payment type.
     */
    public function activate(PaymentType $paymentType)
    {
        $paymentType->activate();

        return response()->json([
            'success' => true,
            'message' => 'Payment type activated successfully.',
            'data' => $paymentType
        ]);
    }

    /**
     * Deactivate a payment type.
     */
    public function deactivate(PaymentType $paymentType)
    {
        $paymentType->deactivate();

        return response()->json([
            'success' => true,
            'message' => 'Payment type deactivated successfully.',
            'data' => $paymentType
        ]);
    }

    /**
     * Get active payment types only.
     */
    public function active()
    {
        $paymentTypes = PaymentType::active()
            ->with(['admin', 'customer'])
            ->get();

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

    /**
     * Get payment types by type (admin or member).
     */
    public function byType($type)
    {
        $paymentTypes = PaymentType::byType($type)
            ->with(['admin', 'customer'])
            ->get();

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