<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/api_auth.php';

function request_payload(): array
{
    $raw = file_get_contents('php://input');
    if (!$raw) {
        return $_POST ?: [];
    }

    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        return $decoded;
    }

    parse_str($raw, $parsed);
    return is_array($parsed) ? $parsed : [];
}

try {
    $session = require_family_session();
    $familyId = (int)($session['family_id'] ?? 0);
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    $data = request_payload();
    $action = (string)($data['action'] ?? $_REQUEST['action'] ?? '');

    if ($familyId <= 0) {
        api_json([
            'success' => false,
            'message' => 'Family session required.'
        ], 403);
    }

    if ($method === 'GET') {
        $stmt = db()->prepare('
            SELECT id, client_name, is_active, created_at, updated_at
            FROM clients
            WHERE family_id = ?
              AND is_active = 1
            ORDER BY client_name ASC
        ');
        $stmt->execute([$familyId]);

        $clients = array_map(static function (array $row): array {
            return [
                'id' => (int)$row['id'],
                'client_name' => (string)($row['client_name'] ?? ''),
                'name' => (string)($row['client_name'] ?? ''),
                'is_active' => (int)($row['is_active'] ?? 0),
                'created_at' => $row['created_at'] ?? null,
                'updated_at' => $row['updated_at'] ?? null,
            ];
        }, $stmt->fetchAll(PDO::FETCH_ASSOC));

        api_json([
            'success' => true,
            'clients' => $clients
        ]);
    }

    if ($method === 'POST') {
        if ($action === 'delete') {
            $id = (int)($data['id'] ?? 0);

            if ($id <= 0) {
                api_json([
                    'success' => false,
                    'message' => 'Client id is required.'
                ], 422);
            }

            $stmt = db()->prepare('
                UPDATE clients
                SET is_active = 0, updated_at = NOW()
                WHERE id = ? AND family_id = ?
            ');
            $stmt->execute([$id, $familyId]);

            if ($stmt->rowCount() < 1) {
                api_json([
                    'success' => false,
                    'message' => 'Client not found.'
                ], 404);
            }

            api_json([
                'success' => true,
                'message' => 'Client deleted.'
            ]);
        }

        $clientName = trim((string)($data['client_name'] ?? ''));

        if ($clientName === '') {
            api_json([
                'success' => false,
                'message' => 'Client name is required.'
            ], 422);
        }

        $check = db()->prepare('
            SELECT id, client_name, is_active
            FROM clients
            WHERE family_id = ?
              AND client_name = ?
            LIMIT 1
        ');
        $check->execute([$familyId, $clientName]);
        $existing = $check->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            if ((int)$existing['is_active'] === 0) {
                $restore = db()->prepare('
                    UPDATE clients
                    SET is_active = 1, updated_at = NOW()
                    WHERE id = ? AND family_id = ?
                ');
                $restore->execute([(int)$existing['id'], $familyId]);

                api_json([
                    'success' => true,
                    'message' => 'Client restored.',
                    'client' => [
                        'id' => (int)$existing['id'],
                        'client_name' => (string)$existing['client_name'],
                        'name' => (string)$existing['client_name'],
                        'is_active' => 1,
                    ],
                    'restored' => true,
                ]);
            }

            api_json([
                'success' => false,
                'message' => 'That client already exists.'
            ], 409);
        }

        $stmt = db()->prepare('
            INSERT INTO clients (family_id, client_name, is_active)
            VALUES (?, ?, 1)
        ');
        $stmt->execute([$familyId, $clientName]);

        api_json([
            'success' => true,
            'message' => 'Client created.',
            'client' => [
                'id' => (int)db()->lastInsertId(),
                'client_name' => $clientName,
                'name' => $clientName,
                'is_active' => 1,
            ],
        ], 201);
    }

    api_json([
        'success' => false,
        'message' => 'Method not allowed.'
    ], 405);

} catch (Throwable $e) {
    error_log('clients.php error: ' . $e->getMessage());

    api_json([
        'success' => false,
        'message' => 'server error',
        'error' => $e->getMessage()
    ], 500);
}