<?php

namespace App\Controllers\Panel\App\Settings\Updates;

use App\Controllers\Panel\BC;
use CodeIgniter\API\ResponseTrait;
use ZipArchive;

class Patch extends BC
{
    use ResponseTrait;
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if (ENVIRONMENT != 'development') return $this->fail(['message' => "Aktifkan Mode Development Terlebih Dahulu!"]);
        global $patchPath;
        global $backupPath;
        $allowed_mime =  ['application/x-zip-compressed', "application/zip", "application/x-rar-compressed", "application/octet-stream", "multipart/x-zip"];
        $pf = $this->request->getFile('file');
        if (!$pf->isValid()) return $this->fail(['message' => "File Tidak Valid!"]);
        if (!in_array($pf->getMimeType(), $allowed_mime)) return $this->fail(['message' => "Format Tidak Diizinkan", 'csrf' => ['name' => csrf_token(), 'value' => csrf_hash()]]);
        $patchPath = WRITEPATH . "patch/main";
        $backupPath = WRITEPATH . "patch/backup";
        @mkdir(WRITEPATH . "patch");
        @mkdir($patchPath);
        @mkdir($backupPath);
        helper('Panel/utils');

        try {
            $za = new ZipArchive();
            $filePath = $pf->getPath() . "/" . $pf->getFilename();
            $za->open($filePath);
            $za->extractTo($patchPath);
        } catch (\Throwable $e) {
            return $this->fail(['message' => $e->getMessage()]);
        }
        if (file_exists("$patchPath/init.php")) {
            include "$patchPath/init.php";
            try {
                if (function_exists('patchInit')) patchInit();
            } catch (\Throwable $th) {
                rrename($backupPath, ROOTPATH);
                return $this->fail(['message' => $th->getMessage()]);
            }
        }
        if (file_exists(WRITEPATH . "patch")) {
            rrmdir(WRITEPATH . "patch");
        }
        setLog("Memasang update " . APP_VERSION_NAME);
        return $this->respond(['message' => "Patch berhasil dipasang"]);
    }
}
