<?php

namespace App\Http\Controllers\Api\Desktop;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Account;
use App\Models\Shop;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SyncAPIController extends Controller
{
    /**
     * App launch sync - returns list of users and employees
     * This endpoint is public (no authentication required)
     */
    public function appLaunchSync(Request $request): JsonResponse
    {
        $request->validate([
            'license_key' => 'required|string'
        ]);

        $licenseKey = $request->string('license_key')->toString();

        $user = User::where('license_key', $licenseKey)
            ->where('is_active', true)
            ->with('shop')
            ->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or inactive license key'
            ], 404);
        }

        // Get all users
        $users = User::where('is_active', true)
            ->where('license_key', $licenseKey)
            ->get()
            ->map(function ($user) {
                return [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'password' => $user->password,
                ];
            });

        // Get all employees from the same shop using direct shop_id from user
        $employees = null;
        $shop = null;

        if ($user->shop_id) {
            $employees = Account::where('model_type', 'employee')
                ->where('shop_id', $user->shop_id)
                ->get()
                ->map(function ($employee) {
                    return [
                        'id' => $employee->id,
                        'name' => $employee->name,
                    ];
                });

            // Get shop data directly from user relationship
            if ($user->shop) {
                $shop = [
                    'id' => $user->shop->id,
                    'name' => $user->shop->name,
                    'address' => $user->shop->address .', ' . $user->shop->city . ' Pakistan',
                    'phone' => $user->shop->phone,
                ];
            }
        }

        return response()->json([
            'success' => true,
            'data' => [
                'users' => $users,
                'employees' => $employees,
                'shop' => $shop,
            ]
        ]);
    }

}

