<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\Z_Website\VoteSite;
use App\Models\Z_Website\UserVote;
use Carbon\Carbon;

class PostbackController extends Controller
{
    public function handlePostback(Request $request, $website, $username = null)
    {
        // قائمة بالأسماء المحتملة للـ username
        $usernameKeys = ['username', 'postback', 'pingUsername', 'userid', 'id', 'uid', 'p_resp', 'user'];

        // إذا لم يتم تمرير username في المسار، استقبله من Query String أو POST
        if (!$username) {
            foreach ($usernameKeys as $key) {
                if ($request->has($key)) {
                    $username = $request->input($key);
                    break;
                }
            }
        }

        // تسجيل البيانات المستلمة
        Log::info('Voting Postback received:', [
            'website' => $website,
            'username' => $username,
            'method' => $request->method(),
            'data' => $request->all(),
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent()
        ]);

        // التحقق من البيانات المطلوبة
        if (!$username) {
            Log::error('Missing required parameter: username.');
            return response()->json(['error' => 'Missing required parameter: username.'], 400);
        }

        try {
            // البحث عن موقع التصويت
            $voteSite = VoteSite::where('site_name', 'LIKE', "%{$website}%")
                ->orWhere('vote_link', 'LIKE', "%{$website}%")
                ->where('active', 1)
                ->first();

            if (!$voteSite) {
                Log::warning("Vote site not found: {$website}");
                return response()->json(['error' => 'Vote site not found.'], 404);
            }

            // البحث عن المستخدم
            $user = DB::table('Users')->where('Username', $username)->select('JID')->first();

            if (!$user || !$user->JID) {
                Log::error("User not found or missing JID: {$username}");
                return response()->json(['error' => 'User not found or JID missing.'], 404);
            }

            // تشغيل الإجراء المخزن لمعالجة التصويت
            try {
                DB::statement("EXEC [__Vote_System] ?, ?, ?", [$user->JID, $username, $website]);
                Log::info("Vote processed successfully via stored procedure for User: {$username} - Website: {$website}");
            } catch (\Exception $spException) {
                Log::error("Stored procedure execution failed: " . $spException->getMessage());
                return response()->json([
                    'status' => 'error',
                    'message' => 'Failed to process vote via stored procedure.'
                ], 500);
            }

            Log::info("Vote processed successfully for User: {$username} - Website: {$website}");

            return response()->json([
                'status' => 'success',
                'message' => 'Vote processed successfully',
                'username' => $username,
                'website' => $website
            ]);

        } catch (\Exception $e) {
            Log::error('Error processing vote postback:', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'website' => $website,
                'username' => $username
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Failed to process vote.'
            ], 500);
        }
    }
}
