<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Helpers\PhoneHelper;
use App\Models\QrcodeRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;

class QrcodeController extends Controller
{
    public function generate(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'tel' => 'required|digits:10',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 422);
        }

        $tel = $request->input('tel');
        $outletid = '';
        $logkey = config('app.oneapp_logkey');
        $baseUrl = config('app.oneapp_base_url');

        // Step 1: 取得 oneTimeKey
        $step1 = Http::post("{$baseUrl}/API/GetPrivateKey.ashx", [
            'outletid' => $outletid,
            'tel'      => $tel,
            'logkey'   => $logkey,
        ]);

        if (!$step1->json('Success')) {
            return response()->json(['success' => false, 'message' => 'GetPrivateKey failed'], 400);
        }

        $oneTimeKey = $step1->json('data.oneTimeKey');

        // Step 2: 取得 User Data
        $step2 = Http::post("{$baseUrl}/API/GetUserData.ashx", [
            'oneTimeKey' => $oneTimeKey,
        ]);

        if (!$step2->json('Success')) {
            return response()->json(['success' => false, 'message' => 'GetUserData failed'], 400);
        }

        $data = $step2->json('data');

        // Step 3: 處理資料
        $encryptedPhone = PhoneHelper::encrypt($tel);
        $maskedPhone = substr($tel, 0, 2) . '*****' . substr($tel, 7);

        // Step 4: 寫入紀錄
        QrcodeRecord::create([
            'outlet_id'         => $data['outletid'],
            'outlet_name'       => $data['name'],
            'representative_id' => $encryptedPhone,
            'qr_generated_at'   => now(),
            'source'            => 'web',
        ]);

        // Step 5: 回傳
        return response()->json([
            'success' => true,
            'data' => [
                'otid'                      => $data['otid'],
                'outletid'                  => $data['outletid'],
                'name'                      => $data['name'],
                'representative_id'         => $encryptedPhone,
                'representative_id_masked'  => $maskedPhone,
            ],
        ]);
    }

    public function generateFromOneApp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'token' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 422);
        }

        // Step 1: 取得 user data
        $step = Http::post(config('app.oneapp_base_url') . '/API/GetUserData.ashx', [
            'oneTimeKey' => $request->input('token'),
        ]);

        if (!$step->json('Success')) {
            return response()->json(['success' => false, 'message' => 'GetUserData failed'], 400);
        }

        $data = $step->json();

        // Step 2: 處理資料
        $tel = $data['tel'];
        $encryptedPhone = PhoneHelper::encrypt($tel);
        $maskedPhone = substr($tel, 0, 2) . '*****' . substr($tel, 7);

        // Step 3: 寫入紀錄
        QrcodeRecord::create([
            'outlet_id'         => $data['outletid'],
            'outlet_name'       => $data['name'],
            'representative_id' => $encryptedPhone,
            'qr_generated_at'   => now(),
            'source'            => 'oneapp',
        ]);

        // Step 4: 回傳
        return response()->json([
            'success' => true,
            'data' => [
                'otid'                     => $data['otid'],
                'outletid'                 => $data['outletid'],
                'name'                     => $data['name'],
                'representative_id'        => $encryptedPhone,
                'representative_id_masked' => $maskedPhone,
            ],
        ]);
    }
}