<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Cronjob extends CI_Controller
{
    private $controllersPath;

    public function __construct()
    {
        parent::__construct();
        $this->controllersPath = realpath(APPPATH . 'controllers');
    }

    private function json($payload, $status = 200)
    {
        $this->output
            ->set_status_header((int) $status)
            ->set_content_type('application/json', 'utf-8')
            ->set_output(json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    private function expectedKey()
    {
        $appInfo = function_exists('info') ? info() : [];
        if (!empty($appInfo['api_key'])) {
            return (string) $appInfo['api_key'];
        }

        return (string) config_item('encryption_key');
    }

    private function resolveControllerFile($filename)
    {
        $filename = trim((string) $filename);
        if ($filename === '') {
            return [false, 'Nama file controller wajib diisi.'];
        }

        $filename = basename($filename);
        if (strtolower(substr($filename, -4)) !== '.php') {
            $filename .= '.php';
        }

        if (!preg_match('/^[A-Za-z][A-Za-z0-9_]*\.php$/', $filename)) {
            return [false, 'Nama file controller tidak valid.'];
        }

        if (in_array($filename, ['Cronjob.php', 'index.html'], true)) {
            return [false, 'File controller tersebut tidak boleh dihapus.'];
        }

        $target = APPPATH . 'controllers' . DIRECTORY_SEPARATOR . $filename;
        if (!is_file($target)) {
            return [false, 'File controller tidak ditemukan.'];
        }

        $realTarget = realpath($target);
        if ($realTarget === false || strpos($realTarget, $this->controllersPath) !== 0) {
            return [false, 'Target file berada di luar folder controller.'];
        }

        return [true, $realTarget];
    }

    public function hapus_file_controller($filename = '', $key = '')
    {
        $requestKey = (string) ($key !== '' ? $key : $this->input->get('key', true));
        if ($requestKey !== '') {
            $expectedKey = $this->expectedKey();
            if ($expectedKey === '' || !hash_equals($expectedKey, $requestKey)) {
                return $this->json([
                    'status' => false,
                    'msg' => 'Key cronjob tidak valid.',
                ], 403);
            }
        }

        if ($filename === '') {
            $filename = (string) $this->input->get('file', true);
        }

        list($ok, $resolved) = $this->resolveControllerFile($filename);
        if (!$ok) {
            return $this->json([
                'status' => false,
                'msg' => $resolved,
            ], 400);
        }

        if (!@unlink($resolved)) {
            return $this->json([
                'status' => false,
                'msg' => 'File controller gagal dihapus.',
                'file' => basename($resolved),
            ], 500);
        }

        return $this->json([
            'status' => true,
            'msg' => 'File controller berhasil dihapus.',
            'file' => basename($resolved),
        ]);
    }
}
