<?php
namespace ComptaFlowUK\Services;

defined('ABSPATH') || exit;

class ClientService {

    private static function prefix(): string {
        global $wpdb;
        return $wpdb->prefix . 'cfuk_';
    }

    public static function create(array $data): int {
        global $wpdb;
        $p = self::prefix();

        $data['uuid'] = wp_generate_uuid4();
        $data['created_by'] = get_current_user_id();
        $data['created_at'] = current_time('mysql');

        $wpdb->insert($p . 'clients', $data);
        return $wpdb->insert_id;
    }

    public static function update(int $id, array $data): bool {
        global $wpdb;
        $p = self::prefix();

        $data['updated_at'] = current_time('mysql');
        return $wpdb->update($p . 'clients', $data, ['id' => $id]) !== false;
    }

    public static function delete(int $id): bool {
        global $wpdb;
        $p = self::prefix();
        return $wpdb->delete($p . 'clients', ['id' => $id]) !== false;
    }

    public static function getById(int $id): ?array {
        global $wpdb;
        $p = self::prefix();
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$p}clients WHERE id = %d",
            $id
        ), ARRAY_A);
        return $row ?: null;
    }

    public static function getAll(int $user_id = 0, string $search = '', int $limit = 50, int $offset = 0): array {
        global $wpdb;
        $p = self::prefix();
        $uid = $user_id ?: get_current_user_id();

        $where = $wpdb->prepare("WHERE created_by = %d", $uid);
        if ($search) {
            $like = '%' . $wpdb->esc_like($search) . '%';
            $where .= $wpdb->prepare(
                " AND (company_name LIKE %s OR contact_name LIKE %s OR email LIKE %s)",
                $like, $like, $like
            );
        }

        return $wpdb->get_results(
            "SELECT * FROM {$p}clients {$where} ORDER BY company_name ASC LIMIT {$limit} OFFSET {$offset}",
            ARRAY_A
        ) ?: [];
    }

    public static function count(int $user_id = 0, string $search = ''): int {
        global $wpdb;
        $p = self::prefix();
        $uid = $user_id ?: get_current_user_id();

        $where = $wpdb->prepare("WHERE created_by = %d", $uid);
        if ($search) {
            $like = '%' . $wpdb->esc_like($search) . '%';
            $where .= $wpdb->prepare(
                " AND (company_name LIKE %s OR contact_name LIKE %s OR email LIKE %s)",
                $like, $like, $like
            );
        }

        return (int) $wpdb->get_var("SELECT COUNT(*) FROM {$p}clients {$where}");
    }

    public static function getDisplayName(array $client): string {
        if (!empty($client['company_name'])) {
            return $client['company_name'];
        }
        return $client['contact_name'] ?? '';
    }

    public static function getFullAddress(array $client): string {
        $parts = array_filter([
            $client['address_line_1'] ?? '',
            $client['address_line_2'] ?? '',
            $client['city'] ?? '',
            $client['county'] ?? '',
            $client['postcode'] ?? '',
        ]);
        return implode(', ', $parts);
    }
}
