<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Email;


class UserController extends Controller
{
    public function updateUserScansCount(Request $request)
    {
        $data = $request->validate([
            'recipes_scans_count' => 'required|integer|min:0'
        ]);
        // Get the authenticated user
        $user = Auth::user();
        $user->recipes_scans_count = $data['recipes_scans_count'];
        $user->save();
        // Return a response
        return response()->json([
            'message' => 'Recipe counts updated successfully',
            'user' => $user
        ], 200);

    }
    
    public function updateUserTotalScansCount(Request $request)
    {
        $data = $request->validate([
            'total_scans' => 'required|integer|min:0'
        ]);
        // Get the authenticated user
        $user = Auth::user();
        $user->total_scans = $data['total_scans'];
        $user->save();
        // Return a response
        return response()->json([
            'message' => 'total scans updated successfully',
            'user' => $user
        ], 200);

    }
    public function updateRecipeCounts(Request $request)
    {
        // Validate the incoming request
        $data = $request->validate([
            'recipes_scans_count' => 'required|integer|min:0',
            'recipes_refresh_count' => 'required|integer|min:0',
            'premium' => 'required|in:0,1', // Validate 'premium' as '0' or '1'
            'expired_at' => 'required|date_format:Y-m-d H:i:s', // Validate 'expired_at' as a valid timestamp
        ]);

        // Get the authenticated user
        $user = Auth::user();

        // Update the user's recipe counts
        $user->recipes_scans_count = $data['recipes_scans_count'];
        $user->recipes_refresh_count = $data['recipes_refresh_count'];
        $user->premium = $data['premium'];
        $user->expired_at = $data['expired_at'];
        $user->save();

        // Return a response
        return response()->json([
            'message' => 'Recipe counts updated successfully',
            'user' => $user
        ], 200);
    }
    public function handlePremiumSubscription(Request $request)
    {
        // Validate the incoming request
        $data = $request->validate([
            'revenuecat_user_id' => 'required',
            'expiration_date' => 'required|date_format:Y-m-d H:i:s', // Validate 'expired_at' as a valid timestamp
            'subscription_status' => 'required',
        ]);

        // Get the authenticated user
        $user = Auth::user();

        $user->revenuecat_user_id = $data['revenuecat_user_id'];;
        $user->premium = 1;
        $user->subscription_status = $data['subscription_status'];
        $user->subscription_ends_at = $data['expiration_date'];
        $user->save();

        // Return a response
        return response()->json([
            'message' => 'User Subscription Successfully',
            'user' => $user
        ], 200);
    }
    public function updateAcceptedTerms(Request $request)
    {
        // Validate the incoming request
        $data = $request->validate([
            'accepted_terms' => 'required|in:0,1',
        ]);

        // Get the authenticated user
        $user = Auth::user();

        // Update the user's recipe counts
        $user->accepted_terms = $data['accepted_terms'];
        $user->save();
        
        Email::firstOrCreate(
            ['email' => $user->email]
        );
        
        // Return a response
        return response()->json([
            'message' => 'Accepted Terms updated successfully',
            'user' => $user
        ], 200);
    }
    
    //statistic apis
    // Check if the user is an administrator
    private function isAdmin()
    {
        return Auth::check() && Auth::user()->role === 'Administrator';
    }

    // Get total users
    public function getTotalUsers()
    {
        if (!$this->isAdmin()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $totalUsers = User::count();
        return response()->json(['total_users' => $totalUsers]);
    }

    // Get users by platform
    public function getUsersByPlatform()
    {
        if (!$this->isAdmin()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $androidUsers = User::where('platform', 'android')->count();
        $iosUsers = User::where('platform', 'ios')->count();

        return response()->json([
            'android_users' => $androidUsers,
            'ios_users' => $iosUsers
        ]);
    }

    // Get premium users by platform
    public function getPremiumUsers()
    {
        if (!$this->isAdmin()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $androidPremium = User::where('platform', 'android')->where('premium', 1)->count();
        $iosPremium = User::where('platform', 'ios')->where('premium', 1)->count();

        return response()->json([
            'android_premium_users' => $androidPremium,
            'ios_premium_users' => $iosPremium
        ]);
    }

    // Get total scans by platform
    public function getTotalScans()
    {
        if (!$this->isAdmin()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $androidScans = User::where('platform', 'android')->sum('total_scans');
        $iosScans = User::where('platform', 'ios')->sum('total_scans');

        return response()->json([
            'android_scans' => $androidScans,
            'ios_scans' => $iosScans
        ]);
    }

    // Get statistics filtered by date range
    public function getUsersByDate(Request $request)
    {
        if (!$this->isAdmin()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $startDate = $request->query('start_date');
        $endDate = $request->query('end_date');

        $query = User::query();

        if ($startDate && $endDate) {
            $query->whereBetween('created_at', [$startDate, $endDate]);
        }

        $androidUsers = $query->where('platform', 'android')->count();
        $iosUsers = $query->where('platform', 'ios')->count();

        return response()->json([
            'android_users' => $androidUsers,
            'ios_users' => $iosUsers
        ]);
    }
}
