<?php
namespace app\appapi\controller;

use app\appapi\BaseController;
use support\Request;
use think\facade\Db;

class ContactController extends BaseController
{
    public function getBranchList(Request $request)
    {
        $param = $request->get();
        // $where[] = ['lang', $param['lang']];

        $list = Db::name('branch')
            ->where('lang',$param['lang'])
            ->order('sort_order', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();

        return $this->Success($list);
    }

    public function addContact(Request $request)
    {
        $param = $request->post();
        // $where[] = ['lang', $param['lang']];
        $data = [
            'company' => $param['company'],
            'name' => $param['name'],
            'tel' => $param['tel'],
            'email' => $param['email'],
            'content' => $param['content'],
        ];
        
        $this->sendEmail($data);


        try{
        
            Db::name('contact')
            ->insert($data);

            return $this->Success('新增成功');
        }catch(\Exception $e){
            return $this->Error('新增失败');
        }

    }

    private function sendEmail($data)
    {
            $to      = "info.service@prodio.com.tw";
            // $to      = "wwayne.hsu@gmail.com";
            $subject = "=?UTF-8?B?".base64_encode("【普達網站-聯絡我們】")."?=";
            $message = "
            公司名稱: $data[company]
            姓名: $data[name]
            電話: $data[tel]
            電子郵件: $data[email]
            內容: $data[content]
            ";
            $headers = 'From: prodio' . "\r\n" .
                'Reply-To: info.service@prodio.com.tw' . "\r\n" .
                'X-Mailer: PHP/' . phpversion();
            mail($to, $subject, $message, $headers);       
    }
}
