<?php

namespace App\Http\Controllers\Administrator;
use App\Classes\Commission;
use App\Classes\AgencyCommission;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Auth;
use App\ExternalClientPaymentModel;
use DataTables;
use Illuminate\Support\Facades\Crypt;
class ExternalPaymentController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:External-Client-AddPayment', ['only' => ['create']]);
        $this->middleware('permission:External-Client-PaymentCollection', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('administrator.external.payment.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('administrator.external.payment.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $commission = new Commission;
        $agency_commission = new AgencyCommission;
        $item_code = NULL;
        $payment_amount = 0;
        $payment_no = 0;
        $this->validate($request, [
            'item'      => 'required',
            'client'    => 'required',
            'date'      => 'required',
            'amount.*'    => 'required|numeric',
        ]);
        foreach ($request->item as $key => $value) {
            $item_code = $request->item[$key];
            $payment_amount = $request->amount[$key];
            $sale_id = $commission->get_sale_id_by_itemcode($item_code);
            $agency_commission->agency_commission_external_project($payment_amount, $sale_id);
            $max_no  = $commission->get_max_no_by_saleid($sale_id);
            $commission->set_commission_external_client_payment($item_code, $payment_amount);
            $payment_no  = $max_no;
            $data = array(
                'sale_id'           => $sale_id,
                'payment_no'        => $payment_no + 1,
                'payment_amount'    => $request->amount[$key], 
                'payment_date'      => date('Y-m-d', strtotime($request->date[$key])),
                'payment_item'      => $item_code,
                'user_log'          => Auth::user()->id,
            );
            ExternalClientPaymentModel::insert($data);
        }
        \LogActivity::addToLog('Add Payment successfully!');
        return back()->with('success', 'Record Created Successfully.');
    }

    
    public function get_client_name(Request $request)
    {
        $search_code = $request->get('term','');
        $gets = DB::select("
            SELECT client_fullname FROM nso007_sale_detail_stock AS detail
            INNER JOIN nso007_item_stock AS item ON detail.saledetail_itemid = item.id
            INNER JOIN nso007_sale_stock AS sale ON detail.saledetail_saleid = sale.id
            INNER JOIN nso007_client AS client_ ON sale.sale_clientid = client_.id
            WHERE sale.sale_status = 2 AND item.item_name = '$search_code'
        ");
        $data = array();
        foreach ($gets as $g) {
            $data[] = array(
                'client_name'=>$g->client_fullname,
            );
        }
        if (empty(count($data))) {
            return ['value'=>'no-result','id'=>''];
        }else{
            return $data;
        }
       
    }

    // External payment list
    public function datatable_get_external_payment()
    {
        $client_deposit = DB::select("
            SELECT client_fullname, project_name, category_name, item_name, payment_no, payment_date, payment_amount, payment.user_log FROM nso007_external_client_payment AS payment
            INNER JOIN nso007_sale_stock AS sale ON payment.sale_id = sale.id
            INNER JOIN nso007_sale_detail_stock AS detail ON sale.id = detail.saledetail_saleid
            INNER JOIN nso007_item_stock AS item ON detail.saledetail_itemid = item.id
            INNER JOIN nso007_project_stock AS project ON item.item_projectid = project.id
            INNER JOIN nso007_category_stock AS category ON item.item_categoryid = category.id
            INNER JOIN nso007_client AS client_ ON sale.sale_clientid = client_.id
            WHERE sale.sale_status = 2
            ORDER BY payment_date ASC
        ");
        return  Datatables::of($client_deposit)
        ->addIndexColumn()
        ->setRowId('id')
        ->editColumn('payment_date', function($client){
            return date('Y-m-d', strtotime($client->payment_date));
        })
        ->editColumn('payment_amount', function($client){
            return "$ ".number_format($client->payment_amount, 2);
        })
        ->make(true);
    }
}
