<?php

namespace App\Http\Controllers\User;

use App\Models\Transaction;
use App\Models\Account;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class TransactionController extends Controller
{
    public function index(Request $request)
    {

        $user = auth()->user();
        if (!$user) {
            abort(403, 'لا يوجد مستخدم.');
        }

        if ($request->ajax()) {

            $draw = $request->get('draw');
            $start = $request->get('start');
            $rowperpage = $request->get('length');
            $searchValue = $request->input('search.value');
            $from = $request->from;
            $to = $request->to;
            $typeFilter = $request->type; // incoming | outgoing | null

            $totalRecords = Transaction::where('user_id', $user->id)->count();

            $totalRecordswithFilter =  Transaction::select(
                                            'transactions.*',             // كل أعمدة  transaction
                                            'accounts.name as account_name',  // اسم العميل
                                            'accounts.phone as account_phone' // هاتف العميل
                                        )
                                        ->join('accounts', 'transactions.account_id', '=', 'accounts.id')
                                        ->where('transactions.user_id', $user->id)
                                        ->when(!empty($typeFilter), function ($q) use ($typeFilter) {
                                                if ($typeFilter === 'outgoing') {
                                                    $q->whereIn('transactions.type', ['purchase', 'supplier_payment']);
                                                } elseif ($typeFilter === 'incoming') {
                                                    $q->whereIn('transactions.type', ['sale', 'payment']);
                                                }
                                            })
                                        ->when($searchValue, function ($query) use ($searchValue) {
                                            $query->where(function ($sub) use ($searchValue) {
                                                $sub->where('accounts.name', 'like', "%{$searchValue}%")
                                                    ->orWhere('accounts.phone', 'like', "%{$searchValue}%");
                                            });
                                        })
                                    ->count();

            $transactions = Transaction::select(
                        'transactions.*',
                        'accounts.name as account_name',
                        'accounts.phone as account_phone'
                    )
                    ->join('accounts', 'transactions.account_id', '=', 'accounts.id')
                    ->where('transactions.user_id', $user->id)
                    ->when($searchValue, function ($query) use ($searchValue) {
                        $query->where(function ($sub) use ($searchValue) {
                            $sub->where('accounts.name', 'like', "%{$searchValue}%")
                                ->orWhere('accounts.phone', 'like', "%{$searchValue}%");
                        });
                    })
                    ->when(!empty($typeFilter), function ($q) use ($typeFilter) {
                            if ($typeFilter === 'outgoing') {
                                $q->whereIn('transactions.type', ['purchase', 'supplier_payment']);
                            } elseif ($typeFilter === 'incoming') {
                                $q->whereIn('transactions.type', ['sale', 'payment']);
                            }
                        })
                ->when(!empty($from) && !empty($to), function ($q) use ($from, $to) {
                    $q->whereBetween('transactions.created_at', [$from . ' 00:00:00', $to . ' 23:59:59']);
                })
                ->when(!empty($from) && empty($to), function ($q) use ($from) {
                    $q->whereDate('transactions.created_at', '>=', $from);
                })
                ->when(!empty($to) && empty($from), function ($q) use ($to) {
                    $q->whereDate('transactions.created_at', '<=', $to);
                })
                ->skip($start)
                ->take($rowperpage)
                ->orderByDesc('id')
                ->get();

           // ✅ حساب المجموعين الحقيقيين من قاعدة البيانات بعد تطبيق نفس الفلاتر
            $baseQuery = Transaction::join('accounts', 'transactions.account_id', '=', 'accounts.id')
                ->where('transactions.user_id', $user->id)
                ->when(!empty($typeFilter), function ($q) use ($typeFilter) {
                    if ($typeFilter === 'outgoing') {
                        $q->whereIn('transactions.type', ['purchase', 'supplier_payment']);
                    } elseif ($typeFilter === 'incoming') {
                        $q->whereIn('transactions.type', ['sale', 'payment']);
                    }
                })
                ->when($searchValue, function ($query) use ($searchValue) {
                    $query->where(function ($sub) use ($searchValue) {
                        $sub->where('accounts.name', 'like', "%{$searchValue}%")
                            ->orWhere('accounts.phone', 'like', "%{$searchValue}%");
                    });
                })
                ->when(!empty($from) && !empty($to), function ($q) use ($from, $to) {
                    $q->whereBetween('transactions.created_at', [$from . ' 00:00:00', $to . ' 23:59:59']);
                })
                ->when(!empty($from) && empty($to), function ($q) use ($from) {
                    $q->whereDate('transactions.created_at', '>=', $from);
                })
                ->when(!empty($to) && empty($from), function ($q) use ($to) {
                    $q->whereDate('transactions.created_at', '<=', $to);
                });

            // 👇 الآن نحسب بناءً على الفلتر
            if ($typeFilter === 'outgoing') {
                // فقط الوارد
                $total_incoming = (clone $baseQuery)
                    ->whereIn('transactions.type', ['purchase', 'supplier_payment'])
                    ->sum('transactions.paid_amount');
                $total_outgoing = 0;
            } elseif ($typeFilter === 'incoming') {
                // فقط الصادر
                $total_outgoing = (clone $baseQuery)
                    ->whereIn('transactions.type', ['sale', 'payment'])
                    ->sum('transactions.paid_amount');
                $total_incoming = 0;
            } else {
                // عرض الكل
                $total_outgoing = (clone $baseQuery)
                    ->whereIn('transactions.type', ['sale', 'payment'])
                    ->sum('transactions.paid_amount');
                $total_incoming = (clone $baseQuery)
                    ->whereIn('transactions.type', ['purchase', 'supplier_payment'])
                    ->sum('transactions.paid_amount');
            }


            $records = [];
            foreach ($transactions as $transaction) {
                $transaction_type = match ($transaction->type) {
                    'sale'             => '<a href="javascript:void(0);"
                                                class="btn btn-sm btn-outline-primary view-sale"
                                                data-id="' . $transaction->sale_id . '">
                                                فاتورة بيع #' . ($transaction->sale?->invoice_number ?? '-') . '
                                            </a>',
                    'payment'          => '<span class="badge bg-primary">دفعة صادرة  </span>',
                    'purchase'         => '<a href="javascript:void(0);"
                                                class="btn btn-sm btn-outline-warning view-purchase"
                                                data-id="' . $transaction->purchase_id . '">
                                                فاتورة شراء #' . ($transaction->purchase?->invoice_number ?? '-') . '
                                            </a>',
                    'supplier_payment' => '<span class="badge bg-warning">دفعة واردة</span>',
                    default             => '<span class="badge bg-secondary">غير محدد</span>',
                };
                 $action = match ($transaction->type) {
                    'sale'             => '<a href="javascript:void(0);"
                                                class="btn btn-sm btn-outline-primary view-sale"
                                                data-id="' . $transaction->sale_id . '"> عرض\تعديل</a>',

                    'payment'          => '<a href="javascript:void(0);" id="transaction-edit" data-id="' . $transaction->id . '"
                                        class="btn btn-sm btn-outline-primary" title="تعديل"> عرض\تعديل </a>',

                    'purchase'         => '<a href="javascript:void(0);" class="btn btn-sm btn-outline-primary view-purchase"
                                                data-id="' . $transaction->purchase_id . '"> عرض\تعديل </a>',

                    'supplier_payment' => '<a href="javascript:void(0);" id="transaction-edit" data-id="' . $transaction->id . '"
                                        class="btn btn-sm btn-outline-primary" title="تعديل"> عرض\تعديل </a>',

                    default             => '<span class="badge bg-secondary">غير محدد</span>',
                };

                $records[] = [
                    'name' => $transaction->account->name ?? '-',
                    'phone' => $transaction->account->phone ? '<a href="tel:' . $transaction->account->phone . '">'. $transaction->account->phone .'</a>': '-',
                    'bank_account' => $transaction->bank_account ?? '-',
                    'paid_amount' => $transaction->paid_amount ?? '-',
                    'type' => $transaction_type ?? '-',
                    'created_at' => $transaction->created_at->format('Y-m-d H:i'),
                    'actions' => '<td>
                                    <div class="d-flex gap-1">'. $action . '
                                        <a href="javascript:void(0);" onclick="confirmDeletetransaction(' . $transaction->id . ')"
                                        class="btn btn-sm btn-icon btn-outline-danger" title="حذف">
                                            حذف
                                        </a>
                                    </div>
                                 </td>',
                ];
            }

            return response()->json([
                'draw' => intval($draw),
                'iTotalRecords' => $totalRecords,
                'iTotalDisplayRecords' => $totalRecordswithFilter,
                'aaData' => $records,
                'total_outgoing' => $total_outgoing,
                'total_incoming' => $total_incoming,
            ]);
        }

        // ✅ الطلبات العامة لعرض الصفحة (بدون AJAX)
        $transactions = Transaction::where('user_id', $user->id)->latest()->get();
        $total = $transactions->count();
        $total_outgoing = Transaction::where('user_id', $user->id)
                        ->whereIn('type', ['sale', 'payment'])
                        ->sum('paid_amount');

        $total_incoming = Transaction::where('user_id', $user->id)
                        ->whereIn('type', ['purchase', 'supplier_payment'])
                        ->sum('paid_amount');
        return view('user.transaction.transactions', compact('transactions', 'total', 'total_outgoing', 'total_incoming'));
    }

    public function create()
    {
        $accounts = Account::where('user_id', auth()->user()->id)->orderBy('accounts.name')
        ->pluck('accounts.name', 'accounts.id')
        ->toArray();
        $modalContent = view('user.transaction.create_transaction', compact('accounts'))->render();

        return response()->json(['modalContent' => $modalContent]);
    }
    public function transaction_suplier_create()
    {
        $accounts = Account::where('user_id', auth()->user()->id)->orderBy('accounts.name')
        ->pluck('accounts.name', 'accounts.id')
        ->toArray();
        $modalContent = view('user.transaction.create_transaction_suplier', compact('accounts'))->render();

        return response()->json(['modalContent' => $modalContent]);
    }

    public function store(Request $request)
        {
            $request->validate([
                'account_id'     => 'nullable|integer|exists:accounts,id',
                'name'           => 'required|string|max:255',
                'phone'          => 'nullable|string|max:20',
                'bank_account'   => 'nullable|string|max:50',
                'phone_account'  => 'nullable|string|max:20',
                'name_account'   => 'nullable|string|max:100',
                'type'           => 'required|in:supplier_payment,payment',
                'paid_amount'    => 'required|numeric|min:0',
                'notes'          => 'nullable|string|max:1000',
            ]);

            $user_id = auth()->id();
            if($request->type == 'payment'){
                $account_type = 'customer';
            }else{
                $account_type = 'supplier';
            }

            if (empty($request->account_id)) {
                $account = Account::create([
                    'user_id'        => $user_id,
                    'name'           => $request->name,
                    'phone'          => $request->phone,
                    'bank_account'   => $request->bank_account,
                    'phone_account'  => $request->phone_account,
                    'name_account'   => $request->name_account,
                    'type'           => $account_type,
                ]);
            } else {
                $account = Account::find($request->account_id);
            }

            $transaction = Transaction::create([
                'account_id'   => $account->id,
                'user_id'      => $user_id,
                'bank_account'   => $request->bank_account,
                'paid_amount'       => $request->paid_amount,
                'notes'        => $request->notes,
                'type'         => $request->type,
            ]);

            if ($request->type == 'payment') {

                   $account->balance += $request->paid_amount;

                } elseif ($request->type == 'supplier_payment') {

                    $account->balance -= $request->paid_amount;

                }
                $account->save();

            $notification = trans('dash.Created Successfully');
                return response()->json(
                    [
                        'notification' => $notification
                    ]
                );
        }


    public function edit($id)
    {
        $transaction = Transaction::find($id);

        $modalContent = view('user.transaction.edit_transaction', compact('transaction'))->render();
        return response()->json(['modalContent' => $modalContent]);

    }


    public function update(Request $request, $id)
    {
        $transaction = Transaction::find($id);
        $validated = $request->validate([
            'paid_amount'    => 'required|numeric|min:0 ',
            'notes'          => 'nullable|string|max:1000',
        ]);
        if ($transaction->type == 'payment') {
            $transaction->account->balance -= $transaction->paid_amount;
            $transaction->account->balance += $request->paid_amount;
            $transaction->account->save();

        } elseif ($transaction->type == 'supplier_payment') {

           $transaction->account->balance += $transaction->paid_amount;
            $transaction->account->balance -= $request->paid_amount;
            $transaction->account->save();
        }
        $transaction->update($validated);

        $notification = trans('dash.Updated Successfully');
        return response()->json(
            [
                'redirect_url' => route('user.transaction.index'),
                'notification' => $notification
            ]
        );
    }

    public function destroy($id)
    {
        $transaction = Transaction::find($id);
        if(isset($transaction->sale) || isset($transaction->purchase) ){
            $notification = trans('dash.You cannot delete this transaction because it is linked to a sale or purchase.');
            $notification = array('messege' => $notification, 'alert-type' => 'warning');
            return redirect()->route('user.transaction.index')->with($notification);
        }
            $paid = $transaction->paid_amount;
        if ($transaction->type == 'payment') {
                $transaction->account->balance -= $paid;
                $transaction->account->save();
            }elseif ($transaction->type == 'supplier_payment') {
                $transaction->account->balance += $paid;
                $transaction->account->save();
            }


        $transaction->delete();
        $notification = trans('dash.Delete Successfully');
        $notification = array('messege' => $notification, 'alert-type' => 'success');
        return redirect()->route('user.transaction.index')->with($notification);
    }

}
