<?php
namespace App\Libraries;

class Common
{

    public function make_pagenation($base_uri, $parameters, $total_rows = 0, $cur_page = 1, $per_page = 10, $num_links = 10)
    {
        if (!is_numeric($cur_page) || empty($cur_page))
            $cur_page = 1;
        if (!is_numeric($per_page) || empty($per_page))
            $per_page = 10;

        $parameters['page'] = '[page]';	// 필수 --> 이게 모든 페이지의 파라메터를 동적으로 할당하는 것이다.
        $base_uri .= make_query_string($parameters);


        if (empty($num_links))
            $num_links = 10;

        $config['base_url'] = $base_uri;
        $config['total_rows'] = $total_rows;
        $config['cur_page'] = $cur_page;
        $config['per_page'] = $per_page;
        $config['num_links'] = $num_links;	// 페이지의 갯수가 일정하게 보이도록.... 
        $config['full_tag_open'] = '<div class="pagination">';
        $config['full_tag_close'] = '</div>';

        $CI =& get_instance();
        $CI->load->library('pagination');
        $CI->pagination->initialize($config);
        $pagination = $CI->pagination->create_links();
        return $pagination;
    }

    /**
     * 워터마킹하기
     */
    public function watermarking($imagePath, $watermark_info, $wmText, $cpid, $key = '')
    {
        $uploader = new MyUpload();

        $wmImagePath = '';	// 워터마크 이미지의 경로
        $wmSpaceHeihgt = 0;	// 워터마크 이미지 하단 공백
        $wmFont = '';	// 워터마크 텍스트(글꼴)
        $wmFontSize = 13;	// 워터마크 텍스트(글꼴) 크기
        $wmTextHeight = 17;	// 워터마크 텍스트의 높이
        $wmTextColor = '#FFFFFF';	// 워터마크 텍스트의 칼라
        $wmTextAlpha = 0.5;	// 워터마크 텍스트 투명도

        try {
            $img = new \Imagick();
            if (is_string($imagePath) && is_file($imagePath)) {
                $img->readImage($imagePath);
            } elseif (is_string($imagePath) && filter_var($imagePath, FILTER_VALIDATE_URL)) {
                $headers = @get_headers($imagePath, 1) ?: [];
                $blob = @file_get_contents($imagePath);
                $contentType = '';
                if (!empty($headers)) {
                    $contentType = is_array($headers['Content-Type'] ?? null)
                        ? end($headers['Content-Type'])
                        : ($headers['Content-Type'] ?? '');
                }
                log_message('info', '[watermarking] source url={url} status={status} content_type={ctype} size={size}', [
                    'url' => $imagePath,
                    'status' => is_array($headers) && isset($headers[0]) ? $headers[0] : '(no status)',
                    'ctype' => $contentType,
                    'size' => $blob === false ? 0 : strlen($blob),
                ]);
                if ($blob === false) {
                    throw new \RuntimeException('Failed to load image from URL');
                }
                $img->readImageBlob($blob);
            } else {
                $img->readImageBlob($imagePath);
            }

            $hImg = $img->getImageHeight();
            $wImg = $img->getImageWidth();

            foreach ($watermark_info as $watermark) {
                if (strtolower($watermark['cpid']) == strtolower($cpid)) {
                    $img_w_min = intval($watermark['img_width_min']);
                    $img_w_max = intval($watermark['img_width_max']);
                    if (($img_w_min <= $wImg) and ($img_w_max >= $wImg)) {
                        $wmImagePath = $watermark['wm_img_path'];
                        $wmSpaceHeihgt = $watermark['wm_space'];
                        $wmFont = $watermark['text_font'];
                        $wmFontSize = intval($watermark['text_size']);
                        $wmTextHeight = intval($watermark['text_pixel']);
                        $wmTextColor = $watermark['text_color'];
                        $wmTextAlpha = $watermark['text_opacity'] / 100;
                        break;
                    }
                }
            }

            if (empty($wmImagePath)) {
                return;
            }

            // 워터마크 이미지 경로 처리
            if (substr($wmImagePath, 0, 1) == '/') {
                $wmImagePath = substr($wmImagePath, 1);
            }
            
            // ROOTPATH와 결합하여 절대 경로 생성 (img 폴더는 프로젝트 루트에 있음)
            $fullWmPath = ROOTPATH . $wmImagePath;
            
            if (!is_file($fullWmPath)) {
                return;
            }

            $wm = new \Imagick($fullWmPath);
            $hWm = $wm->getImageHeight();
            $wWm = $wm->getImageWidth();

            $wmImgLeft = floor(($wImg - $wWm) / 2);
            $wmImgTop = floor(($hImg - $hWm - $wmSpaceHeihgt - $wmTextHeight) / 2);	// 워터마크 이미지의 위치 top
            $wmTxtTop = $wmImgTop + $hWm + $wmSpaceHeihgt + ($wmTextHeight * 0.6);	// 워터마크 텍스트의 위치

            $img->compositeImage($wm, \Imagick::COMPOSITE_OVER, $wmImgLeft, $wmImgTop);
            $wm->destroy();

            // 워터마크 텍스트가 있는 경우에만 텍스트 그리기
            if (!empty($wmText)) {
                $draw = new \ImagickDraw();

                // 폰트 경로: img/watermark/fonts/
                if (!empty($wmFont)) {
                    $fontPath = ROOTPATH . 'img/watermark/fonts/' . $wmFont;
                    if (is_file($fontPath)) {
                        $draw->setFont($fontPath);
                    }
                }

                $draw->setFontSize($wmFontSize);
                $draw->setFillColor(new \ImagickPixel($wmTextColor));
                // $draw->setFillAlpha( $wmTextAlpha );
                $draw->setFillOpacity($wmTextAlpha);	// 워터마크 텍스트 투명도 설정
                $draw->setTextAlignment(2);		// center
                $draw->setStrokeAntialias(1);
                $draw->setStrokeWidth(1);
                $draw->setStrokeColor(new \ImagickPixel('#000000'));
                // $draw->setStrokeAlpha(0.1);
                $draw->setStrokeOpacity(0.1);
                $draw->annotation($wImg / 2, $wmTxtTop, $wmText);

                $img->drawImage($draw);
                $draw->destroy();
            }

            // $img->writeImage();

            $watermark_img = $img->getImageBlob();

            if (empty($key)) {
                throw new \RuntimeException('Empty upload key');
            }
            
            $ok = $uploader->upload_object_storage_imagick2($key, $watermark_img);
            if (!$ok) {
                log_message('error', '[watermarking] upload failed key={key} cpid={cpid}', [
                    'key' => $key,
                    'cpid' => $cpid,
                ]);
            }
            $img->destroy();

            // $object_upload = $this->upload->upload_object_storage($imagePath , $imagePath , 'data');
        } catch (\Throwable $e) {
            log_message('error', '[watermarking] Exception: {message} at {file}:{line}', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ]);
        }

    }


    /**
     * 서버상의 위치를 웹상의 위치로 변경한다...
     */
    public function realpath_to_webpath($realpath)
    {
        $arrImagePath = array(
            '/home/confirms/test-admin.confirms.co.kr/upload/',
            '/home/confirms/upload/',
            '/home/www/admin.confirms.co.kr/upload/',
            '/home/www/upload/',
            '/image/confirms_upload/',
            '/misc/image/confirms_upload/',
            '/storage/web/admin.confirms.co.kr/src/upload/',
            '/storage/web/admin.confirms.co.kr/upload/',
            $_SERVER['DOCUMENT_ROOT'] . '/upload/',
        );

        $return_path = str_replace($arrImagePath, '/upload/', $realpath);
        $return_path = str_replace(' ', '', $return_path);
        return $return_path;
    }

}