<?php
namespace App\Controllers\CRM;

use App\Controllers\Controller;
use App\Models\CRM\Contact;
use App\Models\CRM\Customer;

/** 客户联系人（一个客户下可多人）。super_admin / crm_admin 可增删改；crm_user 仅查看。 */
class ContactsController extends Controller
{
    private function nav(): array
    {
        return [
            ['k' => 'dashboard',  'label' => '仪表盘',     'icon' => '📊', 'url' => 'CRM'],
            ['k' => 'customers',  'label' => '客户管理',   'icon' => '🤝', 'url' => 'CRM/customers'],
            ['k' => 'leads',      'label' => '商机线索',   'icon' => '💡', 'url' => 'CRM/leads'],
            ['k' => 'followups',  'label' => '跟进记录',   'icon' => '📞', 'url' => 'CRM/followups'],
            ['k' => 'contacts',   'label' => '客户联系人', 'icon' => '👥', 'url' => 'CRM/contacts'],
        ];
    }

    /** 列表：/CRM/contacts（全部）或 /CRM/contacts?customer_id=ID（某客户） */
    public function index($customerId = null)
    {
        $customerId = $customerId ? (int)$customerId : (int)($_GET['customer_id'] ?? 0);
        $customer = null;
        if ($customerId) {
            $customer = (new Customer())->find($customerId);
            $contacts = (new Contact())->where('customer_id', $customerId);
        } else {
            $contacts = $this->allWithCustomer();
        }
        return $this->renderSubsys('crm', 'crm/contacts', [
            'contacts' => $contacts,
            'customer' => $customer,
        ], $this->nav(), 'contacts');
    }

    public function create()
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        $preId = (int)($_GET['customer_id'] ?? 0);
        $customers = (new Customer())->all();
        return $this->renderSubsys('crm', 'crm/contact_form', [
            'contact'   => null,
            'customers' => $customers,
            'preId'     => $preId,
        ], $this->nav(), 'contacts');
    }

    public function store()
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        if (!csrf_check()) return $this->redirect('CRM/contacts');
        $cid = (int)$this->post('customer_id');
        $data = $this->collect();
        (new Contact())->insert($data);
        return $this->redirect($cid ? "CRM/contacts?customer_id={$cid}" : 'CRM/contacts');
    }

    public function edit($id)
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        $contact = (new Contact())->find($id);
        if (!$contact) return $this->redirect('CRM/contacts');
        $customers = (new Customer())->all();
        return $this->renderSubsys('crm', 'crm/contact_form', [
            'contact'   => $contact,
            'customers' => $customers,
            'preId'     => (int)($contact['customer_id'] ?? 0),
        ], $this->nav(), 'contacts');
    }

    public function update($id)
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        if (!csrf_check()) return $this->redirect('CRM/contacts');
        $contact = (new Contact())->find($id);
        if (!$contact) return $this->redirect('CRM/contacts');
        $cid = (int)$this->post('customer_id');
        (new Contact())->update($id, $this->collect());
        return $this->redirect($cid ? "CRM/contacts?customer_id={$cid}" : 'CRM/contacts');
    }

    public function destroy($id)
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        $contact = (new Contact())->find($id);
        $cid = $contact ? (int)($contact['customer_id'] ?? 0) : 0;
        (new Contact())->delete($id);
        return $this->redirect($cid ? "CRM/contacts?customer_id={$cid}" : 'CRM/contacts');
    }

    private function collect(): array
    {
        return [
            'customer_id' => (int)$this->post('customer_id'),
            'name'        => trim($this->post('name')),
            'title'       => trim($this->post('title')),
            'phone'       => trim($this->post('phone')),
            'email'       => trim($this->post('email')),
            'wechat'      => trim($this->post('wechat')),
            'is_primary'  => $this->post('is_primary') ? 1 : 0,
            'remark'      => trim($this->post('remark')),
            'created_at'  => date('Y-m-d'),
        ];
    }

    /** 全部联系人 + 客户名称（用于「全部联系人」视图） */
    private function allWithCustomer(): array
    {
        try {
            $rows = \Core\Db::query(
                "SELECT c.*, cu.name AS customer_name FROM crm_contacts c
                 LEFT JOIN crm_customers cu ON cu.id=c.customer_id
                 ORDER BY c.customer_id, c.id"
            )->fetchAll();
            return $rows;
        } catch (\Throwable $e) {
            return (new Contact())->all();
        }
    }
}
