<?php

namespace App\Http\Controllers\User;

use App\Models\Sale;
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 SaleController 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 = Sale::where('user_id', $user->id)->count();

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

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


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

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

            $records = [];
            foreach ($sales as $sale) {


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

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

    public function create()
    {
        $accounts = Account::where('user_id', auth()->user()->id)->orderBy('accounts.name')
        ->pluck('accounts.name', 'accounts.id')
        ->toArray();
        $modalContent = view('user.sale.create_sale', 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);
            }

            $sale = Sale::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,
                'sale_date'         => now(),
                'notes'             => $request->notes,
            ]);
            $transaction = Transaction::create([
                'account_id'   => $account->id,
                'user_id'      => $user_id,
                'sale_id'      => $sale->id,
                'bank_account'   => $request->bank_account,
                'paid_amount'       => $request->paid_amount,
                'notes'        => 'دفعة من ' . $account->name,
                'type'         => 'sale',
            ]);


            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)
    {
        $sale = Sale::find($id);

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

    }


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

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

        $balance_change = $new_diff - $old_diff;

        $sale->account->balance += $balance_change;
        $sale->account->save();


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

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

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

}
