<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QrController extends Controller
{
    public function show($content)
    {
        return view('qr.show', compact('content'));
    }

    public function verify($type, $id)
    {
        $table = $type === 'auto' ? 'auto_orders' : 'estate_orders';
        $order = \Illuminate\Support\Facades\DB::table($table)->where('id', $id)->first();

        if (!$order) {
            abort(404);
        }

        // Add display relations and formatting
        $order->customer = $order->ordered_customer;
        $order->purposeOne = \Illuminate\Support\Facades\DB::table('purposes')->where('id', $order->purpose_id)->first();

        if ($type === 'auto') {
            $order->concernOne = \Illuminate\Support\Facades\DB::table('concerns')->where('id', $order->car_category)->first();
            $order->ownerName = trim($order->owner_last_name . ' ' . $order->owner_first_name . ' ' . $order->owner_patronymic);
            $order->name = $order->car_mark;
        } else {
            $order->regions = \Illuminate\Support\Facades\DB::table('regions')->where('id', $order->region)->first();
            $order->districts = \Illuminate\Support\Facades\DB::table('districts')->where('id', $order->district)->first();
            $order->owner = trim($order->owner_last_name . ' ' . $order->owner_first_name . ' ' . $order->owner_patronymic);
            $order->name = $order->name_of_object;
        }

        $conclusion = \Illuminate\Support\Facades\DB::table('files')
            ->where('order_id', $id)
            ->where('order_type', 'conclusion_')
            ->first();

        return view('qr.' . $type, compact('order', 'conclusion'));
    }

    public function reGenerate($id, $type)
    {
        self::generateQr($id, $type);
        return redirect()->back();
    }

    public static function generateQr($id, $type)
    {
        // type is 'auto_' or 'estate_'
        $cleanType = str_replace('_', '', $type);
        $url       = route('qr.verify', ['type' => $cleanType, 'id' => $id]);
        $dir       = 'public/attachments/' . $type . $id;
        Storage::makeDirectory($dir);
        $qr = QrCode::format('png')->size(200)->generate($url);
        Storage::put($dir . '/qr.png', $qr);
    }

    public function qrImage($type, $id)
    {
        $dbType = $type === 'auto' ? 'auto_' : 'estate_';
        $path   = storage_path('app/public/attachments/' . $dbType . $id . '/qr.png');

        if (!file_exists($path)) {
            abort(404);
        }

        return response()->file($path);
    }
}
