<?php

namespace App\Http\Controllers\V3\Dashboard\Accident;

use App\Enums\AccidentStates;
use App\Exceptions\ProhibitedAction;
use App\Exports\V3\AccidentReceipt\DataTableReport;
use App\Facades\File\FileFacade;
use App\Facades\Sms\Sms;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\AccidentReceipt\ConfirmPaymentInfoRequest;
use App\Http\Requests\V3\AccidentReceipt\StoreRequest;
use App\Http\Requests\V3\AccidentReceipt\UpdateRequest;
use App\Http\Traits\ApiResponse;
use App\Models\Accident;
use App\Models\City;
use App\Models\DailyAccidentSettings;
use App\Models\Damage;
use App\Models\Province;
use App\Services\Cartables\AccidentReceiptTableService;
use App\Services\NominatimService;
use App\Services\PaymentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Throwable;

class AccidentReceiptController extends Controller
{
    use ApiResponse;

    public function index(Request $request, AccidentReceiptTableService $accidentReceiptTableService): JsonResponse
    {
        $data = $accidentReceiptTableService->dataTable($request);

        auth()->user()->addActivityComplete(1122);

        return response()->json($data);
    }

    public function excelReport(Request $request, AccidentReceiptTableService $accidentReceiptTableService): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1126);
        $name = 'گزارش از  خسارات وارده به ابنیه فنی و تاسیسات راه ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        $data = $accidentReceiptTableService->dataTable($request, true);
        return Excel::download(new DataTableReport($data['data']), $name);
    }

    public function accidentDamage(Accident $accident): JsonResponse
    {
        return $this->successResponse($accident->damages()->get(['unit', 'amount', 'value']));
    }

    public function store(StoreRequest $request, NominatimService $nominatimService): JsonResponse
    {
        DB::transaction(function () use ($request, $nominatimService) {

            $province = Province::query()->where('id', '=', $request->province_id)->first();
            $city = City::query()->where('id', '=', $request->city_id)->first();

            $accidentData = [
                'is_foreign'    => $request->is_foreign,
                'province_id' => $province->id,
                'province_fa' => $province->name_fa,
                'city_id' => $city->id,
                'city_fa' => $city->name_fa,
                'axis_name' => $request->axis_name,
                'driver_name' => $request->driver_name,
                'plaque' => $request->plaque,
                'driver_national_code' => $request->driver_national_code,
                'driver_phone_number' => $request->driver_phone_number,
                'user_id' => auth()->user()->id,
                'lat' => $request->lat,
                'lng' => $request->lng,
                'accident_type' => $request->accident_type,
                'accident_date' => $request->accident_date,
                'accident_time' => $request->accident_time,
                'accident_type_fa' => DailyAccidentSettings::query()->where('type', 'accident_type')->where('name', $request->accident_type)->first()->value,
                'way_id' => $nominatimService->get_way_id_from_nominatim($request->lat, $request->lng),
                'report_base' => $request->report_base,
                'police_serial' => $request->police_serial ?? null,
                'police_file_date' => $request->police_file_date ?? null,
                'status' => AccidentStates::BEDON_EGHDAM->value,
                'status_fa' => AccidentStates::name(AccidentStates::BEDON_EGHDAM->value),
            ];

            $sum = 0;
            $damageData = [];

            foreach ($request->damage_items as $key => $item) {
                $damage = Damage::query()->find($item['id']);
                $damageData[$item['id']] = [
                    'value' => $item['value'],
                    'unit' => $damage->unit,
                    'amount' => $item['amount'],
                ];
                $sum += $item['amount'];
            }

            $ojrate_nasb = $sum/100*20;
            $sum += $ojrate_nasb;

            $accidentData['ojrate_nasb'] = $ojrate_nasb;
            $accidentData['sum'] = $sum;

            $accident = Accident::query()->create($accidentData);
            $accident->damage_picture1 = FileFacade::save($request->file('damage_picture1'), "receipts_files/{$accident->id}");
            $accident->damage_picture2 = FileFacade::save($request->file('damage_picture2'), "receipts_files/{$accident->id}");
            $accident->police_file = $request->report_base ? null : FileFacade::save($request->file('police_file'), "receipts_files/{$accident->id}");
            $accident->save();

            $accident->damages()->attach($damageData);

            auth()->user()->addActivityComplete(1123);
        });

        return $this->successResponse();
    }

    public function show(Accident $accident): JsonResponse
    {
        return $this->successResponse($accident->load('damages'));
    }

    public function update(Accident $accident, UpdateRequest $request, NominatimService $nominatimService): JsonResponse
    {
        DB::transaction(function () use ($request, $accident, $nominatimService) {

            $province = Province::query()->where('id', '=', $request->province_id)->first();
            $city = City::query()->where('id', '=', $request->city_id)->first();

            $accidentData = [
                'is_foreign'    => $request->is_foreign,
                'province_id' => $province->id,
                'province_fa' => $province->name_fa,
                'city_id' => $city->id,
                'city_fa' => $city->name_fa,
                'axis_name' => $request->axis_name,
                'driver_name' => $request->driver_name,
                'plaque' => $request->plaque,
                'driver_national_code' => $request->driver_national_code,
                'driver_phone_number' => $request->driver_phone_number,
                'user_id' => auth()->user()->id,
                'lat' => $request->lat,
                'lng' => $request->lng,
                'accident_type' => $request->accident_type,
                'accident_date' => $request->accident_date,
                'accident_time' => $request->accident_time,
                'accident_type_fa' => DailyAccidentSettings::query()->where('type', 'accident_type')->where('name', $request->accident_type)->first()->value,
                'way_id' => $nominatimService->get_way_id_from_nominatim($request->lat, $request->lng),
                'report_base' => $request->report_base,
                'police_serial' => $request->police_serial ?? null,
                'police_file_date' => $request->police_file_date ?? null,
            ];

            if ($request->report_base && $accident->police_file) {
                FileFacade::delete($accident->police_file, true);
            }

            if ($request->has('police_file')) {
                if ($accident->police_file) {FileFacade::delete($accident->police_file, true);}
                $accidentData['police_file'] = FileFacade::save($request->file('police_file'), "receipts_files/{$accident->id}/");
            }

            if ($request->has('damage_picture1')) {
                FileFacade::delete($accident->damage_picture1, true);
                $accidentData['damage_picture1'] = FileFacade::save($request->file('damage_picture1'), "receipts_files/{$accident->id}/");
            }

            if ($request->has('damage_picture2')) {
                FileFacade::delete($accident->damage_picture2, true);
                $accidentData['damage_picture2'] = FileFacade::save($request->file('damage_picture2'), "receipts_files/{$accident->id}/");
            }

            $sum = 0;
            $damageData = [];

            foreach ($request->damage_items as $key => $item) {
                $damage = Damage::query()->find($item['id']);
                $damageData[$item['id']] = [
                    'value' => $item['value'],
                    'unit' => $damage->unit,
                    'amount' => $item['amount'],
                ];
                $sum += $item['amount'];
            }

            $ojrate_nasb = $sum/100*20;
            $sum += $ojrate_nasb;

            $accidentData['ojrate_nasb'] = $ojrate_nasb;
            $accidentData['sum'] = $sum;

            $accident->update($accidentData);

            $accident->damages()->sync($damageData);

            auth()->user()->addActivityComplete(1124);
        });

        return $this->successResponse();
    }

    /**
     * @throws Throwable
     */
    public function destroy(Accident $accident): JsonResponse
    {
        throw_if($accident->status != AccidentStates::BEDON_EGHDAM->value, new ProhibitedAction('قابلیت حذف در این مرحله وجود ندارد'));

        FileFacade::deleteDirectory("receipts_files/{$accident->id}");

        DB::transaction(function () use ($accident) {

            $accident->damages()->detach();

            $accident->delete();

            auth()->user()->addActivityComplete(1125);
        });

        return $this->successResponse();
    }

    public function generateInsuranceLetter(Accident $accident): JsonResponse
    {
        DB::transaction(function () use ($accident) {
            $accident->update([
                'status' => AccidentStates::SODOR_NAME_BIME_VA_DAGHI->value,
                'status_fa' => AccidentStates::name(AccidentStates::SODOR_NAME_BIME_VA_DAGHI->value),
            ]);

            auth()->user()->addActivityComplete(1126);
        });

        $account_data = Province::query()->where('id', $accident->province_id)->first();

        return $this->successResponse([
            $account_data,
            $accident->load('damages')
        ]);
    }

    public function confirmPaymentInfo(ConfirmPaymentInfoRequest $request, Accident $accident): JsonResponse
    {
        DB::transaction(function () use ($request, $accident) {

            $accident->update([
                'deposit_insurance_image' => $request->has('deposit_insurance_image') ? FileFacade::save($request->deposit_insurance_image, "receipts_files/{$accident->id}/deposit_insurance") : null,
                'deposit_insurance_amount' => $request->deposit_insurance_amount ?? 0,
                'deposit_daghi_image' => $request->has('deposit_daghi_image') ? FileFacade::save($request->deposit_daghi_image, "receipts_files/{$accident->id}/deposit_daghi") : null,
                'deposit_daghi_amount' => $request->deposit_daghi_amount ?? 0,
                'status' => AccidentStates::SABT_FISH->value,
                'status_fa' => AccidentStates::name(AccidentStates::SABT_FISH->value),
            ]);

            auth()->user()->addActivityComplete(1132);
        });

        return $this->successResponse();
    }

    /**
     * @throws Throwable
     */
    public function submitInvoice(Accident $accident, PaymentService $paymentService): JsonResponse
    {
        $final_amount = $accident->sum - ($accident->deposit_insurance_amount + $accident->deposit_daghi_amount);

        throw_if($final_amount < 0, new ProhibitedAction('مبالغ داغی و بیمه از مبلغ کل بیشتر می باشد.'));

        $bill_code = $paymentService->invoiceBillApi($accident->driver_national_code, $final_amount);

        DB::transaction(function () use ($bill_code, $final_amount, $accident) {

            $accident->update([
                'final_amount' => $final_amount,
                'bill_code' => $bill_code,
                'status' => AccidentStates::SODOR_FACTOR->value,
                'status_fa' => AccidentStates::name(AccidentStates::SODOR_FACTOR->value),
            ]);

            auth()->user()->addActivityComplete(1129);
        });

        $msg = "فاکتور با شناسه پرداخت \n" . explode("/", $accident->bill_code)[0]. "\n در سامانه سازمان راهداری ثبت شد. برای پرداخت از لینک زیر اقدام نمایید.\n\n".env("PAYMENT_LINK")."/#/pay/".explode("/", $accident->bill_code)[0]."/$final_amount";

        Sms::sendSms($accident->driver_phone_number, $msg);

        return $this->successResponse();
    }

    public function checkPaymentStatus(Accident $accident, PaymentService $paymentService): JsonResponse
    {
        DB::transaction(function () use ($accident, $paymentService) {
            if ($accident->final_amount > 0) {

                $response = json_decode($paymentService->callPaymentStatusBillApi(explode("/", $accident->bill_code)[0]));

                if ($response->isPayed) {
                    $accident->update([
                        'status' => AccidentStates::PARDAKHT_FACTOR->value,
                        'status_fa' => AccidentStates::name(AccidentStates::PARDAKHT_FACTOR->value),
                    ]);
                }
            }
            else
            {
                $accident->update([
                    'status' => AccidentStates::PARDAKHT_FACTOR->value,
                    'status_fa' => AccidentStates::name(AccidentStates::PARDAKHT_FACTOR->value),
                ]);
            }

            auth()->user()->addActivityComplete(1130);
        });

        return $this->successResponse($accident);
    }

    public function generatePoliceDocument(Request $request, Accident $accident): JsonResponse
    {
        DB::transaction(function () use ($request, $accident) {

            $accident->update([
                'status' => AccidentStates::SODOR_NAME_POLICE_RAH->value,
                'status_fa' => AccidentStates::name(AccidentStates::SODOR_NAME_POLICE_RAH->value),
            ]);

            auth()->user()->addActivityComplete(1131);
        });

        return $this->successResponse($accident);
    }

    public function sendSmsAgain(Accident $accident): JsonResponse
    {
        $msg = "فاکتور با شناسه پرداخت \n" . explode("/", $accident->bill_code)[0]. "\n در سامانه سازمان راهداری ثبت شد. برای پرداخت از لینک زیر اقدام نمایید.\n\n".env("PAYMENT_LINK")."/#/pay/".explode("/", $accident->bill_code)[0]."/$accident->final_amount";

        Sms::sendSms($accident->driver_phone_number, $msg);

        return $this->successResponse();
    }

    public function accidentTypes(): JsonResponse
    {
        return $this->successResponse(DailyAccidentSettings::query()->where('type', 'accident_type')->get());
    }
}
