<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use App\Models\Partner;
use App\Models\Setting;
use App\Models\Invoice;
use Illuminate\Http\Request;

class TransactionController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'type' => 'required|in:income,expense',
            'category' => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $categories = $request->type === 'income' 
                        ? array_keys(json_decode(Setting::get('income_categories'), true) ?? [])
                        : array_keys(json_decode(Setting::get('expense_categories'), true) ?? []);
                    
                    if (!in_array($value, $categories)) {
                        $fail('التصنيف المحدد غير صالح.');
                    }
                },
            ],
            'amount' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'transaction_date' => 'required|date',
            'partner_id' => auth()->user()->hasRole(['admin', 'accountant']) ? 'nullable|exists:partners,id' : 'prohibited',
            'buyer_name' => 'required_if:type,income',
            'buyer_phone' => 'nullable|string',
            'buyer_address' => 'nullable|string',
            'buyer_tax_number' => 'nullable|string'
        ]);

        if (!auth()->user()->hasRole(['admin', 'accountant'])) {
            $validated['partner_id'] = auth()->user()->partner_id;
        }

        $transaction = Transaction::create($validated);

        if ($transaction->type === 'income') {
            $this->createInvoices($transaction);
        }

        return response()->json([
            'message' => 'تم إضافة المعاملة بنجاح',
            'transaction' => $transaction
        ]);
    }

    public function update(Request $request, Transaction $transaction)
    {
        $validated = $request->validate([
            'type' => 'required|in:income,expense',
            'category' => 'required|string',
            'amount' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'transaction_date' => 'required|date',
            'partner_id' => auth()->user()->hasRole('admin') ? 'required|exists:partners,id' : 'prohibited',
        ]);

        if (!auth()->user()->hasRole('admin')) {
            $validated['partner_id'] = auth()->user()->partner_id;
        }

        $transaction->update($validated);

        return response()->json([
            'message' => 'تم تحديث المعاملة بنجاح',
            'transaction' => $transaction
        ]);
    }

    public function index()
    {
        $query = Transaction::with('partner');
        
        if (!auth()->user()->hasRole(['admin', 'accountant'])) {
            $query->where(function($q) {
                $q->where('partner_id', auth()->user()->partner_id)
                  ->orWhereNull('partner_id');
            });
        }

        $transactions = $query->latest()->get();
        $partners = Partner::all();
        
        $categories = [
            'income' => json_decode(Setting::get('income_categories'), true) ?? [],
            'expense' => json_decode(Setting::get('expense_categories'), true) ?? []
        ];
        
        return view('transactions.index', compact('transactions', 'partners', 'categories'));
    }

    public function destroy(Transaction $transaction)
    {
        $transaction->delete();
        return response()->json(['message' => 'تم حذف المعاملة بنجاح']);
    }

    private function createInvoices($transaction)
    {
        if ($transaction->type !== 'income') {
            return;
        }

        // نظام الفواتير المختار
        $invoiceSystem = Setting::get('invoice_system', 'split');

        if ($invoiceSystem === 'split') {
            // النظام القديم - تقسيم الفواتير على الشركاء
            $partners = Partner::where('status', '=', 'active')
                              ->where('percentage', '>', 0)
                              ->get();
            
            foreach ($partners as $partner) {
                Invoice::create([
                    'transaction_id' => $transaction->id,
                    'partner_id' => $partner->id,
                    'amount' => $transaction->amount * ($partner->percentage / 100),
                    'share_percentage' => $partner->percentage,
                    'status' => 'pending',
                    'buyer_name' => $transaction->buyer_name,
                    'buyer_phone' => $transaction->buyer_phone,
                    'buyer_address' => $transaction->buyer_address,
                    'buyer_tax_number' => $transaction->buyer_tax_number
                ]);
            }
        } else {
            // نظام الفاتورة الواحدة
            Invoice::create([
                'transaction_id' => $transaction->id,
                'partner_id' => null,
                'amount' => $transaction->amount,
                'share_percentage' => 100,
                'status' => 'pending',
                'seller_name' => Setting::get('system_name', 'نظام إدارة الشركاء'),
                'buyer_name' => $transaction->buyer_name,
                'buyer_phone' => $transaction->buyer_phone,
                'buyer_address' => $transaction->buyer_address,
                'buyer_tax_number' => $transaction->buyer_tax_number
            ]);
        }
    }
} 