<?php

namespace App\Http\Controllers\Game;

use App\Http\Controllers\Controller;
use App\Models\ClientLog;
use Illuminate\Http\Request;

class ClientLogController extends Controller
{
    /**
     * Record client log
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function recordLog(Request $request)
    {
        try {
            $logType = $request->input('log_type');
            
            // Validate log_type
            if (empty($logType) || !in_array($logType, ['register', 'pay'])) {
                return apiReturnFail('Invalid log_type. Must be register or pay');
            }

            $data = [
                'log_type' => $logType,
                'userID' => $request->input('userID'),
                'Channel' => $request->input('c'),
                'campaign_id' => $request->input('campaign_id'),
                'ad_id' => $request->input('ad_id'),
                'pixel' => $request->input('pixel'),
                'pixelID' => $request->input('pixelID'),
                'log_date' => $request->input('log_date') ?: date('Y-m-d'),
            ];

            $result = ClientLog::addLog($data);

            if ($result) {
                return apiReturnSuc(['message' => 'Log recorded successfully']);
            } else {
                return apiReturnFail('Failed to record log');
            }
        } catch (\Exception $e) {
            \Log::error('Client log record error: ' . $e->getMessage(), [
                'request' => $request->all(),
                'trace' => $e->getTraceAsString()
            ]);
            return apiReturnFail('Error: ' . $e->getMessage());
        }
    }
}
