<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API\Dashboard;

use App\Http\Resources\PartnerResource;
use App\Models\Admin;
use App\Models\Partner;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class PartnerController extends Controller
{
    // Get all partners without pagination
    public function getPartners(Request $request)
    {
        try {
            $partners = Partner::select('id', 'name', 'image', 'description', 'url', 'username', 'created_at')
                ->orderBy('created_at', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $partners->map(function ($partner) {
                    return [
                        'id' => $partner->id,
                        'name' => $partner->name,
                        // 'image' => $partner->image ? Storage::url($partner->image) : null,
                        'image' => $partner->image ? asset('storage/' . $partner->image) : null,

                        'description' => $partner->description,
                        'url' => $partner->url,
                        'username' => $partner->username,
                        'created_at' => $partner->created_at
                    ];
                })
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching partners: ' . $e->getMessage()
            ], 500);
        }
    }
    public function getPartner(Request $request, $id)
    {
        $validator = Validator::make(['id' => $id], [
            'id' => 'required|exists:partners,id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $partner = Partner::findOrFail($id);

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $partner->id,
                    'name' => $partner->name,
                    'image' => $partner->image ? asset('storage/' . $partner->image)  : null,
                    'description' => $partner->description,
                    'url' => $partner->url,
                    'username' => $partner->username,
                    'created_at' => $partner->created_at
                ]
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching partner: ' . $e->getMessage()
            ], 500);
        }
    }


    // Create a new partner
    public function createPartner(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name.ar' => 'nullable|string|max:255',
            'name.en' => 'nullable|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'description' => 'nullable|string',
            'url' => 'nullable',
            'username' => 'nullable|string|max:255',
            'type' => 'required|in:1,2',


        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $imagePath = null;
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('partners', 'public');
            }

            $partner = Partner::create([
                'name' => [
                    'ar' => $request->input('name.ar'),
                    'en' => $request->input('name.en')
                ],
                'image' => $imagePath,
                'description' => $request->description,
                'url' => $request->url,
                'type' => $request->type,

                'username' => $request->username
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Partner created successfully',
                'data' => new PartnerResource($partner)
            ], 201);
        } catch (\Exception $e) {
            if ($imagePath && Storage::disk('public')->exists($imagePath)) {
                Storage::disk('public')->delete($imagePath);
            }
            return response()->json([
                'success' => false,
                'message' => 'Error creating partner: ' . $e->getMessage()
            ], 500);
        }
    }

    // Update a partner
    public function updatePartner(Request $request, $id)
    {
        $validator = Validator::make(array_merge($request->all(), ['id' => $id]), [
            'id' => 'required|exists:partners,id',
            'name.ar' => 'nullable|string|max:255',
            'name.en' => 'nullable|string|max:255',
            'image' => 'nullable',
            'description' => 'nullable|string',
            'url' => 'nullable|string|url',
            'username' => 'nullable|string|max:255',

        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $partner = Partner::findOrFail($id);
            $imagePath = $partner->image;

            if ($request->hasFile('image')) {
                if ($imagePath && Storage::disk('public')->exists($imagePath)) {
                    Storage::disk('public')->delete($imagePath);
                }
                $imagePath = $request->file('image')->store('partners', 'public');
            }

            $partner->update([
                'name' => [
                    'ar' => $request->input('name.ar', $partner->name['ar'] ?? null),
                    'en' => $request->input('name.en', $partner->name['en'] ?? null),
                ],
                'image' => $imagePath ?? $partner->image,
                //  'description' => $request->description ?? $partner->description,
                'url' => $request->url ?? $partner->url,
                'username' => $request->username ?? $partner->username,

            ]);


            return response()->json([
                'success' => true,
                'message' => 'Partner updated successfully',
                'data' =>  new PartnerResource($partner)
            ], 200);
        } catch (\Exception $e) {
            if ($imagePath && $request->hasFile('image') && Storage::disk('public')->exists($imagePath)) {
                Storage::disk('public')->delete($imagePath);
            }
            return response()->json([
                'success' => false,
                'message' => 'Error updating partner: ' . $e->getMessage()
            ], 500);
        }
    }

    // Delete a partner
    public function deletePartner($id)
    {
        $validator = Validator::make(['id' => $id], [
            'id' => 'required|exists:partners,id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $partner = Partner::findOrFail($id);
            if ($partner->image && Storage::disk('public')->exists($partner->image)) {
                Storage::disk('public')->delete($partner->image);
            }
            $partner->delete();

            return response()->json([
                'success' => true,
                'message' => 'Partner deleted successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting partner: ' . $e->getMessage()
            ], 500);
        }
    }
}
