<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\ReportWaypointRequest;
use App\Models\Report;
use App\Models\ReportWaypoint;
use App\Models\Item;
use App\Models\Type;
use App\Models\Billing;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Common\SendErrorMessage;
use Illuminate\Support\Facades\Mail;
use App\Mail\MailEmergency;
use App\Http\Controllers\EmergencyController;   // メール処理を継承する

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

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

        // パラメータ初期値
        if (empty($params['sort'])) {
          $params['sort'] = 'id';
          $params['direction'] = 'asc';
        }

        // ページネーション設定
        // $page_max = config('const.DEFAULT_PAGE_MAX');
        $page_max = 10;

        // クエリ成形
        $report_waypointQuery = ReportWaypoint::query();
        $report_waypointQuery = $report_waypointQuery->where('report_id', '=', $reportId);

        // DBよりReportWaypintテーブルの値を検索
        $report_waypoints = $report_waypointQuery
            ->orderBy($params['sort'], $params['direction'])
            ->paginate($page_max);

        // DBよりURIパラメータと同じreportIdを持つReportの情報を取得
        $report = Report::findOrFail($reportId);
            
        // 取得した値をビュー「report/waypoint/index」に渡す
        return view('report/waypoint/index')
            ->with([
                'report_waypoints' => $report_waypoints,
                'params' => $params,
                'report' => $report,
            ]);
    }

    public function create($reportId)
    {
        // 空の$report_waypointを渡す
        $report_waypoint = new ReportWaypoint();

        // DBよりURIパラメータと同じreportIdを持つReportの情報を取得
        $report = Report::findOrFail($reportId);

        // セレクトボックス用にItemsを取得
        $items = Item::get();

        // セレクトボックス用にTypesを取得
        $types = Type::get();

        // セレクトボックス用にBillingsを取得
        $billings = Billing::get();

        return view('report/waypoint/create', compact('report_waypoint', 'report', 'items', 'types', 'billings'));
    }

    public function emergency($reportId)
    {
        // 空の$report_waypointを渡す
        $report_waypoint = new ReportWaypoint();

        // DBよりURIパラメータと同じreportIdを持つReportの情報を取得
        $report = Report::findOrFail($reportId);

        // セレクトボックス用にItemsを取得
        $items = Item::get();

        // セレクトボックス用にTypesを取得
        $types = Type::get();

        // セレクトボックス用にBillingsを取得
        $billings = Billing::get();

        return view('report/waypoint/emergency', compact('report_waypoint', 'report', 'items', 'types', 'billings'));
    }

    public function store(ReportWaypointRequest $request, $reportId)
    {
        // エラーメッセージ
        $error_messages = [];
        if (!empty($error_messages)) {
          return SendErrorMessage::validationException($request, $error_messages);
        }

        $report_waypoint = new ReportWaypoint();
        $report_waypoint->report_id = $reportId;
        $report_waypoint->take_up = $request->take_up;
        $report_waypoint->take_down = $request->take_down;
        $report_waypoint->item_name = $request->item_name;
        $report_waypoint->quantity = $request->quantity;
        $report_waypoint->unit = $request->unit;
        $report_waypoint->unit_price = $request->unit_price;
        $report_waypoint->type_id = $request->type_id;
        $report_waypoint->billing_id = $request->billing_id;
        $report_waypoint->billing_disposal_name = $request->billing_disposal_name;
        $report_waypoint->highway_money = $request->highway_money;
        $report_waypoint->highway_payment = $request->highway_payment;
        $report_waypoint->emergency = $request->emergency;
        $report_waypoint->address = $request->address;
        $report_waypoint->note = $request->note;
        $report_waypoint->save();
    
        if (!empty($request->emergency)) {
          // Send E-Mail
          $sent = false;
          $report = Report::findOrFail($reportId);
          if (!empty($report->user->email)) {
            // IDの簡易暗号化
            $encrypt = EmergencyController::encrypt_decrypt('encrypt', $reportId);
            $url = route('view.emergency.details', ['reportId' => $encrypt]);
  
            Mail::to($report->user->email)->send(new MailEmergency($url));
            if (count(Mail::failures()) == 0) {
              $sent = true;
            };
          }
          // メール送信結果保持
          if ($sent) {
            $message = $report->user->name . ' (' . $report->user->email . ') に緊急配車のメールを送信しました。';
          } else {
            $message = $report->user->name . ' (' . $report->user->email . ') にメールを送信しようとしましたがエラーが発生しました。メールアドレスが正しいかご確認ください。';
          }
          $result = ['status' => $sent, 'message' => $message];
          session()->push('sent-emails', $result);
        }

        return redirect(session()->get('checkpoint-second') ?? './');
    }

    public function edit($reportId, $waypointId)
    {
        // DBよりURIパラメータと同じIDを持つReportの情報を取得
        $report_waypoint = ReportWaypoint::findOrFail($waypointId);

        // DBよりURIパラメータと同じreportIdを持つReportの情報を取得
        $report = Report::findOrFail($reportId);

        // セレクトボックス用にItemsを取得
        $items = Item::get();

        // セレクトボックス用にTypesを取得
        $types = Type::get();

        // セレクトボックス用にBillingsを取得
        $billings = Billing::get();

        // 取得した値をビュー「report/waypoint/edit」に渡す
        return view('report/waypoint/edit', compact('report_waypoint', 'report', 'items', 'types', 'billings'));
    }

    public function update(ReportWaypointRequest $request, $reportId, $waypointId)
    {
        // エラーメッセージ
        $error_messages = [];
        if (!empty($error_messages)) {
          return SendErrorMessage::validationException($request, $error_messages);
        }

        $report_waypoint = ReportWaypoint::findOrFail($waypointId);
        $report_waypoint->report_id = $reportId;
        $report_waypoint->take_up = $request->take_up;
        $report_waypoint->take_down = $request->take_down;
        $report_waypoint->item_name = $request->item_name;
        $report_waypoint->quantity = $request->quantity;
        $report_waypoint->unit = $request->unit;
        $report_waypoint->unit_price = $request->unit_price;
        $report_waypoint->type_id = $request->type_id;
        $report_waypoint->billing_id = $request->billing_id;
        $report_waypoint->billing_disposal_name = $request->billing_disposal_name;
        $report_waypoint->highway_money = $request->highway_money;
        $report_waypoint->highway_payment = $request->highway_payment;
        $report_waypoint->emergency = $request->emergency;
        $report_waypoint->address = $request->address;
        $report_waypoint->note = $request->note;
        $report_waypoint->save();

        return redirect(session()->get('checkpoint-second') ?? './');
    }

    public function destroy(Request $request, $reportId, $waypointId)
    {
        // エラーメッセージ
        $error_messages = [];
        if (!empty($error_messages)) {
          return SendErrorMessage::validationException($request, $error_messages);
        }

        $report_waypoint = ReportWaypoint::findOrFail($waypointId);
        $report_waypoint->delete();
    
        return redirect(session()->get('checkpoint-second') ?? './');
    }

}
