<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Libraries\AppUpdater;

class Updater extends BaseController
{
    protected $updater;

    public function __construct()
    {
        $this->updater = new AppUpdater();
    }

    private function checkAccess()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }

        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin'])) {
            return redirect()->to('/dashboard')->with('error', 'Anda tidak memiliki hak akses untuk memperbarui aplikasi.');
        }

        return null;
    }

    /**
     * Halaman Utama Updater
     */
    public function index()
    {
        if ($redirect = $this->checkAccess()) return $redirect;

        $current = $this->updater->getCurrentVersion();
        
        $data = [
            'title'          => 'Update Aplikasi',
            'currentVersion' => $current,
        ];

        return view('updater/index', $data);
    }

    /**
     * POST Endpoint: Menjalankan proses offline update melalui file ZIP yang diunggah
     */
    public function offlineUpdate()
    {
        if ($redirect = $this->checkAccess()) return $redirect;

        $rules = [
            'zip_file' => 'uploaded[zip_file]|ext_in[zip_file,zip]|max_size[zip_file,153600]' // Max 150MB
        ];

        if (!$this->validate($rules)) {
            $errors = implode(', ', $this->validator->getErrors());
            return redirect()->back()->with('error', 'Gagal validasi file ZIP: ' . $errors);
        }

        $file = $this->request->getFile('zip_file');
        if ($file->isValid() && !$file->hasMoved()) {
            $tempPath = WRITEPATH . 'uploads/temp/';
            if (!is_dir($tempPath)) {
                mkdir($tempPath, 0777, true);
            }

            $newName = 'temp_offline_update.zip';
            $file->move($tempPath, $newName, true);
            $fullFilePath = $tempPath . $newName;

            $manualVersion = trim($this->request->getPost('manual_version') ?? '');

            // Run offline update
            $result = $this->updater->runOfflineUpdate($fullFilePath, $manualVersion);

            if ($result['status'] === 'success') {
                return redirect()->to('/updater')->with('success', $result['message']);
            } else {
                return redirect()->back()->with('error', $result['message']);
            }
        }

        return redirect()->back()->with('error', 'Gagal mengunggah file ZIP.');
    }
}
