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

class DownloadMergePDF extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper(['url', 'form', 'download','date']);
        $this->load->library(['session', 'upload','zip']);
        $this->load->model('Company_model');
    } 

    /**
     * Download all documents under a specific Month of a given Year and Authority
     * Example: /DocumentTree/download_month/3/2025/January
     */
    public function download_month($type_id, $company_id, $year, $month) {
        /*echo 'in month'; */
        $monthNumber = get_month_number($month);
        /*echo $monthNumber;  // Outputs: 03
		exit;*/
        $docs = $this->Company_model->getDocumentsZip($type_id, $company_id, $year, $monthNumber);
		log_message('debug', "October PDF: ". print_r($docs, true));
        $this->_create_zip($docs, "Authority_{$type_id}_{$year}_{$month}",'month');
    }

    private function _create_zip($docs, $zipName = 'Documents', $level = 'type')
    {
        $this->load->library('PdfMergerLib');
        $this->load->library('zip');
        $this->zip->clear_data();

        $baseDir = FCPATH . 'temp_zip/';
        $outputDir = FCPATH . 'output/';

        // 🔹 Clean old temp folder if exists
        if (is_dir($baseDir)) {
            $this->delete_directory($baseDir);
        }
        mkdir($baseDir, 0777, true);
        if (!is_dir($outputDir)) mkdir($outputDir, 0777, true);

        // 🔹 Group documents by authority → year → month
        $grouped = [];
        foreach ($docs as $item) {
            $grouped[$item->authority][$item->year][$item->month][] = [
                'file_name' => $item->file_name,
                'doc_name'  => $item->doc_name
            ];
        }

        // 🔹 Loop through authorities
        foreach ($grouped as $authority => $years) {

            if ($level == 'type') {
                $zipFolderPath = "$baseDir$authority/";
                $zipFileName = "{$authority}.zip";
            }

            foreach ($years as $year => $months) {

                if ($level == 'year') {
                    $zipFolderPath = "$baseDir{$authority}_{$year}/";
                    $zipFileName = "{$authority}_{$year}.zip";
                }

                foreach ($months as $month => $docsList) {

                    if ($level == 'type') {
                        $monthDir = "$zipFolderPath$year/$month/";
                    } elseif ($level == 'year') {
                        $monthDir = "$zipFolderPath$month/";
                    } else {
                        $monthDir = "$baseDir$authority/$year/$month/";
                    }

                    if (!is_dir($monthDir)) {
                        mkdir($monthDir, 0777, true);
                    }

                    // 🔹 Collect PDF file paths
                    $pdfFiles = [];
                    foreach ($docsList as $doc) {
                        $filePath = FCPATH . 'uploads/documents/' . $doc['file_name'];
                        if (file_exists($filePath)) {
                            $pdfFiles[] = $filePath;
                        } else {
                            log_message('error', "Missing PDF: {$filePath}");
                        }
                    }

                    $name = preg_replace('/[^A-Za-z0-9]+/', '_', strtolower($authority));
                    $mergedName = "{$name}_{$year}_{$month}.pdf";
                    $mergedPdfPath = $monthDir . $mergedName;

                    // 🔹 Merge PDFs using PDFMergerLib
                    if (!empty($pdfFiles)) {
                        $merged = $this->pdfmergerlib->merge($pdfFiles, $mergedPdfPath);
                        if (!$merged) {
                            log_message('error', "Failed to merge PDFs for {$authority} - {$year} - {$month}");
                            continue;
                        }
                    } else {
                        log_message('error', "No valid PDFs to merge for {$authority} - {$year} - {$month}");
                        continue;
                    }

                    // 🔹 If this is month-level → directly download the merged file
                    if ($level == 'month') {
                        header('Content-Type: application/pdf');
                        header('Content-Disposition: attachment; filename="' . basename($mergedPdfPath) . '"');
                        readfile($mergedPdfPath);
                        exit;
                    }
                }

                // For year-level, zip each year separately
                if ($level == 'year') {
                    $this->zip->clear_data();
                    $this->zip->read_dir($zipFolderPath, FALSE);
                    $zipFilePath = $outputDir . $zipFileName;
                    $this->zip->archive($zipFilePath);
                    $this->zip->download($zipFileName);
                }
            }

            // For type-level, zip after all years processed
            if ($level == 'type') {
                $this->zip->clear_data();
                $this->zip->read_dir($zipFolderPath, FALSE);
                $zipFilePath = $outputDir . $zipFileName;
                $this->zip->archive($zipFilePath);
                $this->zip->download($zipFileName);
            }
        }
    }

    /**
	 * Helper function to recursively delete old temp folder
	 */
	private function delete_directory($dir)
	{
		if (!file_exists($dir)) return true;
		if (!is_dir($dir)) return unlink($dir);
		foreach (scandir($dir) as $item) {
			if ($item == '.' || $item == '..') continue;
			$this->delete_directory($dir . DIRECTORY_SEPARATOR . $item);
		}
		return rmdir($dir);
	}

}