<?php

namespace App\Helpers;

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\TemplateProcessor;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Dompdf\Dompdf;
use Dompdf\Options;

class DocxHelper
{
    /**
     * Edit prefix dalam file DOCX dan konversi menjadi PDF.
     *
     * @param string $filePath Path file DOCX asli.
     * @param array $prefixes Array pasangan placeholder dan value untuk mengganti teks dalam DOCX.
     * @param string $outputPdfPath Path output untuk menyimpan PDF.
     *                       Contoh: ['PREFIX_PLACEHOLDER_1' => 'NewPrefix1', ...]
     * @return string Path dari file PDF yang dihasilkan.
     *
     */
    public static function parsePrefix($filePath, array $prefixes)
    {
        $templateProcessor = new TemplateProcessor($filePath);
   
        foreach ($prefixes as $placeholder => $value) {
            if($value[1] == 'TEXT'){
                $templateProcessor->setValue($placeholder, $value[0]);
                
            }
            
            if($value[1] == 'IMAGE'){
                if (file_exists(storage_path('app/signature/'.$value[0]))) {
                    $templateProcessor->setImageValue(str_replace(['${', '}'], '', $placeholder), array('path' => storage_path('app/signature/'.$value[0]), 'width' => 50, 'height' => 50, 'ratio' => true));
                }
            }
            
        }

        $docx_temp_name = pathinfo($filePath, PATHINFO_FILENAME) . '.docx'; // Nama unik untuk file sementara

        if (!file_exists(storage_path('app/public/uploads/temp_docx'))) {
            mkdir(storage_path('app/public/uploads/temp_docx'), 0777, true);
        }

        $editedDocxPath = storage_path('app/public/uploads/temp_docx/' . $docx_temp_name);

        $templateProcessor->saveAs($editedDocxPath);
        return $editedDocxPath;
    }



    /**
     * Konversi file DOCX yang telah diedit prefix menjadi PDF.
     *
     * @param array $prefixes Array pasangan placeholder dan value untuk mengganti teks dalam DOCX.
     * @param string $docx_path Path file DOCX yang akan diconvert.
     * @param string $pdf_path Path output untuk menyimpan PDF.
     * @return string Path file PDF yang dihasilkan.
     */
    public static function ConvertPDFWithPrefix($prefixes,$docx_path,$pdf_path)
    {
        $inputFilePath = DocxHelper::parsePrefix($docx_path, $prefixes);
        $libreOfficePath = env('LIBREOFFICE_PATH');

        $command = '"'.$libreOfficePath.'" --headless --convert-to pdf "'.$inputFilePath.'" --outdir "'.dirname($pdf_path).'"';
        $output = [];
        $returnVar = 0;
        exec($command, $output, $returnVar);

        if ($returnVar !== 0) {
            dd('failed to convert PDF File. Return Code: '.$returnVar);
        } else {
            $pathInfo = pathinfo($inputFilePath);
            $newExtension = 'pdf';
            $outputFilePath = dirname($pdf_path) . DIRECTORY_SEPARATOR . $pathInfo['filename'] . '.' . $newExtension;
        }

       return $outputFilePath;
    }


    
    /**
     * Inserts a new record into the MS_PREFIX_DOCUMENT table with the provided details.
     *
     * @param int $documentId The ID of the document.
     * @param string $prefixKey The prefix key associated with the document.
     * @param string $tableName The name of the table where the prefix is applied.
     * @param string $columnName The name of the column where the prefix is applied.
     * @param string $createdBy The identifier of the user who created the record.
     * @param string $updatedBy The identifier of the user who last updated the record.
     * @return bool Returns true if the record was successfully inserted, false otherwise.
     */
    public static function createPrefixDocument($documentId, $prefixKey, $tableName, $columnName, $createdBy, $updatedBy) {
        $result = DB::table('MS_PREFIX_DOCUMENT')->insert([
            'DOCUMENT_ID' => $documentId,
            'PREFIX_KEY' => $prefixKey,
            'TABLE_NAME' => $tableName,
            'COLUMN_NAME' => $columnName,
            'CREATED_BY' => $createdBy,
            'UPDATED_BY' => $updatedBy,
            'CREATED_AT' => now(),
            'UPDATED_AT' => now()
        ]);
        return (bool) $result;
    }


    /**
     * Retrieves the prefix mappings for a given document ID from the MS_PREFIX_DOCUMENT table.
     * 
     * This function queries the database to obtain prefix mappings associated with the provided
     * document ID. It then retrieves the corresponding values from the specified tables and columns
     * for each mapping. If a value is not found, 'N/A' is used as a default.
     * buatkan sebuah view yang telah di join table untuk menjalankan fungsi ini.
     * @param string $documentId The ID of the document for which to retrieve prefix mappings.
     * @return array An associative array of prefix keys and their corresponding values.
     */
    public static function getDocumentPrefixWithData($documentId,$dataId) {
      
        $prefixes = [];
        $mappings = DB::table('MS_PREFIX_DOCUMENT')
            ->where('DOCUMENT_ID', $documentId)
            ->get();
        foreach ($mappings as $mapping) {
            $value = DB::table($mapping->table_name)
                ->where('ID', $dataId) 
                ->value($mapping->column_name);

            $prefixes[$mapping->prefix_key] = array($value !== null ? $value : '', $mapping->type) ;
        }

        return $prefixes;
    }




  
}
