<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\SysVarsModel;
use App\Entities\SysVar;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Database\Exceptions\DatabaseException;
use App\Models\User_accessModel;
use App\Entities\User_access;
use App\Models\SystemImagesModel;
use App\Entities\SystemImage;
use CodeIgniter\Files\File;

class Allsettings extends BaseController
{
    private SysVarsModel $model;
    private SystemImagesModel $systemimage;

    private User_accessModel $user_access_model;
    public function __construct()
    {
        $this->model = new SysVarsModel;
        $this->systemimage = new SystemImagesModel;
        $this->user_access_model = new User_accessModel;
    }

    public function index(): string
    {
        $data = $this->model->findAll();
        $images = $this->getImages();

        return view("Allsettings/index",[
                "sysvars" => $data,
                "images" => $images,
            ]);
    }



    public function update(): string
    {
        $postdata = $this->request->getPost();

        $csrf = csrf_hash();

        $data = $this->getSysVarOr404($postdata['KeyName']);

        if($data){

            $data->fill($this->request->getPost());

            $data->__unset("_method");

            if(!$data->hasChanged()){
                $comment = "Nothing to update";
                return json_encode(["comment" => $comment, "token" => $csrf]);
            }

            if($this->model->save($data)){
                $comment = "ok";
            }else{
                $comment = "fail";
            }
        }else{
            $comment = "fail";
        }
        return json_encode(["comment" => $comment, "token" => $csrf]);
    }

    public function getImages(): array
    {
        $sql = "select ImageID, UsedFor,ImageName from system_images where UsedFor in ('BAGLABEL','BAGSEAL','EXPDATE','BOXEND');";
		$db = db_connect();
		$data = $db->query($sql)->getResult('App\Entities\SystemImage');
        $images = [ 'BAGLABEL' => ['ImageID' => 0, 'ImageName' => '', 'ImageTitle' => 'Security Label'],
                    'BAGSEAL' => ['ImageID' => 0, 'ImageName' => '', 'ImageTitle' => 'Bag Seal'],
                    'EXPDATE' => ['ImageID' => 0, 'ImageName' => '', 'ImageTitle' => 'Expiry Date'],
                    'BOXEND' => ['ImageID' => 0, 'ImageName' => '', 'ImageTitle' => 'Box End']
                  ];
        foreach($data as $img){
            if($img->UsedFor == 'BAGLABEL'){
                $images['BAGLABEL'] = ['ImageID' => $img->ImageID, 'ImageName' => $this->getFullImage($img->ImageName), 'ImageTitle' => 'Security Label'];
            }
            if($img->UsedFor == 'BAGSEAL'){
                $images['BAGSEAL'] = ['ImageID' => $img->ImageID, 'ImageName' => $this->getFullImage($img->ImageName), 'ImageTitle' => 'Bag Seal'];
            }
            if($img->UsedFor == 'EXPDATE'){
                $images['EXPDATE'] = ['ImageID' => $img->ImageID, 'ImageName' => $this->getFullImage($img->ImageName), 'ImageTitle' => 'Expiry Date'];
            }
            if($img->UsedFor == 'BOXEND'){
                $images['BOXEND'] = ['ImageID' => $img->ImageID, 'ImageName' => $this->getFullImage($img->ImageName), 'ImageTitle' => 'Box End'];
            }
        }

        return $images;
    }

    private function getFullImage($image)
    {
        //$filepath =  str_replace('\\', '/',WRITEPATH . "uploads/systemimages/"); // base_url("/public/images/uploaded/recipe_$id/");
        $fullimage  = str_replace('\\', '/',base_url("/images/uploaded/systemimages/$image"));
        return $fullimage;
    }



    public function uploadImage()
    {
        $validationRule = [
            'userfile' => [
                'label' => 'Image File',
                'rules' => [
                    'uploaded[userfile]',
                    'is_image[userfile]',
                    'mime_in[userfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    // 'max_size[userfile,100]',
                    // 'max_dims[userfile,1024,768]',
                ],
            ],
        ];
        if (! $this->validateData([], $validationRule)) {
            //$data = ['uploaderrors' => $this->validator->getErrors()];
            return redirect()->back()->with("uploaderrors", $this->validator->getErrors())->withInput();
        }

        $postdata = $this->request->getPost();
        $usedfor = $postdata['usedfor'];
        $img = $this->request->getFile('userfile');

        if (! $img->hasMoved()) {

            $filepath = str_replace('\\', '/',WRITEPATH . 'uploads/' . $img->store("systemimages"));
            $data = new File($filepath);
            $imagename = esc($data->getBasename());
            $this->setPath(FCPATH . "images\\uploaded\\systemimages");
            $newimage = str_replace('\\', '/', FCPATH . "images\\uploaded\\systemimages\\$imagename");

            if ($this->copyImageToPublic($filepath, $newimage)) {
                $image = new SystemImage(["UsedFor"=>$usedfor, "ImageName"=>$imagename]);
                $imagemodel = new SystemImagesModel;
                $row =  $imagemodel->where('UsedFor',$usedfor)->first();
                if($row) {
                    $row->ImageName = $imagename;
                    $imageid = $imagemodel->save($row);
                }else{
                    $imageid = $imagemodel->insert($image);
                }

                if($imageid === false){
                    return redirect()->back()->with("uploaderrors", ['Failed to Save File Name'])->withInput();
                }
                return redirect()->to("allsettings");
            } else {

                return redirect()->back()->with("uploaderrors", ['file copy failed.From:' . $filepath . ' to:' . $newimage])->withInput();
            }
        } else {
            return redirect()->back()->with("uploaderrors", ['The file has already been moved.'])->withInput();
        }
    }

    public function imagedelete($id)
    {
        //$model = new SystemImagesModel;
        //$image = $model->find($id);

        $image = $this->systemimage->find($id);

        if ($image === null) {
            throw new PageNotFoundException("Image with id $id not found");
        }

        //$recipeid = $image->RecipeID;

        $writableimage = str_replace('\\', '/',WRITEPATH . 'uploads/' . $image->ImageName);
        $ret = $this->deleteimagefile($writableimage);
        if(null == $ret){
            $publicimage = str_replace('\\', '/',FCPATH . "images\\uploaded\\systemimages\\$image->ImageName");
            $ret = $this->deleteimagefile($publicimage);
            if(null == $ret){
                $this->systemimage->delete($id);
                return redirect()->to("allsettings")->with("message", "Image deleted.");
            }
        }
        return redirect()->back()->with("uploaderrors", ['Cannot delete that image.'. $ret]);
    }
    private function deleteimagefile($filetodelete)
    {
        if (is_file($filetodelete)) {

            chmod($filetodelete, 0777);

            if (unlink($filetodelete)) {
                return null;
            } else {
                return "Cannot delete file $filetodelete";
            }
        } else {
            return null;
        }
    }

    private function setPath(string $newpath): string
    {
        $path = str_replace('\\', '/',$newpath);
        if (! is_dir($path)) {
            mkdir($path, 0777, true);
            // create the index.html file
            if (! is_file($path . 'index.html')) {
                $file = fopen($path . 'index.html', 'x+b');
                fclose($file);
            }
        }

        return $path;
    }
    private function copyImageToPublic($imagefile, $newimage)
    {
        $data = file_get_contents($imagefile);
        return file_put_contents($newimage, $data);
    }

    private function getSysVarOr404($key): SysVar
    {
        $data = $this->model->where('KeyName',$key)->first();

        if($data === null){
            throw new PageNotFoundException("SysVar with key $key not found");
        }

        return $data;
    }

//     // private function getUser_accessOr404($uid, $ualid): User
//     // {
//     //     $user = $this->model->getIdValue() getIdValue(([]) find($id);

//     //     if($user === null){
//     //         throw new PageNotFoundException("User with id $id not found");
//     //     }

//     //     return $user;
//     // }




    //     {
//         $rules =[
//             'username' => [
//                 'label' => 'Auth.username',
//                 'rules' => [
//                     'required',
//                     'max_length[30]',
//                     'min_length[3]',
//                     'regex_match[/\A[a-zA-Z0-9\.]+\z/]',
//                     'is_unique[users.username, users.id, '.$id.']',
//                 ],
//             ],
//             'email' => [
//                 'label' => 'Auth.email',
//                 'rules' => [
//                     'required',
//                     'max_length[254]',
//                     'valid_email',
//                     'is_unique[auth_identities.secret, auth_identities.user_id, '.$id .']',
//                 ],
//             ],
//         ];


//         if( ! $this->validate($rules)) {
//             return redirect()->back()
//                             ->with("errors", $this->validator->getErrors())
//                             ->withInput();
//         }

//         $user = $this->getUserOr404($id);

//         $user->fill($this->request->getPost());


//         //dd($user);
//         $arr = json_decode(json_encode($user), true);
//         //$value = $arr['highlighting']['448364']['Data']['0'];
// //dd($arr);
//         $user_access_levels = $this->getUserAccessLevels($id);
// //dd($user_access_levels);

//         $arr  = json_decode(json_encode($user), true);
//         //dd($user);

//         $set = array();
//         $erro = array();
//         foreach($user_access_levels as $user_access_level){
//             $user_access = new User_access;
//             $ualid = $user_access_level->ualid;
//             if( isset( $arr["uaid_$ualid"]) && !empty($arr["uaid_$ualid"])){
//                 $uaid = (int)$arr["uaid_$ualid"];
//                 $user_access->uaid = $uaid;
//             }
//             // else{
//             //     $uaid = 0;
//             //     $user_access->uaid = $uaid;
//             // }
//             if( isset( $arr["can_access_$ualid"]) && $arr["can_access_$ualid"] == "1"){
//                 $user_access->can_access = 1;
//             }else{
//                 $user_access->can_access = 0;
//             }
//             if( isset( $arr["can_edit_$ualid"]) && $arr["can_edit_$ualid"] == "1"){
//                 $user_access->can_edit = 1;
//             }else{
//                 $user_access->can_edit = 0;
//             }
//             $user_access->uid = (int)$id;
//             $user_access->ualid = (int)$ualid;
//             $set[] = $user_access;
//             if(!$this->user_access_model->save($user_access)){
//                 $erro[] = $this->user_access_model->errors();
//             }
// //            $set[] = ["user_id"=>$id, "ualid" => $ualid];
//         }

//         //dd($set, $erro);

//         // $set = array();
//         // foreach($arr as $u){
//         //     $set[] = $arr["can_access_$u->ualid"];
//         //     // if( isset( $arr["can_access_$user_access_level->ualid"]) && $arr["can_access_$user_access_level->ualid"] == "1"){
//         //     //     $set[] = ["user_id"=>$id, "ualid" => $user_access_level->ualid];
//         //     // }
//         // }

//         $user->__unset("_method");

//         if(!$user->hasChanged()){
//             return redirect()->back()->with("message","Nothing to update.");
//         }

//         if( !$this->model->save($user)){
//             return redirect()->back()->with("errors",$this->model->errors())->withInput();
//         }

//         if($user->usergroup == 'admin') {
//             $user->addGroup("admin");
//         }else{
//             $user->removeGroup("admin");
//         }
//         return redirect()->to("users")->with("message","User updated");

//     }




//     private function getUserAccessLevels($uid)
//     {
//         $sql = "SELECT user_access_levels.ualid, user_access_levels.access_level,
//         ua.can_access, ua.can_edit,ua.uaid,
//         ifnull(ua.uid,$uid) AS uid
//         FROM user_access_levels
//         LEFT JOIN
//         (SELECT user_access.uaid, user_access.ualid, ifnull(user_access.uid,$uid) AS uid, user_access.can_access, user_access.can_edit
//         FROM user_access
//         WHERE user_access.uid=$uid
//         ) ua
//         ON user_access_levels.ualid=ua.ualid
//         WHERE ua.uid=1 OR IFNULL(ua.uid,$uid)=$uid
//         ORDER BY user_access_levels.access_level";

//         $data = $this->model->query($sql)->getResult();
//         return $data;
//     }
}
