<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Invoice;
use Carbon\carbon;
use Illuminate\Http\Request;
use App\Models\OrderTransfer;

class OrderController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->authorize('viewAny', App\Models\User::class);
        return view('invoice.view-invoice', [
            'orders' => Order::paginate(100)
        ]);
    }


    public function pending()
    {   // getDay close
        $getDayClose = \DB::table('close_days')->first();
        
        if (auth()->user()->sales_person_category == "Delivery" || auth()->user()->role == "Dispatch Manager") {
            return back()->with('status', 'This Section is Available for Sales Person at the Counter');
        }else {
        $orders = \DB::table('orders')
            ->whereDate('created_at', $getDayClose->day_close)
            ->where('branch', auth()->user()->branch)
            ->where('category', "Counter")
            ->where('status', 0)
            ->get();
        return view('orders.pending-orders', [
            'pendings' => $orders
            ]);
        }
    }


    public function markReady(Order $order)
    {
        $order->status = 1;
        $order->save();
        return back();
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function AllOrders(Request $request)
    {   
         // GET DAY CLOSE DATE
         $getDayClose = \DB::table('close_days')->first();

        if (auth()->user()->role == "Administrator") {
            $transactions = \DB::table('orders')->whereDate('created_at', $getDayClose->day_close)->get();
        }elseif (auth()->user()->role == "Branch Officer") {
            $transactions = \DB::table('orders')->whereDate('created_at', $getDayClose->day_close)
            ->where('branch', auth()->user()->branch)
            ->get();
        }else {
            $transactions = \DB::table('orders')->whereDate('created_at', $getDayClose->day_close)
            ->where('user_id', auth()->id())
            ->get();
        }
        
        return view('all-orders', [
            'all_sales' => $transactions
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function show($order)
    {
        $detail_order = Invoice::where('invoice_number', $order)->get();
        $customer = Order::where('order_id', $order)->first();
        $customer_id = $customer -> customer_id;
        return view('orders.order-transactions', [
            'orders' => $detail_order,
            'invoice_number' => $order,
            'customer_id' => $customer_id
        ]);
    }


    public function TransferOrder()
    {
        $this->validate(request(), [
            'transfer_to' => 'required',
            'order_number' => 'required|unique:order_transfers'
        ]);

        OrderTransfer::create([
            'transfered_by'=>auth()->id(),
            'order_number'=> request('order_number'),
            'transfer_from'=>request('transfer_from'),
            'transfer_to'=>request('transfer_to'),
            'description'=>request('note'),
        ]);

        return back()->with('status', "Transfer Successfull, Waiting Approval");
    }


    public function TransferOrderPending()
    {
        return view('dispatch.pending-order-transfer', [
                'transactions' => \DB::table('order_transfers')->where('transfered_by', auth()->id())->where('status', 2)->get()
        ]);
    }


    public function TransferOrderAccepted()
    {
        return view('dispatch.approved-transfers', [
                'transactions' => \DB::table('order_transfers')->where('transfered_by', auth()->id())->where('status', 1)->get()
        ]);
    }


    public function acceptTransfer()
    {
        return view('dispatch.pending-order-transfer-approve', [
                'transactions' => \DB::table('order_transfers')->where('transfer_to', auth()->user()->branch)->where('status', 2)->get()
        ]);
    }


    public function acceptedTransfer($id)
    {
        $check = \DB::table('order_transfers')->where('order_number', $id)->first();
        if ($check->transfered_by == auth()->user()->id) {
            abort(419, "You can authorize this transfer");
        }

        \DB::table('invoices')->where('invoice_number', $id)->update([
            'branch'=> auth()->user()->branch,
        ]);

        \DB::table('orders')->where('order_id', $id)->update([
            'branch'=> auth()->user()->branch,
        ]);


        \DB::table('order_transfers')->where('order_number', $id)->update([
            'status' => 1,
            'accepted_by' => auth()->id(),
            'accepted_at' => \Carbon\carbon::now()
        ]);

        return auth()->user()->branch;
    }



    public function orderInformation($id)
    {
        $orderInformation = \DB::table('orders')
        ->join('customers','orders.customer_id','customers.id')->where('orders.order_id', $id)
        ->first();
        return collect([
            'order_total_cost' => $orderInformation->total_cost_order,
            'customer_phone' => $orderInformation->customer_phone,
        ]);
    }

}
