<?php
if (!defined("ROOT_PATH")) {
    header("HTTP/1.1 403 Forbidden");
    exit;
}

class pjAdminProfile extends pjAdmin
{
    public function beforeFilter()
    {
        $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
        if (in_array($action, array('pjActionDeleteLogo', 'pjActionDeleteEmailLogo'), true)) {
            pjAppController::beforeFilter();
            if (self::isPost()) {
                pjAppController::validateCsrfToken();
            }
            return true;
        }

        return parent::beforeFilter();
    }

    public function pjActionIndex()
    {
        $this->checkLogin();

        if (isset($_REQUEST['profile_post'])) {
            $this->ensureInvoiceConfigRow();

            $data = array();
            $logo = $this->handleLogoUpload('y_logo', array('png', 'gif', 'jpg', 'jpeg', 'jpe', 'jfif', 'jif', 'jfi', 'webp', 'svg'), true);
            if ($logo !== null) {
                $data['y_logo'] = $logo;
            }

            $emailLogo = $this->handleLogoUpload('y_email_logo', array('png', 'jpg', 'jpeg', 'jpe'), false);
            if ($emailLogo !== null) {
                $data['y_email_logo'] = $emailLogo;
            }

            if (isset($_REQUEST['i18n']) && is_array($_REQUEST['i18n'])) {
                pjMultiLangModel::factory()->updateMultiLang($_REQUEST['i18n'], 1, 'pjInvoiceConfig');

                $defaultLocaleId = $this->getDefaultLocaleId();
                if ($defaultLocaleId && isset($_REQUEST['i18n'][$defaultLocaleId])) {
                    $default = $_REQUEST['i18n'][$defaultLocaleId];
                    foreach (array('y_phone', 'y_email', 'y_url', 'y_zip', 'y_vat_number', 'y_coc_number', 'y_bank_iban', 'y_bank_name') as $field) {
                        if (isset($default[$field])) {
                            $data[$field] = $default[$field];
                        }
                    }
                }
            }

            if (!empty($data)) {
                pjInvoiceConfigModel::factory()->set('id', 1)->modify($data);
            }

            pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminProfile&action=pjActionIndex&err=AP01");
        }

        $this->ensureInvoiceConfigRow();

        $arr = pjInvoiceConfigModel::factory()->find(1)->getData();
        if (!empty($arr)) {
            $arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjInvoiceConfig');
        }

        $locale_arr = pjLocaleModel::factory()
            ->select('t1.*, t2.file')
            ->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left outer')
            ->where('t2.file IS NOT NULL')
            ->orderBy('t1.sort ASC')
            ->findAll()
            ->getData();

        $lp_arr = array();
        foreach ($locale_arr as $item) {
            $lp_arr[$item['id'] . "_"] = $item['file'];
        }

        $this
            ->set('arr', $arr)
            ->set('lp_arr', $locale_arr)
            ->set('locale_str', pjAppController::jsonEncode($lp_arr))
            ->set('is_flag_ready', $this->requestAction(array('controller' => 'pjLocale', 'action' => 'pjActionIsFlagReady'), array('return')))
            ->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/')
            ->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/')
            ->appendJs('pjAdminProfile.js')
            ->appendJs('index.php?controller=pjBase&action=pjActionMessages', PJ_INSTALL_URL, true);
    }

    public function pjActionDeleteLogo()
    {
        $this->deleteLogoField('y_logo');
    }

    public function pjActionDeleteEmailLogo()
    {
        $this->deleteLogoField('y_email_logo');
    }

    private function ensureInvoiceConfigRow()
    {
        $arr = pjInvoiceConfigModel::factory()->find(1)->getData();
        if (empty($arr)) {
            pjInvoiceConfigModel::factory()
                ->setAttributes(array(
                    'id' => 1,
                    'invoice_number' => '1',
                    'invoice_number_digits' => 5,
                    'invoice_number_reset_yearly' => 0,
                    'si_include' => 0,
                    'o_use_qty_unit_price' => 1
                ))
                ->insert();
        }
    }

    private function handleLogoUpload($field, array $allowedExt, $allowSvg)
    {
        if (!isset($_FILES[$field]) || empty($_FILES[$field]['tmp_name'])) {
            return null;
        }

        $dir = PJ_INSTALL_PATH . 'app/web/invoices/';
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }

        $file = $_FILES[$field];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt, true)) {
            return null;
        }

        $hash = md5(uniqid($field, true));
        $relative = 'app/web/invoices/' . $hash . '.' . $ext;
        $destination = PJ_INSTALL_PATH . $relative;

        if ($allowSvg && $ext === 'svg') {
            return move_uploaded_file($file['tmp_name'], $destination) ? $relative : null;
        }

        if (!class_exists('pjImage')) {
            $componentFile = PJ_COMPONENTS_PATH . 'pjImage.component.php';
            if (is_file($componentFile)) {
                require_once $componentFile;
            }
        }

        if (class_exists('pjImage')) {
            $pjImage = new pjImage();
            $pjImage
                ->setAllowedExt($allowedExt)
                ->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/webp'));

            if ($pjImage->load($file)) {
                $relative = 'app/web/invoices/' . $hash . '.' . $pjImage->getExtension();
                $destination = PJ_INSTALL_PATH . $relative;
                if ($pjImage->save($destination)) {
                    return $relative;
                }
            }
        }

        return move_uploaded_file($file['tmp_name'], $destination) ? $relative : null;
    }

    private function deleteLogoField($field)
    {
        $this->setAjax(true);
        if (!$this->isXHR() || !$this->isLoged()) {
            pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'You are not logged in.'));
        }

        $arr = pjInvoiceConfigModel::factory()->find(1)->getData();
        if (!empty($arr) && !empty($arr[$field])) {
            $file = PJ_INSTALL_PATH . $arr[$field];
            if (is_file($file)) {
                @unlink($file);
            }
            pjInvoiceConfigModel::factory()->set('id', 1)->modify(array($field => ':NULL'));
            pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Logo removed.'));
        }

        pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Logo not found.'));
    }

    private function getDefaultLocaleId()
    {
        $locales = pjLocaleModel::factory()->where('t1.is_default', 1)->limit(1)->findAll()->getData();
        return !empty($locales) ? (int) $locales[0]['id'] : 1;
    }
}
?>
