<?php

namespace App\Http\Controllers\Settings\GoogleWorkspace;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\GoogleWorkspaceClientSecretRequest;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Models\ApiCredential;
use App\Services\Integrations\GoogleWorkspace\GoogleWorkspaceIntegration;
use Illuminate\Support\Facades\Artisan;

/**
 * Controller class for the Chrome Book api
 */
class GoogleDirectoryController extends Controller
{
    public function __construct(protected GoogleWorkspaceIntegration $integration) {}

    /**
     * Show the credentials details
     */
    public function index()
    {
        $status = 0;
        try {
            $client = $this->integration->getAccessTokenWithJwt('google_directory');

            if ($client) {
                $status = 1;
            }
        } catch (\Exception $e) {
        }

        return view('settings.google-directory.index', compact('status'));
    }

    /**
     * Show the credentials edit page
     */
    public function editCredentials()
    {
        $credential = ApiCredential::whereSlug('google_directory')->first();
        return view('settings.google-directory.credential-upload', compact('credential'));
    }

    /**
     * Save the google directory credentials. it might be a json file
     *
     * @param GoogleWorkspaceClientSecretRequest request The request object.
     */
    public function saveCredentials(GoogleWorkspaceClientSecretRequest $request)
    {
        if (getFileExtension(request()->file('client_secrete')->getClientOriginalName()) != 'json') {
            return redirect()->back()->withErrors('Client secrete file must be json file');
        }
        $path = storage_path('keys');
        if (!File::isDirectory($path)) {
            File::makeDirectory($path, 0755, true, true);
        }
        try {
            Storage::disk('keys')->put('google_directory_client_secret.json', file_get_contents(request()->file('client_secrete')));
            $oldTockenFilePath = 'google_directory_client_secret_generated.json';

            /* If already generated accesstoken exist then rename the existing file.
            (This is for reset the existing connection.)  */

            if (file_exists(storage_path('keys/' . $oldTockenFilePath))) {
                $newTockenFilePath = Carbon::now()->format('m-d-Y_H-i-s') . '_google_directory_client_secret_generated.json';
                Storage::disk('keys')->move($oldTockenFilePath, $newTockenFilePath);
            }

            //Update the Email address in API Credentials table
            $data = [
                'api_name' => 'Google Directory',
                'slug' => 'google_directory',
            ];

            ApiCredential::updateOrCreate($data, ['user_name' => $request->admin_email]);
        } catch (Exception $e) {
            Log::channel('single')->info('Google Directory credential upload - ' . $e->getMessage());
            return redirect('/google-directory')->with('error', 'Something went wrong. Please try again later.');
        }
        return redirect('/google-directory')->with('message', 'Updated successfully.');
    }

    /**
     * Syncs the data manually.
     *
     * @throws \Exception Connection error. Please check the credentials
     * @return \Illuminate\Http\JsonResponse The JSON response with the status and message
     */
    public function manualSync()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        try {
            $client = $this->integration->getAccessTokenWithJwt('google_directory');
            if (!$client) {
                return response()->json(array('status' => 'error', 'message' => 'Connection failed.'));
            }
            Artisan::call('GoogleDirectoryUsers:sync');
            // return redirect('/google-calendar')->with('message', Artisan::output());
            return response()->json(array('status' => 'success', 'message' => Artisan::output()));
        } catch (\Exception $e) {
            return response()->json(array('status' => 'error', 'message' => 'Connection error. Please check the credentials.'));
        }
    }
}
