<?php

namespace App\Controllers\Pages;

use App\Controllers\BaseController;

class SuperuserController extends BaseController
{

    public function __construct()
    {
        helper(['url', 'form', 'text']);
    }

    public function index()
    {
        $config = require APPPATH . 'Views/shared/config.php';
        return view('superuser/index', ['roleConfig' => $config['superuser']]);
    }

    public function users()
    {
        $config = require APPPATH . 'Views/shared/config.php';
        return view('superuser/users', ['roleConfig' => $config['superuser']]);
    }

    public function validatePage()
    {
        $config = require APPPATH . 'Views/shared/config.php';
        return view('superuser/validate', ['roleConfig' => $config['superuser']]);
    }

    public function pdfBatch()
    {
        $config = require APPPATH . 'Views/shared/config.php';
        return view('superuser/pdf_batch', ['roleConfig' => $config['superuser']]);
    }

    public function processPdfBatch()
    {
        $input = $this->request->getJSON(true);
        $accessNumbers = $input['accessNumbers'] ?? [];
        
        if (empty($accessNumbers)) {
            return $this->response->setStatusCode(400)->setJSON([
                'success' => false,
                'message' => 'No access numbers provided'
            ]);
        }

        $results = [];
        $db = \Config\Database::connect();

        foreach ($accessNumbers as $accessnumber) {
            $accessnumber = trim($accessnumber);
            if (empty($accessnumber)) {
                continue;
            }

            try {
                // Check if request exists
                $sql = "SELECT ACCESSNUMBER, REPORT_LANG FROM GDC_CMOD.dbo.CM_REQUESTS WHERE ACCESSNUMBER = ?";
                $row = $db->query($sql, [$accessnumber])->getRowArray();

                if (!$row) {
                    $results[] = [
                        'accessnumber' => $accessnumber,
                        'success' => false,
                        'error' => 'Access number not found',
                        'lang' => null,
                        'isRegen' => false
                    ];
                    continue;
                }

                // Call report/{accessnumber}/pdf endpoint internally
                $response = $this->callReportPdfEndpoint($accessnumber);
                
                if ($response['success']) {
                    $results[] = [
                        'accessnumber' => $accessnumber,
                        'success' => true,
                        'error' => null,
                        'lang' => $response['lang'] ?? 'Unknown',
                        'isRegen' => $response['isRegen'] ?? false
                    ];
                } else {
                    $results[] = [
                        'accessnumber' => $accessnumber,
                        'success' => false,
                        'error' => $response['error'] ?? 'PDF generation failed',
                        'lang' => null,
                        'isRegen' => false
                    ];
                }
            } catch (\Throwable $e) {
                $results[] = [
                    'accessnumber' => $accessnumber,
                    'success' => false,
                    'error' => $e->getMessage(),
                    'lang' => null,
                    'isRegen' => false
                ];
            }
        }

        return $this->response->setJSON([
            'success' => true,
            'results' => $results,
            'total' => count($results),
            'successful' => count(array_filter($results, fn($r) => $r['success'])),
            'failed' => count(array_filter($results, fn($r) => !$r['success']))
        ]);
    }

    private function callReportPdfEndpoint($accessnumber)
    {
        $db = \Config\Database::connect();
        
        // Get language preference
        $sql = "SELECT REPORT_LANG FROM GDC_CMOD.dbo.CM_REQUESTS WHERE ACCESSNUMBER = ?";
        $row = $db->query($sql, [$accessnumber])->getRowArray();
        $eng = (int) ($row['REPORT_LANG'] ?? 0);
        
        // Load ReportController and call generatePdf
        $reportController = new \App\Controllers\ReportController();
        
        try {
            // Temporarily override the response to capture it
            $response = $reportController->generatePdf($accessnumber);
            
            // Parse the response
            $body = $response->getBody();
            $data = json_decode($body, true);
            
            if ($data && isset($data['success']) && $data['success']) {
                return [
                    'success' => true,
                    'lang' => $data['lang'] ?? ($eng == 1 ? 'English' : 'Indonesian'),
                    'isRegen' => $data['isRegen'] ?? false
                ];
            }
            
            return [
                'success' => false,
                'error' => $data['error'] ?? 'Unknown error'
            ];
        } catch (\Throwable $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

}
