<?php
/**
 * ServiceContractPocs · Slice 8Z-z-A'.
 *
 * Contract-scoped points-of-contact — the client's overall relationship
 * (account manager, regional ops lead, escalation contact). Inherited by
 * every site under the contract unless a site-specific POC overrides.
 *
 * Site-specific POCs live in ServiceContractSitePocs and take precedence
 * in the site drawer UI.
 */
class ServiceContractPocs extends Model
{
    public const ROLES = ['ACCOUNT_MANAGER','REGIONAL_OPS','TECH_LEAD','FINANCE','ESCALATION','OTHER'];

    /** Project-level POCs for one contract — primary first, then by role. */
    public function listFor(int $contractId): array
    {
        return (new DB())->mySelect(
            "SELECT * FROM service_contract_pocs
              WHERE contract_id = :c AND deleted = 0
              ORDER BY is_primary DESC, poc_role, c0d",
            [':c' => $contractId]
        ) ?: [];
    }

    /**
     * Upsert one project POC. When is_primary flips to 1, any other primary
     * POCs on the same contract are demoted so exactly one is primary at a time.
     */
    public function save(int $contractId, array $d, int $userId): array
    {
        if ($contractId <= 0) return ['ok' => false, 'msg' => 'contract_id required.'];
        $name = trim((string)($d['poc_name'] ?? ''));
        if ($name === '') return ['ok' => false, 'msg' => 'poc_name required.'];
        $role = strtoupper((string)($d['poc_role'] ?? 'ACCOUNT_MANAGER'));
        if (!in_array($role, self::ROLES, true)) $role = 'OTHER';
        $isPrimary = !empty($d['is_primary']) ? 1 : 0;

        $db = new DB();
        $id = (int)($d['c0d'] ?? 0);
        $params = [
            ':c'  => $contractId,
            ':r'  => $role,
            ':n'  => $name,
            ':ph' => trim((string)($d['poc_phone'] ?? '')) ?: null,
            ':em' => trim((string)($d['poc_email'] ?? '')) ?: null,
            ':pr' => $isPrimary,
            ':nt' => trim((string)($d['notes'] ?? '')) ?: null,
        ];

        if ($id > 0) {
            // PDO strict binding — build a fresh param array for UPDATE (no :c).
            $u = [
                ':r'  => $params[':r'],
                ':n'  => $params[':n'],
                ':ph' => $params[':ph'],
                ':em' => $params[':em'],
                ':pr' => $params[':pr'],
                ':nt' => $params[':nt'],
                ':id' => $id,
            ];
            $db->insertUpdate(
                "UPDATE service_contract_pocs
                    SET poc_role=:r, poc_name=:n, poc_phone=:ph, poc_email=:em,
                        is_primary=:pr, notes=:nt
                  WHERE c0d=:id",
                $u
            );
            if ($isPrimary) $this->demoteOtherPrimaries($contractId, $id);
            return ['ok' => true, 'id' => $id];
        }
        $params[':cb'] = $userId;
        $r = $db->insertUpdate(
            "INSERT INTO service_contract_pocs
                (contract_id, poc_role, poc_name, poc_phone, poc_email, is_primary, notes, created_by, created_on)
             VALUES (:c, :r, :n, :ph, :em, :pr, :nt, :cb, NOW())",
            $params
        );
        $newId = (int)($r['last_id'] ?? 0);
        if ($isPrimary && $newId > 0) $this->demoteOtherPrimaries($contractId, $newId);
        return ['ok' => true, 'id' => $newId];
    }

    private function demoteOtherPrimaries(int $contractId, int $keepId): void
    {
        (new DB())->insertUpdate(
            "UPDATE service_contract_pocs SET is_primary = 0
              WHERE contract_id = :c AND c0d <> :k AND is_primary = 1",
            [':c' => $contractId, ':k' => $keepId]
        );
    }

    public function remove(int $pocId): array
    {
        if ($pocId <= 0) return ['ok' => false, 'msg' => 'poc_id required.'];
        (new DB())->insertUpdate(
            "UPDATE service_contract_pocs SET deleted = 1 WHERE c0d = :id",
            [':id' => $pocId]
        );
        return ['ok' => true];
    }
}
