<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ApiController extends BaseController
{
    /**
     * Return success response
     */
    protected function successResponse($data = null, $message = 'Operation successful', $code = 200): JsonResponse
    {
        $response = [
            'success' => true,
            'message' => $message,
        ];

        if ($data !== null) {
            $response['data'] = $data;
        }

        return response()->json($response, $code);
    }

    /**
     * Return error response
     */
    protected function errorResponse($message = 'Operation failed', $code = 400, $data = null): JsonResponse
    {
        $response = [
            'success' => false,
            'message' => $message,
        ];

        if ($data !== null) {
            $response['data'] = $data;
        }

        return response()->json($response, $code);
    }

    /**
     * Return validation error response
     */
    protected function validationErrorResponse($errors, $message = 'Validation failed'): JsonResponse
    {
        return response()->json([
            'success' => false,
            'message' => $message,
            'errors' => $errors,
        ], 422);
    }

    /**
     * Return resource response with pagination
     */
    protected function resourceResponse($resource, $message = 'Data retrieved successfully', $code = 200): JsonResponse
    {
        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => $resource,
        ], $code);
    }

    /**
     * Handle database transaction
     */
    protected function executeTransaction(callable $callback, $successMessage = 'Operation completed successfully')
    {
        try {
            return DB::transaction(function () use ($callback, $successMessage) {
                $result = $callback();
                return $this->successResponse($result, $successMessage);
            });
        } catch (\Illuminate\Database\QueryException $e) {
            Log::error('Database error: ' . $e->getMessage());
            
            // Handle specific database errors
            if ($e->getCode() === '23000') {
                return $this->errorResponse('Data already exists or violates constraints', 409);
            }
            
            return $this->errorResponse('Database error occurred', 500);
        } catch (\Exception $e) {
            Log::error('General error: ' . $e->getMessage());
            return $this->errorResponse($e->getMessage(), 500);
        }
    }

    /**
     * Get current user locale information
     */
    protected function getCurrentLocale(Request $request)
    {
        $countryId = $request->attributes->get('country_id');
        $languageId = $request->attributes->get('language_id');
        $localeId = $request->attributes->get('locale_id');

        return [
            'country_id' => $countryId,
            'language_id' => $languageId,
            'locale_id' => $localeId,
            'ip_country' => $request->attributes->get('ip_country'),
        ];
    }

    /**
     * Get current user information
     */
    protected function getCurrentUser(Request $request)
    {
        return $request->user();
    }

    /**
     * Check if user is guest
     */
    protected function isGuest(Request $request): bool
    {
        $user = $this->getCurrentUser($request);
        return $user && $user->is_guest;
    }

    /**
     * Generate device info array
     */
    protected function getDeviceInfo(Request $request): array
    {
        return [
            'device_id' => $request->input('device_id'),
            'platform' => $request->input('platform', 'unknown'),
            'fcm_token' => $request->input('fcm_token'),
            'app_version' => $request->input('app_version'),
            'last_ip' => $request->ip(),
            'ip_country' => $request->attributes->get('ip_country'),
        ];
    }

    /**
     * Log user activity
     */
    protected function logActivity($user, $action, $details = null)
    {
        try {
            // يمكن إضافة نظام لتسجيل نشاطات المستخدمين هنا
            Log::info("User Activity: {$action}", [
                'user_id' => $user->id,
                'action' => $action,
                'details' => $details,
                'timestamp' => now(),
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to log activity: ' . $e->getMessage());
        }
    }
}