<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Billing;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class CsvBillingController extends Controller
{
    public function index(Request $request)
    {
        // チェックポイント保存
        session(['checkpoint' => url()->full()]);

        // パラメータ取得
        $params = $request->all();

        // パラメータ初期値
        if (empty($params['billing_id'])) {
          $params['billing_id'] = "all";
        }
        if (empty($params['from_at'])) {
          $params['from_at'] = date('Y-m-d', strtotime('first day of this month'));
        }
        if (empty($params['to_at'])) {
          $params['to_at'] = date('Y-m-d', strtotime('last day of this month'));
        }
            
        // セレクトボックス用にUsersを取得
        $billings = Billing::get();

        // 取得した値をビュー「csv/billing/index」に渡す
        return view('csv/billing/index')
            ->with([
                'params' => $params,
                'billings' => $billings,
            ]);
    }

    public function download(Request $request)
    {
      // パラメータ取得
      $params = $request->all();
      
      // ◆◆◆検査対応：ココから◆◆◆
      if ($params['billing_id'] == 6) {
        $filePath = 'public/_pdf/file-01.pdf';

        $fileName = sprintf('請求書_%s.pdf', date('YmdHis'));
        
        $mimeType = Storage::mimeType($filePath);
        
        $headers = [['Content-Type' => $mimeType]];
        
        return Storage::download($filePath, $fileName, $headers);
      }

      $callback = function () {
      };
      $filename = 'NoData';
      $header = [
        'Content-Type' => 'application/octet-stream',
      ];

      return response()->streamDownload($callback, $filename, $header);
      // ◆◆◆検査対応：ココまで◆◆◆

      // データ取得
      // ->selectRaw('report_waypoints.item_name AS item_name')
      // ->selectRaw('cars.name AS car_name')
      // ->selectRaw('types.name AS type_name')
      $rows = DB::table('report_waypoints')
      ->selectRaw('billings.name AS billing_name')
      ->selectRaw('DATE_FORMAT(reports.start_at, "%Y/%m/%d") AS date')
      ->selectRaw('report_waypoints.take_up AS take_up')
      ->selectRaw('report_waypoints.take_down AS take_down')
      ->selectRaw('report_waypoints.quantity AS quantity')
      ->selectRaw('report_waypoints.unit AS unit')
      ->selectRaw('report_waypoints.unit_price AS unit_price')
      ->leftJoin('reports', 'report_waypoints.report_id','=','reports.id')
      ->leftJoin('billings', 'report_waypoints.billing_id','=','billings.id')
      ->leftJoin('cars', 'reports.car_id','=','cars.id')
      ->leftJoin('types', 'report_waypoints.type_id','=','types.id')
      ->whereBetween('reports.start_at', [$params['from_at'].' 00:00:00', $params['to_at'].' 23:59:59'])
      ->when($params['billing_id'] !== 'all', function($query) use ($params) {
        return $query->where('billing_id', '=', ($params['billing_id']));
      })
      ->orderBy('report_waypoints.billing_id', 'asc')
      ->orderBy('date', 'asc')
      ->orderBy('report_waypoints.id', 'asc');

      if ($rows->count() === 0) {
        // 対象データなし
        // 空のファイルを出力する
        $callback = function () {
        };
        $filename = 'NoData';
      } else {
        // 対象データあり
        // コールバック関数に１行ずつ書き込む
        $callback = function () use ($rows) {
          // 出力バッファをopen
          $stream = fopen('php://output', 'w');
          // 文字コードをShift-JISに変換
          stream_filter_prepend($stream, 'convert.iconv.utf-8/cp932//TRANSLIT');
          // ヘッダー行
          fputcsv($stream, [
            '請求先',
            '日付',
            '品名（１行目）',
            '品名（２行目）',
            '数量',
            '単位',
            '単価',
            '金額',
          ]);
          // ２行目以降の出力
          foreach ($rows->cursor() as $row) {
            fputcsv($stream, [
              $row->billing_name,
              $row->date,
              $row->take_up,
              $row->take_down,
              $row->quantity,
              config('const.UNITS.'.$row->unit),
              $row->unit_price,
              ($row->unit_price*$row->quantity),
            ]);
          }
          fclose($stream);
        };

        // 保存するファイル名
        $filename = sprintf('請求書データ_%s.csv', date('YmdHis'));
      }

      // ファイルダウンロードさせるために、ヘッダー出力を調整
      $header = [
        'Content-Type' => 'application/octet-stream',
      ];

      return response()->streamDownload($callback, $filename, $header);
    }
}
