<?php
ob_start();
header('Content-Type: text/html; charset=utf-8');
require_once 'db_connect.php';
require_once 'includes/ProxyHelper.php';
include 'includes/header.php';

$proxy = new ProxyHelper();
$html = null;
$error = null;
$attachments = [];

$app_id = $_GET['app_id'] ?? $_POST['app_id'] ?? '';
$app_id = trim(preg_replace('/\D+/', '', $app_id));

if ($app_id !== '') {
    $baseHeaders = [
        'Accept: application/json, text/plain, */*',
        'X-Requested-With: XMLHttpRequest',
        'client: bris'
    ];

    // Fetch Active Session Token (Required for API)
    $activeToken = '';
    if (isset($_GET['officeId']) && trim((string)$_GET['officeId']) !== '') {
        $activeToken = trim((string)$_GET['officeId']);
    } elseif (isset($_POST['officeId']) && trim((string)$_POST['officeId']) !== '') {
        $activeToken = trim((string)$_POST['officeId']);
    }

    if ($activeToken !== '') {
        $resolved = $proxy->getIntegerOfficeId($activeToken);
        if ($resolved !== '') {
            $activeToken = $resolved;
        }
    }

    $cookiesDir = __DIR__ . '/cookies';
    $officeTokenFile = $proxy->getActiveOfficeFile();

    if ($activeToken !== '') {
        if (!is_dir($cookiesDir)) {
            @mkdir($cookiesDir, 0755, true);
        }
        @file_put_contents($officeTokenFile, $activeToken);
    } else {
        if (file_exists($officeTokenFile)) {
            $activeToken = trim(file_get_contents($officeTokenFile));
        }
    }

    if ($activeToken === '') {
        $dashResp = $proxy->fetch('https://bdris.gov.bd/br/application', 'GET', [], false, 'https://bdris.gov.bd/');
        $dashBody = $dashResp['body'] ?? '';
        if (preg_match('/\/admin\/br\/applications\/search\?data=([A-Za-z0-9_\-]+)/i', $dashBody, $m)) {
            $activeToken = $m[1];
        }
    }
    if ($activeToken !== '') {
        $resolved = $proxy->getIntegerOfficeId($activeToken);
        if ($resolved !== '') {
            $activeToken = $resolved;
        }
        if (!is_dir($cookiesDir)) {
            @mkdir($cookiesDir, 0755, true);
        }
        @file_put_contents($officeTokenFile, $activeToken);
    }

    // If activeToken is a numeric integer, call office permission API first to register the office selection on BDRIS side
    if ($activeToken !== '' && ctype_digit($activeToken)) {
        $permUrl = 'https://bdris.gov.bd/api/office/permission?officeId=' . $activeToken;
        $proxy->fetch($permUrl, 'GET', array(), false,
                        'https://bdris.gov.bd/admin/br/applications/search', $baseHeaders);
    }

    if (!function_exists('isHtmlBody')) {
        function isHtmlBody($body) {
            $s = strtolower((string)$body);
            return strpos($s, '<html') !== false || strpos($s, '<!doctype') !== false;
        }
    }

    // Fetch Attachments
    $officeToken = $proxy->getOfficeToken($activeToken);
    $refUrl = 'https://bdris.gov.bd/admin/br/applications/search';
    if ($officeToken !== '') {
        $refUrl .= '?data=' . urlencode($officeToken);
    }
    $attResp = $proxy->fetch('https://bdris.gov.bd/api/br/application/attachments/' . urlencode($app_id), 'GET', [], false, $refUrl, $baseHeaders, 20, 2);
    
    $success = false;
    if (($attResp['status'] ?? 0) === 200 && !isHtmlBody($attResp['body'] ?? '')) {
        $j = json_decode($attResp['body'], true);
        if (isset($j['data']) && is_array($j['data'])) {
            $attachments = $j['data'];
            $success = true;
        } elseif (isset($j['attachments']) && is_array($j['attachments'])) {
            $attachments = $j['attachments'];
            $success = true;
        }
    }
    
    // Fallback: Resolve encryptedId and fetch attachments from details response
    if (!$success) {
        $encryptedId = '';
        
        // Try fast-path search by details/info first
        $fastServices = array('br', 'dr');
        foreach ($fastServices as $svcTry) {
            $refUrl = 'https://bdris.gov.bd/admin/' . $svcTry . '/applications/search';
            if ($officeToken !== '') {
                $refUrl .= '?data=' . urlencode($officeToken);
            }
            $fUrl  = 'https://bdris.gov.bd/api/' . $svcTry . '/application/details/' . urlencode($app_id);
            $fResp = $proxy->fetch($fUrl, 'GET', array(), false, $refUrl, $baseHeaders);
            if (($fResp['status'] ?? 0) === 200 && !isHtmlBody($fResp['body'] ?? '')) {
                $fj = json_decode($fResp['body'], true);
                if (is_array($fj) && !empty($fj['encryptedId'])) {
                    $encryptedId = $fj['encryptedId'];
                    break;
                }
            }
            $infoUrl = 'https://bdris.gov.bd/api/' . $svcTry . '/info/application/' . urlencode($app_id);
            $infoResp = $proxy->fetch($infoUrl, 'GET', array(), false, $refUrl, $baseHeaders);
            if (($infoResp['status'] ?? 0) === 200 && !isHtmlBody($infoResp['body'] ?? '')) {
                $ij = json_decode($infoResp['body'], true);
                if (is_array($ij) && !empty($ij['encryptedId'])) {
                    $encryptedId = $ij['encryptedId'];
                    break;
                }
            }
        }
        
        // Try search list fallback
        if ($encryptedId === '') {
            $searchSvcs = array('br', 'dr');
            foreach ($searchSvcs as $svc) {
                $listUrl = 'https://bdris.gov.bd/api/' . $svc . '/applications/search';
                $refUrl  = 'https://bdris.gov.bd/admin/' . $svc . '/applications/search';
                if ($officeToken !== '') {
                    $refUrl .= '?data=' . urlencode($officeToken);
                }
                
                $sparams = array(
                    'status'           => 'ALL',
                    'draw'             => 1,
                    'start'            => 0,
                    'length'             => 20,
                    'search[value]'    => $app_id,
                    'search[regex]'    => 'false',
                    'order[0][column]' => 1,
                    'order[0][dir]'    => 'desc',
                    'order[0][name]'   => ''
                );
                if ($activeToken !== '') {
                    $officeToken = $proxy->getOfficeToken($activeToken);
                    if ($officeToken !== '') {
                        $sparams['data'] = $officeToken;
                    } else {
                        if (ctype_digit($activeToken)) {
                            $sparams['officeId'] = $activeToken;
                        } else {
                            $sparams['data'] = $activeToken;
                        }
                    }
                }
                
                $sresp  = $proxy->fetch($listUrl, 'GET', $sparams, false, $refUrl, $baseHeaders, 20, 1, 300);
                $sbody  = (string)($sresp['body'] ?? '');
                if (($sresp['status'] ?? 0) === 200 && !isHtmlBody($sbody)) {
                    $sj   = json_decode($sbody, true);
                    $rows = isset($sj['data']) ? $sj['data'] : array();
                    if (is_array($rows)) {
                        foreach ($rows as $row) {
                            $rowId = (string)(isset($row['id']) ? $row['id'] :
                                      (isset($row['applicationId']) ? $row['applicationId'] :
                                      (isset($row['appId']) ? $row['appId'] : '')));
                            if ($rowId === (string)$app_id) {
                                $encryptedId = (string)(isset($row['encryptedId']) ? $row['encryptedId'] :
                                               (isset($row['encryptedID']) ? $row['encryptedID'] :
                                               (isset($row['encrypted_id']) ? $row['encrypted_id'] : '')));
                                break 2;
                            }
                        }
                    }
                }
            }
        }
        
        // Fetch details using encryptedId
        if ($encryptedId !== '') {
            $eUrl  = 'https://bdris.gov.bd/api/application/details?data=' . urlencode($encryptedId);
            $refUrl = 'https://bdris.gov.bd/admin/br/applications/search';
            if ($officeToken !== '') {
                $refUrl .= '?data=' . urlencode($officeToken);
            }
            $eResp = $proxy->fetch($eUrl, 'GET', array(), false, $refUrl, $baseHeaders);
            if (($eResp['status'] ?? 0) === 200 && !isHtmlBody($eResp['body'] ?? '')) {
                $dj = json_decode($eResp['body'], true);
                if (is_array($dj)) {
                    if (isset($dj['docs']) && is_array($dj['docs'])) {
                        $attachments = $dj['docs'];
                        $success = true;
                    } elseif (isset($dj['attachments']) && is_array($dj['attachments'])) {
                        $attachments = $dj['attachments'];
                        $success = true;
                    } else {
                        $error = 'এই আবেদনের কোনো ডকুমেন্ট বা সংযুক্তি পাওয়া যায়নি।';
                    }
                }
            }
        }
    }

    if (!$success && !$error) {
        $error = 'ডকুমেন্ট আনতে সমস্যা হয়েছে। সার্ভার সেশন চেক করুন।';
    }
}
?>

<div class="row justify-content-center d-print-none">
    <div class="col-md-8">
        <div class="card mt-4">
            <div class="card-header bg-secondary text-white">
                <h4 class="mb-0"><i class="fas fa-folder-open"></i> ডকুমেন্ট প্রিন্ট</h4>
            </div>
            <div class="card-body">
                <form action="" method="GET">
                    <div class="mb-3">
                        <label for="app_id" class="form-label">আবেদন নম্বর</label>
                        <input type="text" class="form-control" id="app_id" name="app_id" value="<?php echo htmlspecialchars($app_id); ?>" placeholder="আবেদন নম্বর দিন" required>
                    </div>
                    <button type="submit" class="btn btn-secondary text-white">ডকুমেন্ট খুঁজুন</button>
                    <a href="universal-dashboard.php" class="btn btn-outline-secondary">ড্যাশবোর্ডে ফিরে যান</a>
                </form>
            </div>
        </div>
    </div>
</div>

<?php if ($error): ?>
<div class="container d-print-none">
    <div class="alert alert-danger mt-3"><?php echo htmlspecialchars($error); ?></div>
</div>
<?php endif; ?>

<?php if (!empty($attachments)): ?>
<!-- Custom Print Layout for Documents -->
<div class="container mt-4 bg-white p-5 border" id="printArea">
    <style>
        @media print {
            .d-print-none { display: none !important; }
            body { background: white; }
            .container { max-width: 100%; width: 100%; padding: 0; border: none !important; }
            .card { border: none !important; }
            .card-header { display: none !important; }
        }
        .bdris-header { text-align: center; border-bottom: 2px solid #ccc; padding-bottom: 10px; margin-bottom: 20px; }
        .app-title { font-size: 24px; font-weight: bold; margin: 10px 0; }
        .doc-section { margin-top: 10px; page-break-inside: avoid; }
        .doc-img { max-width: 100%; height: auto; border: 1px solid #ddd; padding: 5px; margin-bottom: 20px; }
    </style>
    
    <div class="bdris-header">
        <div class="app-title">আবেদনের সংযুক্ত ডকুমেন্টসমূহ</div>
        <p class="mb-0">আবেদন নম্বর: <?php echo htmlspecialchars($app_id); ?></p>
    </div>

    <div class="doc-section">
        <div class="row">
        <?php foreach ($attachments as $doc): ?>
            <?php
                $rawUrl = $doc['fileUrl'] ?? ($doc['filePath'] ?? ($doc['url'] ?? ($doc['docUrl'] ?? ($doc['documentUrl'] ?? ''))));
                if (empty($rawUrl)) continue;
                $viewUrl = 'image-proxy.php?url=' . urlencode($rawUrl);
                $docName = $doc['documentName'] ?? ($doc['docName'] ?? ($doc['name'] ?? 'Document'));
            ?>
            <div class="col-12 text-center mb-5">
                <h5 class="text-muted border-bottom pb-2 mb-3"><?php echo htmlspecialchars($docName); ?></h5>
                <img src="<?php echo htmlspecialchars($viewUrl); ?>" class="doc-img" alt="Document" loading="lazy">
            </div>
        <?php endforeach; ?>
        </div>
    </div>
    
    <div class="mt-4 text-center d-print-none">
        <button class="btn btn-lg btn-secondary text-white" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
    </div>
</div>
<?php endif; ?>

<?php include 'includes/footer.php'; ?>
