<?php
declare(strict_types=1);
namespace App\Repositories;
use App\Core\Repository;

final class CustomerRepository extends Repository {
    public function findByIdentifier(string $value): ?array {
        $v = trim($value);
        if ($v === '') return null;
        $normalized = preg_replace('/\D+/', '', $v) ?: '';
        return $this->one(
            "SELECT * FROM customers
             WHERE REPLACE(REPLACE(REPLACE(phone,'+',''),' ',''),'-','')=? OR civil_id=?
             ORDER BY id DESC LIMIT 1",
            [$normalized, $v]
        );
    }

    public function findById(int $id): ?array {
        return $this->one("SELECT * FROM customers WHERE id=? LIMIT 1", [$id]);
    }

    public function search(string $q): array {
        $q = trim($q);
        if ($q === '') return [];
        return $this->all(
            "SELECT * FROM customers
             WHERE full_name LIKE ? OR phone LIKE ? OR civil_id LIKE ?
             ORDER BY id DESC LIMIT 12",
            ["%$q%","%$q%","%$q%"]
        );
    }

    public function searchForAdmin(string $q = '', string $scope = 'all'): array {
        $params = [];
        $where = [];
        if ($q !== '') {
            $where[] = "(full_name LIKE ? OR phone LIKE ? OR civil_id LIKE ?)";
            $like = '%' . $q . '%';
            $params = [$like, $like, $like];
        }
        if ($scope === 'blacklist') {
            $where[] = "is_blacklisted=1";
        }
        $sql = "SELECT * FROM customers";
        if ($where) $sql .= " WHERE " . implode(" AND ", $where);
        $sql .= " ORDER BY is_blacklisted DESC, id DESC";
        return $this->all($sql, $params);
    }

    public function createOrUpdate(array $data): int {
        $existing = $this->findByIdentifier((string)($data['phone'] ?: $data['civil_id']));
        if ($existing) {
            $this->exec(
                "UPDATE customers SET full_name=?, phone=?, civil_id=?, updated_at=NOW() WHERE id=?",
                [$data['full_name'], $data['phone'], $data['civil_id'] ?: null, $existing['id']]
            );
            return (int)$existing['id'];
        }
        return $this->insert(
            "INSERT INTO customers(full_name,phone,civil_id,created_at,updated_at) VALUES(?,?,?,?,?)",
            [$data['full_name'], $data['phone'], $data['civil_id'] ?: null, date('Y-m-d H:i:s'), date('Y-m-d H:i:s')]
        );
    }

    public function blacklist(int $id, string $reason): int {
        return $this->exec(
            "UPDATE customers SET is_blacklisted=1, blacklist_reason=?, updated_at=NOW() WHERE id=?",
            [$reason, $id]
        );
    }

    public function unblacklist(int $id): int {
        return $this->exec(
            "UPDATE customers SET is_blacklisted=0, blacklist_reason=NULL, updated_at=NOW() WHERE id=?",
            [$id]
        );
    }
}
