<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Console\Output\BufferedOutput;

class TenantController extends Controller
{
    
    public function load_tenant(Request $request)
    {

    	try {
			  $data_array['tenant'] = $request->tenant;
       
			  $req = reqGest('POST', 'v1/tenant/load', $data_array);
				if ($req && $req['success']) {
					return sendResponse($req['data'], "DATA_GOT_SUCCESSFULLY");
				} else {
					return sendError("Please, contact administrators");
				}
      
		} catch (Exception $e) {
				return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
		}

    }
    
	public function store(Request $request)
    {

    	try {
					// Firstly take the software informations from main database
					// create row in company_software
					$tenant = $request->tenant;
					$dbname = $tenant['dbname'];
					$subdomain = $tenant['subdomain'];
					$etablissement_id = $tenant['etab'];// from $request->etablissement_id
					$data_array = [];
					$data_array['newdbname'] = $dbname;
					$req = reqGest('POST', 'v1/generate/database', $data_array);
					if ($req && $req['success']) {

							$dbname = $req['data']['bd'];//"elearning_";// Take the prefix
							// Now create the database and if need the default data

							// create the database here, perhaps will need the cpanel api here. (to be created in helper)
							// $output = new BufferedOutput();
                        	$response = CpanelApi($dbname);
                        	$response = json_decode($response, true);
                        	if ($response['cpanelresult']['event']['result'] != '1') {
                        	    //return sendError("Please, contact administrators", $dbname);
                        	    return sendError("Please, contact administrators", $response['event']['reason']);
                        	}
                            //return sendError("Please, contact administrators", $dbname);
                            CpanelApiPrivilege($dbname);

							//Artisan::call("make:database", ['dbname' => $dbname]);
							 				
							if(changeEnv(['database' => $dbname]) ){
									// Run migration command here
									// Artisan::call('migrate');
									Artisan::call("migrate",  array('--database' => 'tenant', '--force' => true));
									// Now store tenant in main database
									$data_array['tenant'] = [];
									$data_array['tenant']['bd'] = $dbname;
									$data_array['tenant']['subdomain'] = $subdomain;
									$data_array['tenant']['etablissement_id'] = $etablissement_id;
						
									$req = reqGest('POST', 'v1/tenants', $data_array);

									if ($req && $req['success']) {
											return sendResponse($req['data'], "DATA_GOT_SUCCESSFULLY");
									} else {
											return sendError("Please, contact administrators");
									}					
						
							}
							return sendResponse([], "TENANT_CREATED_SUCCESSFULLY");

					} else {
							return sendError("FAILED TAKING PREFIX");
					}
				  
			} catch (Exception $e) {
					return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
			}

    }
    
}
