<?php

namespace App\Http\Controllers;

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

use App\Services\MailService;  // 导入 MailService
class ContactController extends Controller
{
    protected $liquidRenderer;

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


    function create()
    {
        // 构建导航数据 开始
        $breadcrumbs = [
            [
                'url' => '/',
                'name' => 'Home',
            ]
        ];

        $breadcrumbs[] = [
            'url' => '#',
            'name' => 'Contact Us',
        ];


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

        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. ');
            }

            // 询盘数据

            $inquiryData = [
                'order_number' => $distInquiry->order_number,
                'customer_name' => $distInquiry->customer_name,
                'email' => $distInquiry->email,
                'consulting_products' => $distInquiry->consulting_products,
                'freight_forwarder' => $distInquiry->freight_forwarder,
                'business_model' => $distInquiry->business_model,
                'content' => $distInquiry->content,
                'referer_url' => $distInquiry->referer_url,
            ];

            // 使用 MailService 静态方法发送邮件
            $mailSent = MailService::sendInquiryMail($inquiryData);


            // 成功时的响应
            $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 错误
        }
    }


}
