<?php

namespace App\Http\Controllers\User;

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

class PurchaseController 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;

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

            $totalRecordswithFilter =  Purchase::select(
                                            'purchases.*',             // كل أعمدة المبيعات
                                            'accounts.name as account_name',  // اسم العميل
                                            'accounts.phone as account_phone' // هاتف العميل
                                        )
                                        ->join('accounts', 'purchases.account_id', '=', 'accounts.id')
                                        ->where('purchases.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}%");
                                            });
                                        })
                                    ->count();

            $purchases = Purchase::select(
                        'purchases.*',
                        'accounts.name as account_name',
                        'accounts.phone as account_phone'
                    )
                    ->join('accounts', 'purchases.account_id', '=', 'accounts.id')
                    ->where('purchases.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($from) && !empty($to), function ($q) use ($from, $to) {
                    $q->whereBetween('purchases.created_at', [$from . ' 00:00:00', $to . ' 23:59:59']);
                })
                ->when(!empty($from) && empty($to), function ($q) use ($from) {
                    $q->whereDate('purchases.created_at', '>=', $from);
                })
                ->when(!empty($to) && empty($from), function ($q) use ($to) {
                    $q->whereDate('purchases.created_at', '<=', $to);
                })
                ->skip($start)
                ->take($rowperpage)
                ->orderByDesc('id')
                ->get();

              $baseQuery = Purchase::select(
                        'purchases.*',
                        'accounts.name as account_name',
                        'accounts.phone as account_phone'
                    )
                    ->join('accounts', 'purchases.account_id', '=', 'accounts.id')
                    ->where('purchases.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($from) && !empty($to), function ($q) use ($from, $to) {
                    $q->whereBetween('purchases.created_at', [$from . ' 00:00:00', $to . ' 23:59:59']);
                })
                ->when(!empty($from) && empty($to), function ($q) use ($from) {
                    $q->whereDate('purchases.created_at', '>=', $from);
                })
                ->when(!empty($to) && empty($from), function ($q) use ($to) {
                    $q->whereDate('purchases.created_at', '<=', $to);
                });

            $total_paid_amount = (clone $baseQuery)
                    ->sum('purchases.paid_amount');
            $total_amount = (clone $baseQuery)
                    ->sum('purchases.total_amount');


            $records = [];
            foreach ($purchases as $purchase) {


                $records[] = [
                    'invoice_number' => $purchase->invoice_number ?? '-',
                    'name' => $purchase->account->name ?? '-',
                    'phone' => $purchase->account->phone ? '<a href="tel:' . $purchase->account->phone . '">'. $purchase->account->phone .'</a>': '-',
                    'total_amount' => $purchase->total_amount ?? '-',
                    'paid_amount' => $purchase->paid_amount ?? '-',
                    'created_at' => $purchase->created_at->format('Y-m-d H:i'),
                    'actions' => '<td>
                                            <div class="d-flex gap-1">
                                                <a href="javascript:void(0);" id="purchase-edit" data-id="' . $purchase->id . '"
                                                class="btn btn-sm btn-icon btn-outline-primary" title="تعديل">
                                                     عرض\تعديل
                                                </a>
                                                <a href="javascript:void(0);" onclick="confirmDeletepurchase(' . $purchase->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_paid_amount' => $total_paid_amount,
                'total_amount' => $total_amount,
            ]);
        }

        // ✅ الطلبات العامة لعرض الصفحة (بدون AJAX)
        $purchases = Purchase::where('user_id', $user->id)->latest()->get();
        $total = $purchases->count();
        return view('user.purchase.purchases', compact('purchases', 'total'));
    }

    public function create()
    {
        $accounts = Account::where('user_id', auth()->user()->id)->orderBy('accounts.name')
        ->pluck('accounts.name', 'accounts.id')
        ->toArray();
        $modalContent = view('user.purchase.create_purchase', 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',
                'total_amount'   => 'required|numeric|min:0',
                'paid_amount'    => 'required|numeric|min:0',
                'notes'          => 'nullable|string|max:1000',
            ]);

            $user_id = auth()->id();

            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'           => 'customer',
                ]);
            } else {
                $account = Account::find($request->account_id);
            }

            $purchase = Purchase::create([
                'account_id'        => $account->id,
                'user_id'           => $user_id,
                'total_amount'      => $request->total_amount,
                'paid_amount'       => $request->paid_amount,
                'remaining_amount'  => $request->total_amount - $request->paid_amount,
                'notes'             => $request->notes,
            ]);
            $transaction = Transaction::create([
                'account_id'   => $account->id,
                'user_id'      => $user_id,
                'purchase_id'      => $purchase->id,
                'bank_account'   => $request->bank_account,
                'paid_amount'       => $request->paid_amount,
                'notes'        => 'دفعة من ' . $account->name,
                'type'         => 'purchase',
            ]);


            if($request->total_amount > $request->paid_amount){
               $account->balance += ($request->total_amount - $request->paid_amount);
                $account->save();
            }else{
                $account->balance -= ( $request->paid_amount - $request->total_amount);
                $account->save();
              }


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


    public function edit($id)
    {
        $purchase = Purchase::find($id);

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

    }


    public function update(Request $request, $id)
    {
        $purchase = purchase::find($id);
        $validated = $request->validate([
            'total_amount'   => 'required|numeric|min:0',
            'paid_amount'    => 'required|numeric|min:0 ',
            'notes'          => 'nullable|string|max:1000',
        ]);

        $old_diff  = $purchase->paid_amount - $purchase->total_amount;
        $new_diff  = $request->paid_amount - $request->total_amount;

        $balance_change = $new_diff - $old_diff;

        $purchase->account->balance -= $balance_change;
        $purchase->account->save();

        $validated ['remaining_amount'] = $validated['total_amount'] - $validated['paid_amount'];
        $purchase->update($validated);

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

    public function destroy($id)
    {
        $purchase = Purchase::find($id);
        if($purchase->total_amount >= $purchase->paid_amount){
        $purchase->account->balance -= ($purchase->total_amount - $purchase->paid_amount);
            $purchase->account->save();
        }else{
            $purchase->account->balance += ( $purchase->paid_amount - $purchase->total_amount);
            $purchase->account->save();
        }
        $purchase->account->save();
        $purchase->delete();
        $notification = trans('dash.Delete Successfully');
        $notification = array('messege' => $notification, 'alert-type' => 'success');
        return redirect()->route('user.purchase.index')->with($notification);
    }

}
