<?php

namespace App\Http\Controllers\Lumina;
use App\Http\Controllers\Controller;
use App\Models\Mongo;
use Illuminate\Http\Request;

use DB;
use Carbon\Carbon;
use Exception;
use Image;

class SettingController extends Controller
{
    public function __construct() { login_lumina(); }

    public function index(){





    }

    public function show($id){

        $files = glob("D:\laragon\htdocs\\endoindex\\version\\*.txt"); // get all file names
        $arr = array();
        $i=0;
        foreach ($files as $file) {

            if (is_file($file)) {
                $ex01       = explode("\\",$file);
                $ex02       = explode("_",end($ex01));
                $ex03       = explode(".",end($ex02));
                $myfile     = fopen($file, "r") or die("Unable to open file!");
                $json       = jsonDecode(fread($myfile,filesize($file)));
                $arr[$i]= (array) $json;
                fclose($myfile);
                $i++;
            }
        }
        $view['files'] = array_reverse($arr);

        $view['scope_type']         = get_config_scope();
        $view['config']             = $this->read_config();
        $view['tb_procedure']       = (object) Mongo::table('tb_procedure')->get();
        $view['tb_room']            = Mongo::table('tb_room')->get();
        $view['email']              = uget("email");
        // dd($view);
        return view("lumina.setting.$id", $view);
    }

    public function read_config(){
        $json_arr = [];
        try {
            // $path = "D:/laragon/htdocs/config/project/lumina.txt";
            // $json_str = file_exists($path) ? file_get_contents($path) : '';
            // $json_arr = json_decode($json_str, true);
            // if(!$json_arr){
            //     $json_arr = [];
            // }
            $json_arr = Mongo::table('tb_lumina')->where('id', 1)->first();
        } catch (\Exception) {}
        return $json_arr;
    }

    public function store(Request $r){
        switch($r->event){
            case "shutdown"      : $this->shutdown($r); break;
            case "restart"       : $this->restart($r); break;
            case "save_config"   : return $this->save_config($r); break;
        }
    }

    public function save_config($r){
        // dd($r->all());
        //
        try {
            // $path = "D:/laragon/htdocs/config/project/lumina.txt";
            // $json_str = file_exists($path) ? file_get_contents($path) : '';
            // $arr = json_decode($json_str, true);

            // if(!$arr){
            //     $arr = [];
            // }

            // $arr['username'] = @$r->username;
            // $arr['password'] = @$r->password;
            // $arr['department'] = @$r->department;
            // $arr['procedure_code'] = @$r->procedure_code;
            // $arr['procedure'] = @$r->procedure;
            // $arr['modality'] = @$r->modality;
            // $json_str = json_encode($arr);
            // file_put_contents($path, $json_str);
            // // update or create in users (password need hash before create or users - endocapture)
            // $w[] = array('name', 'OR');
            // $or_user = Mongo::table('users')->where($w)->first();
            // if(!isset($or_user)){
            //     $user_data = $this->set_user_array($r);
            //     Mongo::table('users')->insert($user_data);
            // } else {
            //     $or_user = (object) $or_user;
            //     $user_data = $this->set_user_array($r, $or_user);
            //     Mongo::table('users')->where($w)->update($user_data);
            // }
            $u = [];
            $data = $r->all();
            $lumina = Mongo::table('tb_lumina')->where('id', 1)->first();
            if(!isset($lumina)){
                $i['id'] = 1;
                Mongo::table('tb_lumina')->insert($i);
            }
            foreach (isset($data)?$data:[] as $key => $value) {
                if($key == '_token'){
                    continue;
                }
                $u[$key] = $value;
            }
            Mongo::table('tb_lumina')->where('id', 1)->update($u);
        } catch(\Exception){}
        return redirect()->back();
    }


    public function set_user_array($r, $user_data=null){
        $i['id']                = isset($user_data->id) && $user_data->id != ""  ? $user_data->id : get_last_id('id', 'users') + 1;
        $i['department']        = $r->department;
        $i["user_status"]       = 'active';
        $i['comname']           = "endocapture01";
        $i['tablename']         = "tb_department";
        $i['user_code']         = "";
        $i["user_type"]         = "endo";
        $i['user_branch']       = "";
        $i['practical']         = "";
        $i['color']             = "#000000";
        $i["name"]              = "$r->department";
        $i['user_rfid']         = "";
        $i['user_prefix']       = "";
        $i['user_firstname']    = "$r->department";
        $i['user_lastname']     = "";
        $i['user_email']        = "";
        $i['user_config']       = "";
        $i["name"]              = "$r->department";
        $i["email"]             = @$r->username."";
        $i['phone']             = "";
        $is_same_password       = isset($r->password) && isset($user_data->password)        ? ($r->user_password == $user_data->password ): false;
        $hash                   =  bcrypt($r->password);
        $i["password"]          = $is_same_password  ? $user_data->password : $hash;// Hash::make($r->input($user."_password"));
        $i['remember_token']    = "";
        $i['opencase']          = 1;
        $i['procedure_json']    = "";

        if(isset($user_data)){
            $i['updated_at']        = Carbon::now()->toDateTimeString();
        } else {
            $i['created_at']        = Carbon::now()->toDateTimeString();
        }

        return $i;
    }

    public function shutdown(){
        system("shutdown /s /f /t 0");
    }

    public function restart(){
        system('shutdown -f -t 0 -r');
        // system("shutdown /s /f /t 1");

    }

}
