<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Http\Request;

use App\Deposit;
use App\DepositDetail;
use App\DepositKind;
use App\Bank;
use App\Unit;
use App\Delivery;
use App\DeliveryDetail;
use App\SalesKind;
use App\System;
use App\Invoice;
use App\Supply;
use App\Payment;
use App\PaymentKind;
use App\Products;
use App\Supplier;
use App\SupplierLedger;
Use App\SupplierLedgerDetail;
Use App\MonthlyPurchase;


class MonthlyPurchaseController extends Controller
{

	public function summary(Request $request)
	{
		$formdata = [
			'Action' => $request->input('Action', null),
			'Year' => $request->input('Year', null), // 月次更新（年） : Action='Update'のときのみ有効
			'Month' => $request->input('Month', null),// 月次更新（月） : Action='Update'のときのみ有効
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);

		if ($formdata['Action'] == 'Update')
		{
			// 仕入月次更新
			//		仕入月次更新した記録を残すだけ
			//		実際は 都度 計算するのだが、事務処理の記録として残す

			$monthlypurchase = new MonthlyPurchase;
			$monthlypurchase->year = $formdata['Year'];
			$monthlypurchase->month = $formdata['Month'];
			$monthlypurchase->updated = date('Y-m-d H:i:s');

			$monthlypurchase->save();

		}
		elseif ($formdata['Action'] == 'Cancel')
		{
			// 仕入月次更新 取消
			//		仕入月次更新した記録を消すだけ

			$query = MonthlyPurchase::query();
			$query->where("year" , $formdata['Year']);
			$query->where("month" , $formdata['Month']);
			$query->delete();
		}
		

		// 最終 仕入月次更新月
		$monthlypurchase = null;
	
		$query = MonthlyPurchase::query();
		$query->selectRaw("year");
		$query->selectRaw("month");
		$query->orderBy("year", 'DESC');
		$query->orderBy("month", 'DESC');
		
		$monthlypurchase = $query->first();
		logger('Monthly.summary', ['monthlypurchase' => $monthlypurchase]);

		$resp = [
			'monthly' => $monthlypurchase,
		];
		return response()->json($resp);
	}

	public function PayableList01(Request $request)
	{
		// 仕入先毎買掛
		//logger('MonthlyPurchase.PayableList01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);
		$system = new System();

		// Supplies data subquery
		$suppliesData = DB::table('supplies')
			->select(
				DB::raw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入先"."SupplierCode"\')) AS SupplierCode'),
				DB::raw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入先"."名称"\')) AS 仕入先名'),
				DB::raw('SUM(CASE WHEN jt.商品No IN (\'00700\') THEN jt.仕入金額 ELSE 0 END) AS 商品仕入'),
				DB::raw('SUM(CASE WHEN jt.商品No IN (\'00720\', \'00800\', \'00850\') THEN jt.仕入金額 ELSE 0 END) AS 材料仕入'),
				DB::raw('SUM(CASE WHEN jt.商品No IN (\'99999\') THEN jt.仕入金額 ELSE 0 END) AS 消費税計'),
				DB::raw('SUM(CASE WHEN jt.商品No NOT IN (\'00700\', \'00720\', \'00800\', \'00850\', \'99999\') THEN jt.仕入金額 ELSE 0 END) AS 消耗品その他')
			)
			->join(DB::raw('JSON_TABLE(
					supplies.details,
					\'$[*]\' 
					COLUMNS(
						仕入金額 INT PATH \'$."仕入金額"\',
						商品No INT PATH \'$."商品No"\',
						商品名 VARCHAR(255) PATH \'$."商品名"\'
					)
				) AS jt'), DB::raw('1'), DB::raw('1'))
			->leftJoin('products', DB::raw('jt.商品No'), '=', 'products.code')
			->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS DATE)'), [$formdata['date_from'], $formdata['date_to']])
			->groupBy('SupplierCode', '仕入先名');

		// Payments data subquery
		$paymentsData = DB::table('payments')
			->select(
				DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\')) AS CHAR) AS SupplierCode'),
				DB::raw('SUM(jt.money) AS 当月支払')
			)
			->join(DB::raw('JSON_TABLE(
					payments.attributes, 
					\'$.PaymentDetailTable[*]\' 
					COLUMNS(
						money INT PATH \'$.Amount\'
					)
				) AS jt'), DB::raw('1'), DB::raw('1'))
			->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS DATE)'), [$formdata['date_from'], $formdata['date_to']])
			->groupBy('SupplierCode');


		$suppliersData = Supplier::query();
		$suppliersData->selectRaw("code");
		$suppliersData->selectRaw("name");
		$suppliersData->selectRaw("attributes->'$.予備' AS yobi");
		$suppliersData->orderBy("code");
	

		// Main query combining supplies_data and payments_data
		//$query = DB::table(DB::raw('(' . $suppliersData->toSql() . ') AS sm'))
		//	->mergeBindings($suppliersData)
		//	->leftJoin(DB::raw('(' . $suppliesData->toSql() . ') AS s'), 'sm.code', '=', 's.SupplierCode')
		$query = DB::table(DB::raw('(' . $suppliesData->toSql() . ') AS s'))
			->mergeBindings($suppliesData)
			->leftJoin(DB::raw('(' . $paymentsData->toSql() . ') AS p'), 's.SupplierCode', '=', 'p.SupplierCode')
			->mergeBindings($paymentsData)
			->select(
				's.SupplierCode',
				's.仕入先名',
				's.商品仕入',
				's.材料仕入',
				's.消費税計',
				's.消耗品その他',
				'p.当月支払'
			)
			->orderBy('s.SupplierCode')
			->get();

		$payablelist = [];
		foreach($query as $payable)
		{
			$payablelist[] = (array)$payable;
		}

		// 年間仕入高
		$year = intval(date('Y', strtotime($formdata['date_from'])));
		$month = intval(date('m', strtotime($formdata['date_from'])));
		if ($month < $system->TermBeginingMonth())
		{
			$year--;
		}
		$termBeginDate = "{$year}-{$system->TermBeginingMonth()}-01";
		logger('MonthlyPurchase.PayableList01', ['termBeginDate' => $termBeginDate]);

		$query = DB::table('supplies')
		->select(
			DB::raw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入先"."SupplierCode"\')) AS SupplierCode'),
			DB::raw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入先"."名称"\')) AS 仕入先名'),
			DB::raw('SUM(jt.仕入金額) AS 仕入金額')
		)
		->join(DB::raw('JSON_TABLE(supplies.details, \'$[*]\' 
			COLUMNS(
				仕入金額 INT PATH \'$."仕入金額"\',
				商品No INT PATH \'$."商品No"\',
				商品名 VARCHAR(255) PATH \'$."商品名"\')
			) AS jt'), function ($join) {
				$join->on(DB::raw('1'), '=', DB::raw('1')); // ダミー結合条件
			})
		->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS DATE)'), [$termBeginDate, $formdata['date_to']])
		->groupBy('SupplierCode', '仕入先名')
		->orderBy('SupplierCode')
		->get();

		// 年間仕入高
		$yearlysupplies = [];
		foreach($query as $supplie)
		{
			$yearlysupplies[] = (array)$supplie;
		}
		$yearlysupplies2 = [];
		foreach($yearlysupplies as $supplie)
		{
			$supplier_code = $supplie['SupplierCode'];
			$yearlysupplies2[$supplier_code] = $supplie;
		}

		// 支払
		$payments = $paymentsData->get();
		$payments2 = [];
		foreach($payments as $payment)
		{
			$payments2[$payment->SupplierCode] = (array)$payment;
		}

		// 仕入先マスタ
		$query = Supplier::query();
		$query->selectRaw("code");
		$query->selectRaw("name");
		$query->selectRaw("JSON_UNQUOTE(attributes->'$.予備') AS yobi");
		$query->orderBy("code");
		$query->distinct();
		$rows = $query->get();
		$suppliers = [];
		foreach($rows as $row) {
			$suppliers[$row['code']] = [
				'code' => $row['code'],
				'name' => $row['name'],
				'yobi' => $row['yobi'],
			];
		}


		$payablelist2 = [];
		foreach($suppliers as $supplie)
		{
			$payablelist2[$supplie['code']] = [
				'SupplierCode' => $supplie['code'],
				'仕入先名' => $supplie['name'],
				'予備' => $supplie['yobi'],
				'商品仕入' => 0,
				'材料仕入' => 0,
				'消費税計' => 0,
				'消耗品その他' => 0,
				'前月繰越' => 0,
				'当月支払' => 0,
				'年間仕入高' => 0,
			];
		}
		foreach($payablelist as $payable)
		{
			$supplier_code = $payable['SupplierCode'];
			//$payable['年間仕入高'] = $yearlysupplies2[$supplier_code]['仕入金額'];
			$payablelist2[$supplier_code] = array_merge(
				$payablelist2[$supplier_code],
				$payable,
				[
					'年間仕入高' => $yearlysupplies2[$supplier_code]['仕入金額'],
				]
			);
		}
		foreach($yearlysupplies2 as $payable)
		{
			$supplier_code = $payable['SupplierCode'];
			//$payable['年間仕入高'] = $yearlysupplies2[$supplier_code]['仕入金額'];
			$payablelist2[$supplier_code] = array_merge(
				$payablelist2[$supplier_code],
				$payable,
				[
					'年間仕入高' => $yearlysupplies2[$supplier_code]['仕入金額'],
				]
			);
		}
		foreach($payments2 as $payment)
		{
			$supplier_code = $payment['SupplierCode'];
			//$payable['年間仕入高'] = $yearlysupplies2[$supplier_code]['仕入金額'];
			$payablelist2[$supplier_code] = array_merge(
				$payablelist2[$supplier_code],
				$payment,
				[
					'当月支払' => $payment['当月支払'],
				]
			);
		}

		// 前月の仕入先元帳を取得
		//$wdate = new DateTime($formdata['date_to']);
		//$wdate->modify('first day of last month')->modify('last day of this month');
		//$previousMonthEnd = $wdate->format('Y-m-d');
		$dateTo = $formdata['date_to'];
		$previousMonthEnd = date('Y-m-t', strtotime("last day of -1 month", strtotime($dateTo)));


		$query = SupplierLedger::query();
		$query->selectRaw("SupplierCode");
		$query->selectRaw("PaymentDate");
		$query->selectRaw("CurrAccountsPayable"); // 当月買掛残
		//$query->whereRaw("CAST(PaymentDate AS DATE) < '{$formdata['date_to']}'");
		$query->whereRaw("CAST(PaymentDate AS DATE) = '{$previousMonthEnd}'");
		logger('MonthlyPurchase.zengetu', ['sql' => $query->toSql()]);
		
		$prerows = $query->get();
		$zengetu = [];
		foreach($prerows as $row)
		{
			$zengetu[$row['SupplierCode']] = $row['CurrAccountsPayable'];
		}

		logger('MonthlyPurchase.zengetu', ['zengetu' => $zengetu]);

		foreach($payablelist2 as $row)
		{
			if (isset($row['SupplierCode'])) {
				$supplier_code = $row['SupplierCode'];
				
				// $zengetu に対応する値が存在するかチェック
				if (isset($zengetu[$supplier_code])) {
					// キーが存在している場合にマージ
					$payablelist2[$supplier_code] = array_merge(
						$payablelist2[$supplier_code],
						[
							'前月繰越' => $zengetu[$supplier_code],
						]
					);
				} else {
					// $zengetu[$supplier_code] が存在しない場合の処理
					// 例: ログ出力、デフォルト値を設定など
				}
			} else {
				// 'SupplierCode' が存在しない場合の処理
				// 例: ログ出力やエラーハンドリング
			}
		}

		//foreach($payablelist2 as $row)
		//{
		//	$supplier_code = $payment['SupplierCode'];
		//	$payablelist2[$supplier_code] = array_merge(
		//		$payablelist2[$supplier_code],
		//		$row,
		//		[
		//			'前月繰越' => $zengetu[$row[$supplier_code]],
		//		]
		//	);
			
		//}
		//foreach($prerows as $row)
		//{
		//	$supplier_code = $row['SupplierCode'];
		//	$payablelist2[$supplier_code] = array_merge(
		//		$payablelist2[$supplier_code],
		//		$row,
		//		[
		//			'前月繰越' => $row['CurrAccountsPayable'],
		//		]
		//	);
		//}

		logger('MonthlyPurchase.PayableList01', ['sql' => $suppliesData->toSql()]);
		logger('MonthlyPurchase.PayableList01', ['sql' => $paymentsData->toSql()]);

		
		$viewdata = [
			'formdata' => $formdata,
			'payablelist01' => $payablelist2,
		];

		logger('MonthlyPurchase.PayableList01', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthlypurchase.payableList01" ,compact('viewdata'));
	}

	public function Ledgerist01(Request $request)
	{
		// 仕入先元帳
		//logger('MonthlyPurchase.Ledgerist01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);

		// 仕入先元帳の確認
		$query = SupplierLedger::query();
		$query->selectRaw("SupplierCode");
		$query->selectRaw("PaymentDate");
		$query->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'");
		$query->whereRaw("ClosedFlag >= 6");
		$supplierledger = $query->get();

		logger('MonthlyPurchase.SupplierLedger', ['sql' => $query->toSql()]);

		// 月次更新済みのデータがあるか？
		if ($supplierledger->isEmpty()) {
		// 月次更新済みのデータはない

			// 仕入先元帳の削除（締めフラグに6が立っていないもの）
			$query = SupplierLedger::query();
			$query->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'");
			$query->whereRaw("ClosedFlag < 6");
			$query->delete();

			logger('MonthlyPurchase.SupplierLedger', ['sql' => $query->toSql()]);

			// 仕入先元帳明細の削除
			$query = SupplierLedgerDetail::query();
			$query->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'");
			$query->delete();

			logger('MonthlyPurchase.SupplierLedgerDetail', ['sql' => $query->toSql()]);

		} else {
		// 月次更新済みのデータがある

		}


		// 単位マスタ
		$query = Unit::query();
		$query->selectRaw("code");
		$query->selectRaw("name");
		$query->orderBy("code");
		$query->distinct();
		$rows = $query->get();
		$units = [];
		foreach($rows as $row) {
			$units[$row['code']] = $row['name'];
		}


		// 仕入データ
		$query = supply::query();
		$query->selectRaw("SupplyNumber");
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS 仕入日');
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入先".SupplierCode\')) AS SupplierCode');
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入先"."名称"\')) AS 仕入先名');
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入先"."Remark"\')) AS Remark');
		$query->selectRaw('details');
	
		$KeyColumn = "CAST(supplies.attributes->'$.仕入日' AS DATE)";
		$query->whereRaw("{$KeyColumn} BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");

		$query->orderByRaw("SupplierCode");
		$query->orderByRaw("SupplyNumber");

		logger('MonthlyPurchase.Supply', ['sql' => $query->toSql()]);

		$supplies = $query->get();

		$wtoku_no = 'zzzzzzz';
		foreach($supplies as $supply)
		{
			if ($supply['SupplierCode'] != $wtoku_no)
			{
				$supplierledger2 = new SupplierLedger;
				$supplierledger2->SupplierCode = $supply['SupplierCode'];
				$supplierledger2->PaymentDate = $formdata['date_to'];
				$supplierledger2->ClosedFlag = 0;

				$supplierledger2->save();
				$wtoku_no = $supply['SupplierCode'];
			}
			$details = json_decode($supply['details'], true);
			foreach($details as $detail)
			{
				logger('MonthlyPurchase.supply', ['supply' => $supply]);
				logger('MonthlyPurchase.details', ['details' => $details]);
				$supplierlederdetail = new SupplierLedgerDetail;
				$supplierlederdetail->SupplierCode = $supply['SupplierCode'];
				$supplierlederdetail->PaymentDate = $formdata['date_to'];
				$supplierlederdetail->SlipNo = $supply['SupplyNumber'];
				$supplierlederdetail->InputDate = $supply['仕入日'];
				$supplierlederdetail->ClassFlag = 0;
				$supplierlederdetail->PaymentKindCode = $detail['仕入区分No'];
				//新システムで入力したデータにはNumberが保存されない
				//$supplierlederdetail->Number = $detail['Number'];
				$supplierlederdetail->ProductCode = $detail['商品No'];
				$supplierlederdetail->ProductName = $detail['商品名'] . $detail['商品名予備'] ?? '';
				$supplierlederdetail->Size1 = $detail['寸法1'];
				$supplierlederdetail->Size2 = $detail['寸法2'];
				$supplierlederdetail->Unit = $detail['単位名'];
				$supplierlederdetail->Total = $detail['総量'];
				$supplierlederdetail->PurchaseAmount = $detail['仕入金額'];
				$supplierlederdetail->PaymentAmount = 0;
				$supplierlederdetail->Remark = $supply['Remark'];
				$supplierlederdetail->OutputOrder = 10;
				$supplierlederdetail->Amount = $detail['仕入数量'];
				$supplierlederdetail->UnitPrice = $detail['単価'];

				$supplierlederdetail->save();
			}
		}

		// 支払データ
		$query = payment::query();
		$query->selectRaw("PaymentNumber");
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS PaymentDate');
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\')) AS SupplierCode');
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.Remark\')) AS Remark');
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.Application1\')) AS Application1');
		$query->selectRaw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDetailTable\')) AS PaymentDetailTable');
	
		$KeyColumn = "CAST(payments.attributes->'$.PaymentDate' AS DATE)";
		$query->whereRaw("{$KeyColumn} BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");

		$query->orderByRaw("SupplierCode");
		$query->orderByRaw("PaymentNumber");

		logger('MonthlyPurchase.Payments', ['sql' => $query->toSql()]);

		$payments = $query->get();

		// 支払区分マスタ
		$query = PaymentKind::query();
		$query->selectRaw("code");
		$query->selectRaw("name");
		$query->orderBy("code");
		$query->distinct();
		$rows = $query->get();
		$paymentkind = [];
		foreach($rows as $row) {
			$paymentkind[$row['code']] = [
				'name' => $row['name'],
			];
		}

		$wtoku_no = 'zzzzzzz';
		foreach($payments as $payment)
		{
			if ($payment['SupplierCode'] != $wtoku_no)
			{
				$supplierledger2 = new SupplierLedger;
				$supplierledger2->SupplierCode = $payment['SupplierCode'];
				$supplierledger2->PaymentDate = $formdata['date_to'];
				$supplierledger2->ClosedFlag = 0;

				$supplierledger2->save();
				$wtoku_no = $payment['SupplierCode'];
			}
			$details = json_decode($payment['PaymentDetailTable'], true);
			foreach($details as $detail)
			{
				$supplierlederdetail = new SupplierLedgerDetail;
				$supplierlederdetail->SupplierCode = $payment['SupplierCode'];
				$supplierlederdetail->PaymentDate = $formdata['date_to'];
				$supplierlederdetail->SlipNo = $payment['PaymentNumber'];
				$supplierlederdetail->InputDate = $payment['PaymentDate'];
				$supplierlederdetail->ClassFlag = 1;
				$supplierlederdetail->PaymentKindCode = $detail['PaymentType'];
				//$supplierlederdetail->Number = $detail['Number'];
				$supplierlederdetail->ProductCode = "";
				$supplierlederdetail->ProductName = "支払　　☆" . $paymentkind[$detail['PaymentType']]['name'];
				if($detail['PaymentType'] == '2') {
					$supplierlederdetail->ProductName = $supplierlederdetail->ProductName . "(" . $detail['手形番号'] . ")";
				}
				if($payment['SupplierCode'] >= "00080" && $payment['SupplierCode'] <= "00084") {
					$supplierlederdetail->ProductName = $supplierlederdetail->ProductName . "(" . $payment['Application1'] . ")";
				}
				$supplierlederdetail->Size1 = 0;
				$supplierlederdetail->Size2 = 0;
				$supplierlederdetail->Unit = "";
				$supplierlederdetail->Total = 0;
				$supplierlederdetail->PurchaseAmount = 0;
				$supplierlederdetail->PaymentAmount = $detail['Amount'];
				$supplierlederdetail->Remark = $payment['Remark'];
				$supplierlederdetail->OutputOrder = 10;
				$supplierlederdetail->Amount = 0;
				$supplierlederdetail->UnitPrice = 0;

				$supplierlederdetail->save();
			}
		}

		// 当月に仕入、支払がない仕入先で買掛残のあるものを生成
		// あとから作成
		//
		//



		// 鏡部分の生成
		$query = SupplierLedger::query();
		$query->selectRaw("SupplierCode");
		$query->selectRaw("PaymentDate");
		$query->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'");
		$query->distinct();
		$rows = $query->get();
		foreach($rows as $supplierleder2)
		{
			// 前月の仕入先元帳を取得
			$query = SupplierLedger::query();
			$query->selectRaw("SupplierCode");
			$query->selectRaw("PaymentDate");
			$query->selectRaw("CurrAccountsPayable"); // 当月買掛残
			$query->whereRaw("SupplierCode = '" . $supplierleder2['SupplierCode'] . "'");
			$query->whereRaw("CAST(PaymentDate AS DATE) < '{$formdata['date_to']}'");
			$query->orderBy("PaymentDate", "DESC");
			$prerows = $query->get();

			logger('MonthlyPurchase.SupplierLedger', ['sql' => $query->toSql()]);

			if($prerows->isEmpty())
			{
				// 前月データなし
				$PrevAccountsPayable = 0;
			} else {
				// 前月データあり
				$PrevAccountsPayable = $prerows[0]['CurrAccountsPayable'];	// 前月の当月買掛残をセット
			}
			// 当月仕入金額、当月支払金額集計
			$query = SupplierLedgerDetail::query();
			$query->selectRaw("sum(PurchaseAmount) AS PurchaseAmount");
			$query->selectRaw("sum(PaymentAmount) AS PaymentAmount");
			$query->whereRaw("SupplierCode = '" . $supplierleder2['SupplierCode'] . "'");
			$query->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'");
			$query->groupByRaw("SupplierCode");

			logger('MonthlyPurchase.SupplierLederDetail', ['sql' => $query->toSql()]);

			$currTotals = $query->get();
			if($currTotals->isEmpty())
			{
				$CurrPurchaseAmount = 0;
				$CurrPaymentAmount = 0;
			} else {
				$CurrPurchaseAmount = $currTotals[0]['PurchaseAmount'];
				$CurrPaymentAmount = $currTotals[0]['PaymentAmount'];				
			}
			$CurrAccountsPayable = $PrevAccountsPayable + $CurrPurchaseAmount - $CurrPaymentAmount;
	
			// 仕入先元帳更新
			DB::table('supplierledger')
    		->whereRaw("SupplierCode = '{$supplierleder2['SupplierCode']}'")
    		->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'")
    		->update([
        		'PrevAccountsPayable' => $PrevAccountsPayable,
        		'CurrPurchaseAmount' => $CurrPurchaseAmount,
        		'CurrPaymentAmount' => $CurrPaymentAmount,
        		'CurrAccountsPayable' => $CurrAccountsPayable
    		]);

			// 仕入先元帳明細
			$supplierlederdetail = new SupplierLedgerDetail;
			$supplierlederdetail->SupplierCode = $supplierleder2['SupplierCode'];
			$supplierlederdetail->PaymentDate = $formdata['date_to'];
			$supplierlederdetail->SlipNo = "";
			//$supplierlederdetail->InputDate = "";
			$supplierlederdetail->ClassFlag = 0;
			$supplierlederdetail->PaymentKindCode = "";
			$supplierlederdetail->Number = 0;
			$supplierlederdetail->ProductName = "前月繰越残高";
			$supplierlederdetail->Size1 = 0;
			$supplierlederdetail->Size2 = 0;
			$supplierlederdetail->Unit = "";
			$supplierlederdetail->Total = 0;
			$supplierlederdetail->PurchaseAmount = $PrevAccountsPayable;
			$supplierlederdetail->PaymentAmount = 0;
			$supplierlederdetail->Remark = "";
			$supplierlederdetail->OutputOrder = 5;
			$supplierlederdetail->Amount = 0;
			$supplierlederdetail->UnitPrice = 0;

			$supplierlederdetail->save();

		}


		// 仕入先元帳
		$query = SupplierLedger::query();
		$query->selectRaw("SupplierCode");
		$query->selectRaw("PaymentDate");
		$query->selectRaw("PrevAccountsPayable"); // 前月買掛残
		$query->selectRaw("CurrPurchaseAmount"); // 当月仕入金額
		$query->selectRaw("CurrPaymentAmount"); // 当月支払金額
		$query->selectRaw("CurrAccountsPayable"); // 当月買掛残
		$query->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'");
		$query->leftJoin('suppliers', 'code', '=', 'SupplierCode');
		$query->selectRaw("suppliers.name as Name");
		$query->selectRaw('JSON_UNQUOTE(suppliers.attributes->\'$.予備\') AS 予備');
		$query->orderByRaw("SupplierCode");
		$query->distinct();
		$rows = $query->get();

		$supplierledger = [];
		foreach($rows as $row)
		{
			$query = SupplierLedgerDetail::query();
			$query->selectRaw("SlipNo");
			$query->selectRaw("InputDate");
			$query->selectRaw("ClassFlag");
			$query->selectRaw("PaymentKindCode");
			$query->selectRaw("Number");
			$query->selectRaw("ProductCode");
			$query->selectRaw("ProductName");
			$query->selectRaw("Size1");
			$query->selectRaw("Size2");
			$query->selectRaw("Unit");
			$query->selectRaw("Total");
			$query->selectRaw("PurchaseAmount");
			$query->selectRaw("PaymentAmount");
			$query->selectRaw("Remark");
			$query->selectRaw("OutputOrder");
			$query->selectRaw("Amount");
			$query->selectRaw("UnitPrice");
			$query->whereRaw("SupplierCode = '" . $row['SupplierCode'] . "'");
			$query->whereRaw("CAST(PaymentDate AS DATE) = '{$formdata['date_to']}'");
			$query->orderByRaw("SupplierCode");
			$query->orderByRaw("OutputOrder");
			$query->orderByRaw("InputDate");
			$query->orderByRaw("ClassFlag");
			$query->orderByRaw("SlipNo");
			$query->orderByRaw("Number");
			$supplierledgerdetail = $query->get();

			$row['detail'] = $supplierledgerdetail;
			$supplierledger[] = $row;
		}

		
		$viewdata = [
			'formdata' => $formdata,
			'supplierledger' => $supplierledger,
		];

		logger('MonthlyPurchase.ledgerist01', ['viewdata' => $viewdata]);
		//return response()->json($formdata);

		return view("monthlypurchase.ledgerist01" ,compact('viewdata'));
	}

	public function PayableList02(Request $request)
	{
		// 仕入先支払一覧表
		//logger('MonthlyPurchase.PayableList01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);

		$query = DB::table('payments')
		->select(
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS DATE) AS PaymentDate'),
			'PaymentNumber',
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\')) AS CHAR) AS SupplierCode'),
			'suppliers.name AS suppliers_name',
			DB::raw('JSON_UNQUOTE(suppliers.attributes->\'$.予備\') AS 予備'),
			'payment_kind.name AS paymentkind_name',
			'jt.money',
			'jt.満期日',
			'jt.手形番号',
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.Application1\')) AS CHAR) AS Application1'),
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.Remark\')) AS CHAR) AS Remark')
		)
		->join(DB::raw('JSON_TABLE(payments.attributes, \'$.PaymentDetailTable[*]\'
			COLUMNS(
				money INT PATH \'$.Amount\',
				payment_type INT PATH \'$.PaymentType\',
				満期日 DATE PATH \'$."満期日"\',
				手形番号 VARCHAR(255) PATH \'$."手形番号"\')
			) AS jt'), function ($join) {
			})
		->leftJoin('suppliers', DB::raw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\'))'), '=', 'suppliers.code')
		->leftJoin('payment_kind', 'jt.payment_type', '=', 'payment_kind.code')
		->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS DATE)'), [$formdata['date_from'], $formdata['date_to']])
		->orderBy('PaymentDate')
		->orderBy('PaymentNumber');

		logger('MonthlyPurchase.PayableList01', ['sql' => $query->toSql()]);

		$results = $query->get();

		$payments = [];
		foreach($results as $result)
		{
			$payments[] = (array)$result;
		}


		
		$viewdata = [
			'formdata' => $formdata,
			'payments' => $payments,
		];

		logger('MonthlyPurchase.PayableList02', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthlypurchase.payableList02" ,compact('viewdata'));
	}


	public function MonthlyList01(Request $request)
	{
		// 仕入支払（月報）
		//logger('MonthlyPurchase.PayableList01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);
		$system = new System();

		$query = DB::table('supplies')
		->select(
			'products.product_type',
			'product_types.name',
			DB::raw('SUM(jt.仕入数量) as sum_quantity'),
			DB::raw('SUM(jt.仕入金額) as sum_amount')
		)
		->join(DB::raw('JSON_TABLE(supplies.details, \'$[*]\' 
			COLUMNS(
				仕入金額 INT PATH \'$."仕入金額"\',
				仕入数量 INT PATH \'$."仕入数量"\',
				商品No INT PATH \'$."商品No"\',
				商品名 VARCHAR(255) PATH \'$."商品名"\')
			) AS jt'), function ($join) {
			})
		->leftJoin('products', 'jt.商品No', '=', 'products.code')
		->leftJoin('product_types', 'products.product_type', '=', 'product_types.code')
		->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS DATE)'), [$formdata['date_from'], $formdata['date_to']])
		->groupBy('products.product_type', 'product_types.name')
		->orderBy('products.product_type')
		->orderBy('product_types.name');

		logger('MonthlyPurchase.monthlyList01', ['sql' => $query->toSql()]);

		$results = $query->get();

		// 配列に変換
		$supplies = [];
		foreach($results as $result)
		{
			$supplies[] = (array)$result;
		}


		// 期首からの請求額合計
		$year = intval(date('Y', strtotime($formdata['date_from'])));
		$month = intval(date('m', strtotime($formdata['date_from'])));
		if ($month < $system->TermBeginingMonth())
		{
			$year--;
		}
		$termBeginDate = "{$year}-{$system->TermBeginingMonth()}-01";
		logger('MonthlyPurchase.monthlyList01', ['termBeginDate' => $termBeginDate]);


		$query = DB::table('supplies')
		->select(
			'products.product_type',
			'product_types.name',
			DB::raw('SUM(jt.仕入数量) as sum_quantity'),
			DB::raw('SUM(jt.仕入金額) as sum_amount')
		)
		->join(DB::raw('JSON_TABLE(supplies.details, \'$[*]\' 
			COLUMNS(
				仕入金額 INT PATH \'$."仕入金額"\',
				仕入数量 INT PATH \'$."仕入数量"\',
				商品No INT PATH \'$."商品No"\',
				商品名 VARCHAR(255) PATH \'$."商品名"\')
			) AS jt'), function ($join) {
			})
		->leftJoin('products', 'jt.商品No', '=', 'products.code')
		->leftJoin('product_types', 'products.product_type', '=', 'product_types.code')
		->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS DATE)'), [$termBeginDate, $formdata['date_to']])
		->groupBy('products.product_type', 'product_types.name')
		->orderBy('products.product_type');

		logger('MonthlyPurchase.monthlyList01', ['sql' => $query->toSql()]);

		$results = $query->get();
		// 配列に変換
		$yearlysupplies = [];
		foreach($results as $result)
		{
			$yearlysupplies[] = (array)$result;
		}

		logger('MonthlyPurchase.monthlyList01-yearlysupplies', [$yearlysupplies]);

		// 集計
		$producttypeRowDefault = [
			'NO' => '',
			'商品分類名' => '',
			'月計数量' => 0,
			'月計金額' => 0,
			'年計数量' => 0,
			'年計金額' => 0,
		];
		$producttypes = [];
		// 月計
		foreach($supplies as $supplie)
		{
			$producttype_code = $supplie['product_type'];
			if (!array_key_exists($producttype_code, $producttypes))
			{
				$producttypes[$producttype_code] = array_merge(
					$producttypeRowDefault,
					[
						'NO' => $producttype_code,
						'商品分類名' => $supplie['name'],
					]
				);
			}
			$producttypes[$producttype_code]['月計数量'] += $supplie['sum_quantity'];
			$producttypes[$producttype_code]['月計金額'] += $supplie['sum_amount'];
		}
		// 年計
		foreach($yearlysupplies as $supplie)
		{
			$producttype_code = $supplie['product_type'];
			if (!array_key_exists($producttype_code, $producttypes))
			{
				$producttypes[$producttype_code] = array_merge(
					$producttypeRowDefault,
					[
						'NO' => $producttype_code,
						'商品分類名' => $supplie['name'],
					]
				);
			}
			$producttypes[$producttype_code]['年計数量'] += $supplie['sum_quantity'];
			$producttypes[$producttype_code]['年計金額'] += $supplie['sum_amount'];
		}

		// 商品分類コードの昇順にソート
		asort($producttypes);

		// 支払集計
		$query = DB::table('payments')
		->select(
			DB::raw('SUM(CASE WHEN jt.payment_type IN (1, 3) THEN jt.money ELSE 0 END) AS 現金・小切手'),
			DB::raw('SUM(CASE WHEN jt.payment_type IN (4) THEN jt.money ELSE 0 END) AS 振込'),
			DB::raw('SUM(CASE WHEN jt.payment_type NOT IN (1, 3, 4, 2) THEN jt.money ELSE 0 END) AS 相殺・その他'),
			DB::raw('SUM(CASE WHEN jt.payment_type IN (2) THEN jt.money ELSE 0 END) AS 手形')
		)
		->join(DB::raw('JSON_TABLE(payments.attributes, \'$.PaymentDetailTable[*]\' 
			COLUMNS(
				money INT PATH \'$.Amount\',
				payment_type INT PATH \'$.PaymentType\')
			) AS jt'), function ($join) {
				$join->on(DB::raw('1'), DB::raw('1')); // Dummy join condition
			})
		->leftJoin('payment_kind', 'jt.payment_type', '=', 'payment_kind.code')
		->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS DATE)'), [$formdata['date_from'], $formdata['date_to']])
		->orderBy('jt.payment_type');

		$results = $query->get();
		// 配列に変換
		$payments = [];
		foreach($results as $result)
		{
			$payments[] = (array)$result;
		}

		
		$viewdata = [
			'formdata' => $formdata,
			'producttypes' => $producttypes,
			'payments' => $payments,
		];

		logger('MonthlyPurchase.monthlyList01', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthlypurchase.monthlyList01" ,compact('viewdata'));
	}

	public function ProductList01(Request $request)
	{
		// 仕入商品明細一覧表
		//logger('MonthlyPurchase.productList01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);
		$system = new System();

		$query = DB::table('products')
		->select(
			'products.code', 
			'products.name', 
			'products.unit', 
			'units.name as unit_name', 
			'products.product_type', 
			'product_types.name as producttype_name'
		)
		->leftJoin('units', 'products.unit', '=', 'units.code')
		->leftJoin('product_types', 'products.product_type', '=', 'product_types.code')
		->orderBy('products.product_type');

		logger('MonthlyPurchase.monthlyList01', ['sql' => $query->toSql()]);

		$results = $query->get();
		// 配列に変換
		$products = [];
		foreach($results as $result)
		{
			$products[] = (array)$result;
		}

		logger('MonthlyPurchase.productList01-products', ['products' => $products]);


		// 当期仕入合計
		$year = intval(date('Y', strtotime($formdata['date_from'])));
		$month = intval(date('m', strtotime($formdata['date_from'])));
		if ($month < $system->TermBeginingMonth())
		{
			$year--;
		}
		$termBeginDate = "{$year}-{$system->TermBeginingMonth()}-01";
		logger('MonthlyPurchase.productList01', ['termBeginDate' => $termBeginDate]);


		$query = DB::table('supplies')
		->select(
			'products.code',
			DB::raw('SUM(jt.仕入数量) as sum_quantity'),
			DB::raw('SUM(jt.仕入金額) as sum_amount')
		)
		->join(DB::raw('JSON_TABLE(supplies.details, \'$[*]\' 
			COLUMNS(
				仕入金額 INT PATH \'$."仕入金額"\',
				仕入数量 INT PATH \'$."仕入数量"\',
				商品No INT PATH \'$."商品No"\',
				商品名 VARCHAR(255) PATH \'$."商品名"\')
			) AS jt'), function ($join) {
			})
		->leftJoin('products', 'jt.商品No', '=', 'products.code')
		->leftJoin('product_types', 'products.product_type', '=', 'product_types.code')
		->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS DATE)'), [$termBeginDate, $formdata['date_to']])
		->groupBy('products.code');

		logger('MonthlyPurchase.monthlyList01', ['sql' => $query->toSql()]);

		$results = $query->get();
		// 配列に変換
		$yearlysupplies = [];
		foreach($results as $result)
		{
			$yearlysupplies[] = (array)$result;
		}

		logger('MonthlyPurchase.productList01-yearlysupplies', [$yearlysupplies]);


		// 前期仕入
		$year--;
		$earlytermBeginDate = "{$year}-{$system->TermBeginingMonth()}-01";
		logger('MonthlyPurchase.productList01', ['earlytermBeginDate' => $earlytermBeginDate]);

		$query = DB::table('supplies')
		->select(
			'products.code',
			DB::raw('SUM(jt.仕入数量) as sum_quantity'),
			DB::raw('SUM(jt.仕入金額) as sum_amount')
		)
		->join(DB::raw('JSON_TABLE(supplies.details, \'$[*]\' 
			COLUMNS(
				仕入金額 INT PATH \'$."仕入金額"\',
				仕入数量 INT PATH \'$."仕入数量"\',
				商品No INT PATH \'$."商品No"\',
				商品名 VARCHAR(255) PATH \'$."商品名"\')
			) AS jt'), function ($join) {
			})
		->leftJoin('products', 'jt.商品No', '=', 'products.code')
		->leftJoin('product_types', 'products.product_type', '=', 'product_types.code')
		->where(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS DATE)'), '>=', $earlytermBeginDate)
		->where(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(supplies.attributes, \'$."仕入日"\')) AS DATE)'), '<', $termBeginDate)
		->groupBy('products.code');

		logger('MonthlyPurchase.monthlyList01', ['sql' => $query->toSql()]);

		$results = $query->get();
		// 配列に変換
		$earlyyearlysupplies = [];
		foreach($results as $result)
		{
			$earlyyearlysupplies[] = (array)$result;
		}

		logger('MonthlyPurchase.productList01-earlyyearlysupplies', [$earlyyearlysupplies]);


		// 集計
		$productRowDefault = [
			'code' => '',
			'name' => '',
			'unit' => '',
			'unit_name' => '',
			'product_type' => '',
			'producttype_name' => '',
			'当期仕入数' => 0,
			'当期仕入額' => 0,
			'前期仕入数' => 0,
			'前期仕入額' => 0,
		];
		$productslist = [];

		// 商品一覧
		foreach($products as $product)
		{
			$product_code = $product['code'];
			if (!array_key_exists($product_code, $productslist))
			{
				$productslist[$product_code] = array_merge(
					$productRowDefault,
					[
						'code' => $product_code,
						'name' => $product['name'],
						'unit' => $product['unit'],
						'unit_name' => $product['unit_name'],
						'product_type' => $product['product_type'],
						'producttype_name' => $product['producttype_name'],
					]
				);
			}
		}
		// 当期
		foreach($yearlysupplies as $supplie)
		{
			$product_code = $supplie['code'];
			$productslist[$product_code]['当期仕入数'] += $supplie['sum_quantity'];
			$productslist[$product_code]['当期仕入額'] += $supplie['sum_amount'];
		}
		// 前期
		foreach($earlyyearlysupplies as $supplie)
		{
			$product_code = $supplie['code'];
			$productslist[$product_code]['前期仕入数'] += $supplie['sum_quantity'];
			$productslist[$product_code]['前期仕入額'] += $supplie['sum_amount'];
		}

		
		$viewdata = [
			'formdata' => $formdata,
			'products' => $productslist,
		];

		logger('MonthlyPurchase.productList01', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthlypurchase.productList01" ,compact('viewdata'));
	}

	public function BillList00(Request $request)
	{
		// 支払手形管理表
		//logger('MonthlyPurchase.BillList00', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);


		// 翌月満期の手形
		$nextMonthFirstDay = date('Y-m-01', strtotime($formdata['date_from'] . ' + 1 month' ) );
		$nextMonthLastDay  = date('Y-m-t' , strtotime($formdata['date_from'] . ' + 1 month' ) );

		$query = DB::table('payments')
		->select(
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS DATE) AS PaymentDate'),
			'PaymentNumber',
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\')) AS CHAR) AS SupplierCode'),
			'suppliers.name AS suppliers_name',
			'payment_kind.name AS paymentkind_name',
			'jt.money',
			'jt.満期日',
			'jt.手形番号',
			'banks.name AS banks_name',
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.Remark\')) AS CHAR) AS Remark')
		)
		->join(DB::raw('JSON_TABLE(payments.attributes, \'$.PaymentDetailTable[*]\' 
			COLUMNS(
				money INT PATH \'$.Amount\',
				payment_type INT PATH \'$.PaymentType\',
				満期日 DATE PATH \'$."満期日"\',
				手形番号 VARCHAR(255) PATH \'$."手形番号"\',
				銀行番号 VARCHAR(255) PATH \'$."銀行番号"\')
			) AS jt'), function ($join) {
				$join->on(DB::raw('1'), '=', DB::raw('1')); // Dummy join condition, assuming every row should join
			})
		->leftJoin('suppliers', DB::raw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\'))'), '=', 'suppliers.code')
		->leftJoin('payment_kind', 'jt.payment_type', '=', 'payment_kind.code')
		->leftJoin('banks', 'jt.銀行番号', '=', 'banks.code')
		->whereBetween(DB::raw('CAST(jt.満期日 AS DATE)'), [$nextMonthFirstDay, $nextMonthLastDay])
		->where('jt.payment_type', '=', 2)
		->orderBy('PaymentNumber');

		logger('MonthlyPurchase.BillList00', ['sql' => $query->toSql()]);

		$results = $query->get();
		// 配列に変換
		$billList00 = [];
		foreach($results as $result)
		{
			$billList00[] = (array)$result;
		}

		
		$viewdata = [
			'formdata' => $formdata,
			'billList00' => $billList00,
		];

		logger('MonthlyPurchase.BillList00', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthlypurchase.billList00" ,compact('viewdata'));
	}

	public function BillList01(Request $request)
	{
		// 当月発生支払手形一覧表
		//logger('MonthlyPurchase.PayableList01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);

		$query = DB::table('payments')
		->select(
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS DATE) AS PaymentDate'),
			'PaymentNumber',
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\')) AS CHAR) AS SupplierCode'),
			'suppliers.name AS suppliers_name',
			'payment_kind.name AS paymentkind_name',
			'jt.money',
			'jt.満期日',
			'jt.手形番号',
			'banks.name AS banks_name',
			DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.Remark\')) AS CHAR) AS Remark')
		)
		->join(DB::raw('JSON_TABLE(payments.attributes, \'$.PaymentDetailTable[*]\' 
			COLUMNS(
				money INT PATH \'$.Amount\',
				payment_type INT PATH \'$.PaymentType\',
				満期日 DATE PATH \'$."満期日"\',
				手形番号 VARCHAR(255) PATH \'$."手形番号"\',
				銀行番号 VARCHAR(255) PATH \'$."銀行番号"\')
			) AS jt'), function ($join) {
				$join->on(DB::raw('1'), '=', DB::raw('1')); // Dummy join condition, assuming every row should join
			})
		->leftJoin('suppliers', DB::raw('JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.SupplierCode\'))'), '=', 'suppliers.code')
		->leftJoin('payment_kind', 'jt.payment_type', '=', 'payment_kind.code')
		->leftJoin('banks', 'jt.銀行番号', '=', 'banks.code')
		->whereBetween(DB::raw('CAST(JSON_UNQUOTE(JSON_EXTRACT(payments.attributes, \'$.PaymentDate\')) AS DATE)'), [$formdata['date_from'], $formdata['date_to']])
		->where('jt.payment_type', '=', 2)
		->orderBy('PaymentNumber');

		logger('MonthlyPurchase.BillList01', ['sql' => $query->toSql()]);

		$results = $query->get();
		// 配列に変換
		$billList01 = [];
		foreach($results as $result)
		{
			$billList01[] = (array)$result;
		}

		
		$viewdata = [
			'formdata' => $formdata,
			'billList01' => $billList01,
		];

		logger('MonthlyPurchase.billList01', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthlypurchase.billList01" ,compact('viewdata'));
	}

	public function bill00(Request $request)
	{
		//logger('Monthly.bill00', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);

		$query = Deposit::query();
		$query->selectRaw("DepositNumber");
		$query->selectRaw("deposits.attributes");
		$query->where('deposits.deleted', null);
		$query->leftJoin('deposit_details AS details', 'DepositNumber', '=', 'details.deposit_number');
		$query->selectRaw("details.attributes as detail");
		$query->leftJoin('customers AS billing', "deposits.BillingCustomerCode", '=', 'billing.code');
		$query->selectRaw("billing.name as CustomerName");

		$query->whereRaw("details.attributes->>'$.DepositType' = 2"); // 2:手形
		
		$KeyColumn = "CAST(deposits.attributes->'$.DepositDate' AS DATE)";

		$query->whereRaw("{$KeyColumn} BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");
		$query->orderByRaw($KeyColumn);
		$query->orderBy('billing.code');
			
		logger('Monthly.bill00', ['sql' => $query->toSql()]);
		$deposits = $query->get();

		$query = Bank::query();
		$query->selectRaw("code");
		$query->selectRaw("bankcode");
		$query->selectRaw("name");
		$query->orderBy("code");
		$query->distinct();
		$rows = $query->get();
		$banks = [];
		foreach($rows as $row) {
			$banks[$row['code']] = [
				'bankcode' => $row['bankcode'],
				'name' => $row['name'],
			];
		}

		foreach($deposits as &$deposit)
		{
			$deposit['attributes'] = json_decode($deposit['attributes'],true);
			$deposit['detail'] = json_decode($deposit['detail'],true);
			$deposit['bank'] = $banks[$deposit['detail']['銀行番号']];
		}

		logger('Monthly.bill00', ['deposits' => $deposits]);

		
		$viewdata = [
			'formdata' => $formdata,
			'deposits' => $deposits,
		];

		logger('Monthly.bill00', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthly.bill00" ,compact('viewdata'));
	}

	public function bill01(Request $request)
	{
		//logger('Monthly.bill01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);

		$query = Deposit::query();
		$query->selectRaw("DepositNumber");
		$query->selectRaw("deposits.attributes");
		$query->where('deposits.deleted', null);
		$query->leftJoin('deposit_details AS details', 'DepositNumber', '=', 'details.deposit_number');
		$query->selectRaw("details.attributes as detail");
		$query->leftJoin('customers AS billing', "deposits.BillingCustomerCode", '=', 'billing.code');
		$query->selectRaw("billing.name as CustomerName");

		$query->whereRaw("details.attributes->>'$.DepositType' = 2"); // 2:手形
		$KeyColumn = "CAST(details.attributes->'$.PaymentDate' AS DATE)";
		$query->whereRaw("{$KeyColumn} BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");
		$query->orderByRaw($KeyColumn);
		$query->orderBy('billing.code');
			
		logger('Monthly.bill01', ['sql' => $query->toSql()]);
		$deposits = $query->get();

		$query = Bank::query();
		$query->selectRaw("code");
		$query->selectRaw("bankcode");
		$query->selectRaw("name");
		$query->orderBy("code");
		$query->distinct();
		$rows = $query->get();
		$banks = [];
		foreach($rows as $row) {
			$banks[$row['code']] = [
				'bankcode' => $row['bankcode'],
				'name' => $row['name'],
			];
		}

		foreach($deposits as &$deposit)
		{
			$deposit['attributes'] = json_decode($deposit['attributes'],true);
			$deposit['detail'] = json_decode($deposit['detail'],true);
			$deposit['bank'] = $banks[$deposit['detail']['銀行番号']];
		}

		logger('Monthly.bill01', ['deposits' => $deposits]);

		
		$viewdata = [
			'formdata' => $formdata,
			'deposits' => $deposits,
		];

		logger('Monthly.bill01', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthly.bill01" ,compact('viewdata'));
	}


	public function bill02(Request $request)
	{
		//logger('Monthly.bill02', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);

		$query = Deposit::query();
		$query->selectRaw("billing.code as CustomerCode");
		$query->selectRaw("billing.name as CustomerName");
		$query->selectRaw("DATE_FORMAT(CAST(details.attributes->'$.PaymentDate' AS DATE),'%Y-%m') AS YM");
		$query->selectRaw("SUM(details.attributes->'$.Amount') AS Price");
		$query->leftJoin('deposit_details AS details', 'DepositNumber', '=', 'details.deposit_number');
		$query->leftJoin('customers AS billing', "deposits.BillingCustomerCode", '=', 'billing.code');
		$query->where('deposits.deleted', null);
		$query->whereRaw("details.attributes->>'$.DepositType' = 2"); // 2:手形
		$KeyColumn = "CAST(details.attributes->'$.PaymentDate' AS DATE)";
		$query->whereRaw("{$KeyColumn} BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");

		$query->orderBy("CustomerCode");
		$query->orderBy("CustomerName");
		$query->orderBy("YM");

		$query->groupBy("CustomerCode");
		$query->groupBy("CustomerName");
		$query->groupBy("YM");

		logger('Monthly.bill02', ['sql' => $query->toSql()]);
		$deposits = $query->get();

		// 5か月分 と 6か月以降 の容れ物を作る
		$customerRowDefault = [
			'CustomerCode' => '',
			'CustomerName' => '',
			'TotalPrice' => 0,
			'Prices' => [],
		];
		for($i = 0; $i < 5; ++$i)
		{
			$YM = date('Y-m', strtotime($formdata['date_from'] . " {$i} month" ));
			$customerRowDefault['Prices'][$YM] = 0;
		}
		$customerRowDefault['Prices']['After'] = 0;

		logger('Monthly.bill02', ['customerRowDefault' => $customerRowDefault]);

		$customers = [];
		foreach($deposits as $deposit)
		{
			$customerCode = $deposit['CustomerCode'];
			if (!array_key_exists($customerCode, $customers))
			{
				$customers[$customerCode] = array_merge(
					$customerRowDefault,
					[
						'CustomerCode' => $customerCode,
						'CustomerName' => $deposit['CustomerName'],
					]
				);
			}

			if (array_key_exists($deposit['YM'], $customers[$customerCode]['Prices']))
			{
				$customers[$customerCode]['Prices'][$deposit['YM']] += $deposit['Price'];
			}
			else
			{
				$customers[$customerCode]['Prices']['After'] += $deposit['Price'];
			}
			$customers[$customerCode]['TotalPrice'] += $deposit['Price'];
		}

		//logger('Monthly.bill02', ['deposits' => $deposits]);
		logger('Monthly.bill02', ['customers' => $customers]);

		
		$viewdata = [
			'formdata' => $formdata,
			'header' => $customerRowDefault,
			'customers' => $customers,
		];

		logger('Monthly.bill02', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthly.bill02" ,compact('viewdata'));
	}


	// 得意先別売掛残高順位表
	//    指定月の請求額
	//    指定月の売掛金合計
	//    指定月以降の入金合計
	//    期首からの請求額合計
	public function receivable01(Request $request)
	{
		//logger('Monthly.receivable01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);
		$system = new System();

		// 指定月の請求額
		$query = Invoice::query();
		//$query->selectRaw("invoices.attributes");
		$query->whereRaw("CAST(TRIM(BOTH '\"' FROM invoices.attributes->'$.\"当月請求\".\"請求日\"') AS DATE) BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");
		$query->leftJoin('customers AS billing', 'BillingCustomerCode', '=', 'billing.code');
		$query->selectRaw("billing.code as billing_customer_code");
		$query->selectRaw("billing.name as billing_customer_name");
		$query->selectRaw("invoices.attributes->'$.\"当月請求\".\"請求額\"' as 当月請求額");
		//logger('Monthly.receivable01', ['sql' => $query->toSql()]);
		$thisMonthInvoices = $query->get();
		//logger('Monthly.receivable01', ['thisMonthInvoices' => $thisMonthInvoices]);
		
		// 売上区分
		$salesKinds = SalesKind::GetKeyValueArray();

		// 指定月の売掛金合計
		$query = Delivery::query();
		$query->whereRaw("CAST(deliveries.attributes->>'$.Summary.\"請求日\"' AS DATE) BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");
		$query->leftJoin('customers AS billing', 'BillingCustomerCode', '=', 'billing.code');
		$query->selectRaw("billing.code as billing_customer_code");
		$query->selectRaw("billing.name as billing_customer_name");
		$query->leftJoin('delivery_details AS detail', 'DeliveryNumber', '=', 'detail.delivery_number');
		$query->selectRaw("detail.attributes->>'$.Amount' AS Price");
		$query->selectRaw("detail.attributes->>'$.\"売上区分No\"' AS SalesKind");
		//$query->selectRaw("deliveries.attributes->'$.Summary.\"締めフラグ\"' AS ClosedFlag");
		$query->whereRaw("deliveries.attributes->'$.Summary.\"締めフラグ\"' = 6");
		//logger('Monthly.receivable01', ['sql' => $query->toSql()]);

		$deliveries = $query->get();
		//logger('Monthly.receivable01', ['deliveries' => $deliveries]);

		// 指定期間以降の入金合計（売掛で入金済の額）
		$query = Deposit::query();
		$query->whereRaw("'{$formdata['date_to']}' < CAST(deposits.attributes->>'$.DepositDate' AS DATE)");
		$query->leftJoin('deposit_details AS detail', 'DepositNumber', '=', 'detail.deposit_number');
		$query->leftJoin('customers AS billing', 'BillingCustomerCode', '=', 'billing.code');
		$query->selectRaw("billing.code as billing_customer_code");
		$query->selectRaw("billing.name as billing_customer_name");
		$query->selectRaw("detail.attributes->>'$.Amount' AS Price");
		$query->selectRaw("detail.attributes->>'$.DepositType' AS DepositKind");
		//$query->selectRaw("deposits.attributes->'$.ClosedFlag' AS ClosedFlag");
		$query->whereRaw("deposits.attributes->'$.ClosedFlag' = 6");
		//logger('Monthly.receivable01', ['sql' => $query->toSql()]);

		$deposits = $query->get();
		//logger('Monthly.receivable01', ['deposits' => $deposits]);

		// 期首からの請求額合計
		$year = intval(date('Y', strtotime($formdata['date_from'])));
		$month = intval(date('m', strtotime($formdata['date_from'])));
		if ($month < $system->TermBeginingMonth())
		{
			$year--;
		}
		$termBeginDate = "{$year}-{$system->TermBeginingMonth()}-01";
		logger('Monthly.receivable01', ['termBeginDate' => $termBeginDate]);

		$query = Invoice::query();
		//$query->selectRaw("invoices.attributes");
		$query->whereRaw("CAST(TRIM(BOTH '\"' FROM invoices.attributes->'$.\"当月請求\".\"請求日\"') AS DATE) BETWEEN '{$termBeginDate}' AND '{$formdata['date_to']}'");
		$query->leftJoin('customers AS billing', 'BillingCustomerCode', '=', 'billing.code');
		$query->selectRaw("billing.code as billing_customer_code");
		$query->selectRaw("billing.name as billing_customer_name");
		$query->selectRaw("SUM(invoices.attributes->'$.\"当月請求\".\"買上額\"') as 売上合計");
		$query->groupByRaw("billing_customer_code");
		$query->groupByRaw("billing_customer_name");
		$query->orderByRaw("billing_customer_code");
		//logger('Monthly.receivable01', ['sql' => $query->toSql()]);
		$salesPriceTotals = $query->get();
		//logger('Monthly.receivable01', ['salesPriceTotal' => $salesPriceTotal]);

		// 集計
		$customerRowDefault = [
			'得意先NO' => '',
			'得意先名' => '',
			'指定月請求額' => 0,
			'指定月売掛金合計' => 0,
			'指定月以降入金合計' => 0,
			'今期請求額累計' => 0,
		];
		$customers = [];
		foreach($thisMonthInvoices as $invoice)
		{
			$customer_code = $invoice['billing_customer_code'];
			if (!array_key_exists($customer_code, $customers))
			{
				$customers[$customer_code] = array_merge(
					$customerRowDefault,
					[
						'得意先NO' => $customer_code,
						'得意先名' => $invoice['billing_customer_name'],
					]
				);
				$customers[$customer_code]['指定月請求額'] += $invoice['当月請求額'];
			}
		}
		foreach($deliveries as $delivery)
		{
			$customer_code = $delivery['billing_customer_code'];
			if (!array_key_exists($customer_code, $customers))
			{
				$customers[$customer_code] = array_merge(
					$customerRowDefault,
					[
						'得意先NO' => $customer_code,
						'得意先名' => $delivery['billing_customer_name'],
					]
				);
			}
			if (array_key_exists($delivery['SalesKind'],$salesKinds))
			{
				if ($salesKinds[$delivery['SalesKind']]['surplus'] > 0)
				{
					// 売掛金合計
					$customers[$customer_code]['指定月売掛金合計'] += ($delivery['Price'] * (1 + $system->TaxRate()) );
				}
				else
				{
					// 返品・値引き
					$customers[$customer_code]['指定月売掛金合計'] -= ($delivery['Price'] * (1 + $system->TaxRate()) );
				}
			}
			else
			{
				logger('Monthly.receivable01', ['LINE'=>__LINE__,'delivery' => $delivery]);
			}
		}
		foreach($deposits as $deposit)
		{
			$customer_code = $deposit['billing_customer_code'];
			if (!array_key_exists($customer_code, $customers))
			{
				$customers[$customer_code] = array_merge(
					$customerRowDefault,
					[
						'得意先NO' => $customer_code,
						'得意先名' => $deposit['billing_customer_name'],
					]
				);
			}
			// 入金合計
			$customers[$customer_code]['指定月以降入金合計'] += $deposit['Price'];
		}
		foreach($salesPriceTotals as $salesPriceTotal)
		{
			$customer_code = $salesPriceTotal['billing_customer_code'];
			if (!array_key_exists($customer_code, $customers))
			{
				$customers[$customer_code] = array_merge(
					$customerRowDefault,
					[
						'得意先NO' => $customer_code,
						'得意先名' => $salesPriceTotal['billing_customer_name'],
					]
				);
			}
			// 入金合計
			$customers[$customer_code]['今期請求額累計'] += $salesPriceTotal['売上合計'];
		}
		foreach($customers as &$customer)
		{
			if ($customer['指定月売掛金合計'] > $customer['指定月以降入金合計'])
			{
				$customer['売掛残高'] = $customer['指定月売掛金合計'] - $customer['指定月以降入金合計'];
			}
			else
			{
				$customer['売掛残高'] = 0;
			}
		}

		// 売掛残高でソートして順位付け
		usort($customers, function ($left, $right)
		{
			if ($left['売掛残高'] != $right['売掛残高']) return ($left['売掛残高'] < $right['売掛残高']) ? 1 : -1;
			if ($left['得意先NO'] != $right['得意先NO']) return ($left['得意先NO'] - $right['得意先NO']);
			return 0;
		});
		// 順位
		$rank = 1;
		$count = 1;
		$prev = 0;
		foreach($customers as &$customer)
		{
			if ($prev != $customer['売掛残高'])
			{
				$rank = $count;
			}
			$customer['順位'] = $rank;
			$count++;
			$prev = $customer['売掛残高'];
		}



		$viewdata = [
			'formdata' => $formdata,
			'header' => $customerRowDefault,
			'customers' => $customers,
		];

		//logger('Monthly.bill02', ['viewdata' => $viewdata]);
		return view("monthly.receivable01" ,compact('viewdata'));
	}


	// 得意先別売上管理表
	public function sales01(Request $request)
	{
		//logger('Monthly.sales01', [__FILE__ => __LINE__]);
		$formdata = [
			'date_from' => request('date_from'),
			'date_to' => request('date_to'),
		];
		$version = [
			'client_version' => $request->input('version', null),
			'page_created' => $request->input('server_clock', null),
			'page_loaded_' => $request->input('client_clock', null),
		];
		$this->OperationLog($version,['formdata' => $formdata]);


		// 指定月の請求額
		$query = Invoice::query();
		//$query->selectRaw("invoices.attributes");
		$query->whereRaw("CAST(invoices.attributes->>'$.\"当月請求\".\"請求日\"' AS DATE) BETWEEN '{$formdata['date_from']}' AND '{$formdata['date_to']}'");
		$query->leftJoin('customers AS billing', 'BillingCustomerCode', '=', 'billing.code');
		$query->selectRaw("billing.code as billing_customer_code");
		$query->selectRaw("billing.name as billing_customer_name");
		$query->selectRaw("invoices.attributes->'$.\"前回請求\".\"残額\"' as 前回残額");
		$query->selectRaw("invoices.attributes->'$.\"当月請求\".\"買上額\"' as 当月買上額");
		$query->selectRaw("invoices.attributes->'$.\"当月請求\".\"返品値引額\"' as 当月返品値引額");
		$query->selectRaw("invoices.attributes->'$.\"当月請求\".\"消費税額\"' as 消費税額");
		$query->selectRaw("invoices.details as details");
		//logger('Monthly.sales01', ['sql' => $query->toSql()]);
		$invoices = $query->get();
		//logger('Monthly.sales01', ['invoices' => $invoices]);
		
		// 入金区分
		$depositKinds = DepositKind::GetKeyValueArray();

		$customerDefault = [
			'得意先NO' => '',
			'得意先名' => '',
			'前月繰越額' => 0,
			'現金・振込' => 0,
			'手形入金' => 0,
			'相殺その他' => 0,
			'入金合計' => 0,
			'入金値引' => 0,
			'差引繰越' => 0,
			'当月売上' => 0,
			'消費税' => 0,
			'当月繰越' => 0,
		];


		// 集計
		$customers = [];
		$system = new System();
		foreach($invoices as $invoice)
		{
			$billing_customer_code = $invoice['billing_customer_code'];
			if (!array_key_exists($billing_customer_code, $customers))
			{
				$customers[$billing_customer_code] = array_merge(
					$customerDefault,
					[
						'得意先NO' => $billing_customer_code,
						'得意先名' => $invoice['billing_customer_name'],
					]
				);
			}

			foreach($invoice['details'] as $detail)
			{
				if (empty($detail['入金額']))
				{
					continue;
				}
				switch ($detail['入金区分'])
				{
					case 1: // 現金
					case 4: // 振込
					case 5: // 振込手数料
					case 9: // 振込消費税
							$customers[$billing_customer_code]['現金・振込'] += $detail['入金額'];
						break;
					case 2: // 手形・でんさい
					case 3: // 小切手
						$customers[$billing_customer_code]['手形入金'] += $detail['入金額'];
						break;
					case 6: // 相殺
					case 8: // その他
						$customers[$billing_customer_code]['相殺その他'] += $detail['入金額'];
						break;
					case 7: // 入金値引き
						$customers[$billing_customer_code]['入金値引'] += $detail['入金額'];
						break;
					default:
						break;
				}
			}

			$customers[$billing_customer_code]['前月繰越額'] += $invoice['前回残額'];
			$customers[$billing_customer_code]['当月売上'] += ($invoice['当月買上額'] - $invoice['当月返品値引額']);
			$customers[$billing_customer_code]['消費税'] += $invoice['消費税額'];
		}
		foreach($customers as &$customer)
		{
			$customer['入金合計'] = $customer['現金・振込'] + $customer['手形入金'] + $customer['相殺その他'];
			$customer['差引繰越'] = $customer['前月繰越額'] - $customer['入金合計'];
			$customer['当月繰越'] = $customer['差引繰越'] + $customer['当月売上'] + $customer['消費税'];
		}

		ksort($customers);

		//logger('Monthly.sales01', ['customers' => $customers]);
		
		$viewdata = [
			'formdata' => $formdata,
			'header' => $customerDefault,
			'customers' => $customers,
		];

		logger('Monthly.sales01', ['viewdata' => $viewdata]);
		//return response()->json($formdata);
		return view("monthly.sales01" ,compact('viewdata'));
	}

}
