<?php
namespace App\Controllers\CRM;

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

/** 客户管理（CRM 系统）。super_admin / crm_admin 可增删改；crm_user 仅查看。 */
class CustomersController 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'],
        ];
    }

    public function index()
    {
        $customers = (new Customer())->all();
        $contactCounts = $this->contactCounts();
        return $this->renderSubsys('crm', 'crm/customers', [
            'customers'     => $customers,
            'contactCounts' => $contactCounts,
        ], $this->nav(), 'customers');
    }

    /** 每个客户的联系人数量（键=customer_id） */
    private function contactCounts(): array
    {
        $out = [];
        try {
            $rows = \Core\Db::query("SELECT customer_id, COUNT(*) AS n FROM crm_contacts GROUP BY customer_id");
            foreach ($rows->fetchAll() as $r) { $out[(int)$r['customer_id']] = (int)$r['n']; }
        } catch (\Throwable $e) {}
        return $out;
    }

    public function create()
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        return $this->renderSubsys('crm', 'crm/customer_form', ['customer' => null], $this->nav(), 'customers');
    }

    public function store()
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        if (!csrf_check()) { return $this->renderSubsys('crm', 'crm/customer_form', ['customer' => null], $this->nav(), 'customers'); }
        $data = $this->collect();
        (new Customer())->insert($data);
        return $this->redirect('CRM/customers');
    }

    public function edit($id)
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        $customer = (new Customer())->find($id);
        if (!$customer) return $this->redirect('CRM/customers');
        return $this->renderSubsys('crm', 'crm/customer_form', ['customer' => $customer], $this->nav(), 'customers');
    }

    public function update($id)
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        if (!csrf_check()) return $this->redirect('CRM/customers');
        $customer = (new Customer())->find($id);
        if (!$customer) return $this->redirect('CRM/customers');
        (new Customer())->update($id, $this->collect());
        return $this->redirect('CRM/customers');
    }

    public function destroy($id)
    {
        subsys_admin('crm') or \Core\App::forbidden('需要 CRM 管理员权限');
        (new Customer())->delete($id);
        return $this->redirect('CRM/customers');
    }

    private function collect(): array
    {
        return [
            'name'        => trim($this->post('name')),
            'company'     => trim($this->post('company')),
            'contact'     => trim($this->post('contact')),
            'phone'       => trim($this->post('phone')),
            'email'       => trim($this->post('email')),
            'country'     => trim($this->post('country')),
            'type'        => $this->post('type') ?: 'brand',
            'source'      => trim($this->post('source')),
            'level'       => $this->post('level') ?: 'C',
            'customer_no' => trim($this->post('customer_no')),
            'industry'    => trim($this->post('industry')),
            'region'      => trim($this->post('region')),
            'credit_limit'=> (float)$this->post('credit_limit'),
            'status'      => $this->post('status') ?: 'lead',
            'remark'      => trim($this->post('remark')),
            'owner'       => trim($this->post('owner')) ?: ($_SESSION['admin_name'] ?? ''),
            'created_at'  => date('Y-m-d'),
        ];
    }
}
