<?php

namespace App\Http\Controllers;

use App\Models\Partner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PartnerController extends Controller
{
    public function index()
    {
        $partners = Partner::all();
        return view('partners.index', compact('partners'));
    }

    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'nullable|email|max:255',
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string|max:255',
                'percentage' => 'required|numeric|min:0|max:100',
                'national_id' => 'nullable|string|max:20',
                'bank_name' => 'nullable|string|max:100',
                'bank_account' => 'nullable|string|max:50',
                'bank_iban' => 'nullable|string|max:50',
                'notes' => 'nullable|string',
                'status' => 'required|in:active,inactive'
            ]);

            // التحقق من مجموع النسب
            $totalPercentage = Partner::where('status', 'active')->sum('percentage');
            if (($totalPercentage + $validated['percentage']) > 100) {
                return response()->json([
                    'message' => 'مجموع نسب الشركاء لا يمكن أن يتجاوز 100%'
                ], 422);
            }

            $partner = Partner::create($validated);

            DB::commit();

            return response()->json([
                'message' => 'تم إضافة الشريك بنجاح',
                'partner' => $partner
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('خطأ في إضافة شريك: ' . $e->getMessage());
            
            return response()->json([
                'message' => 'حدث خطأ أثناء إضافة الشريك',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function show(Partner $partner)
    {
        return response()->json([
            'id' => $partner->id,
            'name' => $partner->name,
            'user_code' => $partner->user_code,
            'email' => $partner->email,
            'phone' => $partner->phone,
            'address' => $partner->address,
            'percentage' => $partner->percentage,
            'national_id' => $partner->national_id,
            'bank_name' => $partner->bank_name,
            'bank_account' => $partner->bank_account,
            'bank_iban' => $partner->bank_iban,
            'notes' => $partner->notes,
            'status' => $partner->status
        ]);
    }

    public function update(Request $request, Partner $partner)
    {
        try {
            DB::beginTransaction();

            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'nullable|email|max:255',
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string|max:255',
                'percentage' => 'required|numeric|min:0|max:100',
                'national_id' => 'nullable|string|max:20',
                'bank_name' => 'nullable|string|max:100',
                'bank_account' => 'nullable|string|max:50',
                'bank_iban' => 'nullable|string|max:50',
                'notes' => 'nullable|string',
                'status' => 'required|in:active,inactive'
            ]);

            // التحقق من مجموع النسب
            $totalPercentage = Partner::where('status', 'active')
                ->where('id', '!=', $partner->id)
                ->sum('percentage');

            if (($totalPercentage + $validated['percentage']) > 100) {
                return response()->json([
                    'message' => 'مجموع نسب الشركاء لا يمكن أن يتجاوز 100%'
                ], 422);
            }

            $partner->update($validated);

            DB::commit();
            return response()->json([
                'message' => 'تم تحديث الشريك بنجاح',
                'partner' => $partner
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('خطأ في تحديث شريك: ' . $e->getMessage());
            
            return response()->json([
                'message' => 'حدث خطأ أثناء تحديث الشريك',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy(Partner $partner)
    {
        $partner->is_active = false;
        $partner->save();
        return response()->json(['message' => 'تم حذف الشريك بنجاح']);
    }
} 