<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\LiquidRenderer;
use App\Models\DistInquiry;

class ContactController extends Controller
{
    protected $liquidRenderer;

    public function __construct(LiquidRenderer $liquidRenderer)
    {
        $this->liquidRenderer = $liquidRenderer;
    }


    function create()
    {

        //模板支持多级目录，需要目录符号
        $output = LiquidRenderer::render('contact_create.liquid', [
            'csrf_token' => csrf_token()
        ]);

        return response($output);
    }


    function store(Request $request)
    {
        try {

            // 验证 CSRF Token
            if (!$request->has('_token') || $request->input('_token') !== csrf_token()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Invalid token.',
                ], 403); // 返回 HTTP 403 错误
            }

            // 从请求中获取所有数据
            $data = $request->all();

            // 指定特殊字段的值
            $data['dist_id'] = 0; // app('dist')->id; // 指定当前登录的分销商ID
            $data['referer_url']=$request->headers->get('referer'); // 获取上一页的URL
            $data['ip_address'] = $request->ip(); // 获取用户IP地址
            $data['order_number']= generateOrderNumber('ORD');
            // 使用模型的 create 方法插入数据
            $distInquiry = DistInquiry::create($data);

            // 如果插入失败，抛出异常
            if (!$distInquiry) {
                throw new \Exception('submit failed, please try again later. ');
            }

            // 成功时的响应
            $response = [
                'status' => 'success'
            ];


            return response()->json($response, 200);
        } catch (\Exception $e) {
            // 捕获所有异常并返回错误信息
            $response = [
                'status' => 'error',
                'message' => 'submit failed, please try again later. ',
            ];

            return response()->json($response, 500); // 返回 HTTP 500 错误
        }
    }


}
