<?php

require_once("../../config/session.php");
require_once("../../config/function.php");

error_reporting(0);

$site_data = site_data();

if (
    !isset($_SESSION['is_login'], $_SESSION['login_token']) ||
    $_SESSION['is_login'] !== true ||
    empty($_SESSION['login_token'])
) {
    session_destroy();
    redirect('../../logout', 0);
    exit;
}

$user_data = user_data($_SESSION['login_token']);

if (
    empty($user_data['user_id']) ||
    empty($user_data['login_token']) ||
    !hash_equals((string)$_SESSION['login_token'], (string)$user_data['login_token'])
) {
    session_destroy();
    redirect('../../logout', 0);
    exit;
}

if (
    $user_data['usertype'] === 'White Label' &&
    (
        (int)$user_data['site_id'] === (int)$site_data['site_id'] ||
        (int)$user_data['user_id'] !== (int)$site_data['user_id']
    )
) {
    session_destroy();
    redirect('../../logout', 0);
    exit;
}

$connection = mysqli_connect('localhost', $dbname, $dbpass, $dbname);

if (!$connection) {
    http_response_code(500);
    exit('Database connection failed.');
}

mysqli_set_charset($connection, 'utf8mb4');

$parameterName = 'UB8RM0X3pIs0peiXzhJkREd7YHrSLG0oqTwRYfqH0q';
$encryptedSearchId = isset($_GET[$parameterName])
    ? trim((string)$_GET[$parameterName])
    : '';

if ($encryptedSearchId === '') {
    http_response_code(400);
    exit('Invalid request.');
}

$recordId = decryptSearchId($encryptedSearchId);

if ($recordId === false || !is_numeric($recordId) || (int)$recordId <= 0) {
    http_response_code(403);
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Invalid Print Link</title>
    </head>
    <body>
        <script>
            alert('Invalid or modified print link.');
            setTimeout(function () {
                window.close();
                setTimeout(function () {
                    window.location.href = '../printRecord';
                }, 500);
            }, 300);
        </script>
    </body>
    </html>
    <?php
    exit;
}

$recordId = (int)$recordId;
$stmt = mysqli_prepare($connection, 'SELECT * FROM printRecords WHERE id = ? LIMIT 1');

if (!$stmt) {
    http_response_code(500);
    exit('Database query preparation failed.');
}

mysqli_stmt_bind_param($stmt, 'i', $recordId);

if (!mysqli_stmt_execute($stmt)) {
    mysqli_stmt_close($stmt);
    http_response_code(500);
    exit('Database query failed.');
}

$result = mysqli_stmt_get_result($stmt);
$record = $result ? mysqli_fetch_assoc($result) : null;
mysqli_stmt_close($stmt);

if (!$record) {
    http_response_code(404);
    exit('Print record not found.');
}

if (
    isset($record['service']) &&
    !in_array($record['service'], array('Aadhar Manual', 'Aadhar_FingerPrint', 'AADHAR_OTP'), true)
) {
    http_response_code(403);
    exit('Invalid service record.');
}

if (isset($record['status']) && $record['status'] !== 'Success') {
    http_response_code(403);
    exit('Print record is not completed.');
}

$decodedPrintData = base64_decode((string)($record['printData'] ?? ''), true);

if ($decodedPrintData === false) {
    http_response_code(500);
    exit('Invalid encoded print data.');
}

$printData = json_decode($decodedPrintData, true);

if (!is_array($printData)) {
    http_response_code(500);
    exit('Invalid print data.');
}

function addSpaceAfter4Digits($number)
{
    $number = preg_replace('/\s+/', '', (string)$number);
    return trim(chunk_split($number, 4, ' '));
}

function pageEscape($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function xmlSafe($value)
{
    return htmlspecialchars(trim((string)$value), ENT_QUOTES | ENT_XML1, 'UTF-8');
}

function safeImageSource($value)
{
    $value = trim((string)$value);

    if ($value === '') {
        return '';
    }

    if (preg_match('#^data:image/(?:jpeg|jpg|png|webp);base64,[A-Za-z0-9+/=\r\n]+$#i', $value)) {
        return $value;
    }

    if (preg_match('#^https?://#i', $value) || strpos($value, '/') === 0 || strpos($value, './') === 0 || strpos($value, '../') === 0) {
        return $value;
    }

    return '';
}

$b = array(
    'aadharno'        => (string)($printData['aadharno'] ?? ''),
    'name'             => (string)($printData['name'] ?? ''),
    'fathername'       => (string)($printData['fathername'] ?? ''),
    'dobadhar'         => (string)($printData['dobadhar'] ?? ''),
    'birthtithilocal'  => (string)($printData['birthtithilocal'] ?? ''),
    'gender'           => (string)($printData['gender'] ?? ''),
    'genderlocal'      => (string)($printData['genderlocal'] ?? ''),
    'address'          => (string)($printData['address'] ?? ''),
    'namelocal'        => (string)($printData['namelocal'] ?? ''),
    'addresslocal'     => (string)($printData['addresslocal'] ?? ''),
    'imgdata'          => (string)($printData['imgdata'] ?? ''),
    'filetype'         => (string)($printData['filetype'] ?? ''),
    'imgcode'          => (string)($printData['imgcode'] ?? ''),
    'vtcandpost'       => (string)($printData['vtcandpost'] ?? ''),
    'pincode'          => (string)($printData['pincode'] ?? ''),
    'srno'             => (string)($printData['srno'] ?? '')
);

$aadhaarDigits = preg_replace('/\D+/', '', $b['aadharno']);

if (strlen($aadhaarDigits) !== 12) {
    http_response_code(500);
    exit('Invalid Aadhaar data.');
}

$b['aadharno'] = $aadhaarDigits;
$formattedAadhaarNumber = addSpaceAfter4Digits($aadhaarDigits);

if (strcasecmp($b['filetype'], 'SSO') === 0 && $b['imgcode'] !== '') {
    $cleanImageCode = preg_replace('/[^A-Za-z0-9+\/=]/', '', $b['imgcode']);
    $photoSource = 'data:image/jpeg;base64,' . $cleanImageCode;
} else {
    $photoSource = safeImageSource($b['imgdata']);
}

$sex = strtoupper(trim($b['gender'])) === 'MALE' ? 'M' : 'F';
$qrReference = date('YmdHis') . random_int(1000, 9999);
$codeContents = '<?xml version="1.0" encoding="UTF-8"?>'
    . '<PrintLetterBarcodeData '
    . 'uid="' . xmlSafe($b['aadharno']) . '" '
    . 'name="' . xmlSafe($b['name']) . '" '
    . 'gender="' . xmlSafe($sex) . '" '
    . 'dob="' . xmlSafe($b['dobadhar']) . '" '
    . 'co="' . xmlSafe($b['fathername']) . '" '
    . 'po="' . xmlSafe($b['vtcandpost']) . '" '
    . 'address="' . xmlSafe($b['address']) . '" '
    . 'pc="' . xmlSafe($b['pincode']) . '" '
    . 'ref="' . xmlSafe($qrReference) . '"'
    . '/>';

$qrUrl = 'https://api.qrserver.com/v1/create-qr-code/'
    . '?size=300x300&ecc=L&margin=2&format=png&data=' . rawurlencode($codeContents);

$randomNumber = str_pad((string)random_int(1, 99999999999999), 14, '0', STR_PAD_LEFT);
$formattedAadhaar = 'EAadhaar_'
    . $randomNumber
    . date('YmdHis')
    . '_'
    . date('dmYHis');
?>
<!DOCTYPE html>

 <title><?= pageEscape($formattedAadhaar) ?></title>
        <meta charset="utf-8">
        <link rel="icon" href="<?= pageEscape($site_data['logo'] ?? '') ?>" type="image/*" sizes="16x16">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> 
        <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
        <script>
        window.onload = function() { window.print();  }
        </script>
        
    </head>

    <style type="text/css">
           body{
      font-family: 'Roboto', sans-serif;
    }
    h1, h2, h3, h4{
      font-family: 'Open Sans', sans-serif;
    }
    .clr{
      clear: both;
    }
    .pdf{
      /*width: 650px;*/
      width: 680px;
      height: 845px;
      border: solid 2px;
      margin: 10% auto;
    }
    .left{
      width: 48.7%;
      float: left;
      border-right: solid 2px;
      height: 100%;
    }
    .right{
      width: 48.8%;
      float: left;
      border-left: solid 2px;
      height: 100%;
    }
    .cntr{
      float: left;
      
    }
    img{
      width: 100%;
    }
    .img4{
      /*
      border-bottom: solid #e70000;
      */
    }
    p{
      font-size: 12px;
      text-align: center;
      margin: 0;
    }
    .rtt{
      float: left;
      width: 15%;
    }
    .rtt_rt{
      float: left;
        width: 146%;
        padding-left: 18%;
        margin-top: -10%;
    }
    .rtt p, .brcd p{
      transform: rotate(90deg);
      margin-top: 25px;
      font-size: 9px;
      font-weight: bold;
    }
    ul li{
      font-size: 10px;
      list-style: none;
      line-height: 11px;
    }
    ul{
      padding: 0;
      margin-top: 5px;
    }
    .vld{
      float: left;
      width: 52%;
      text-align: right;
    }
    .brcd{
      float: left;
      width: 26%;
      background: url("images/q.jpg") no-repeat;
      background-size: 50px;
      margin-top: 100px;
      padding-left: 15px;
      background-position-x: center;
    }
    .brcd.print {
        display: list-item;
        list-style-image: url("images/q.jpg");
        list-style-position: inside;
    }
    .prnt{
        position: absolute;
        margin-top: -60px;
    }
    .vld img{
      width: 153px;
    padding-top: 32px;
    }
    h4 span, h2 span{
      color: #e70000;
    }
    h4{
      font-size: 14px;
      text-align: center;
      padding-top: 20px;
      margin: 0;
    }
    h3{
      margin: 0 0 4px;
      text-align: center;
    }
    h3 span{
      border-bottom: solid 0;
    }
    h2{
      text-align: center;
      font-size: 18px;
      letter-spacing: 1px;
      font-weight: 500;
      margin: 0;
      border-bottom: solid #e70000;
    }
    .img2{
     /*
      border-top: dashed 1px;
      */
      margin-top: 5px;
      padding: 5px 0;
    }

    img.cut-008 {
    height: 8px;
}

    .a_lft{
    width: 20%;
    float: left;
    padding: 0 15px;
    padding-left: 24px;
    }
    .a_rgt{
      width: 68%;
      float: left;
    }
    .a_rgt ul{
      margin-top: 0;
      margin-bottom: 0;
    }
    .a_rgt img{
        width: 75px;
        float: right;
        position: absolute;
        margin: 25px 140px 0;
    }
    .adhr h2{
      font-size: 14px;
      border-top: solid #e70000 2px;
      border-bottom: 0;
    }
    .adhr p{
      font-size: 10px;
    }
    .adhr h3{
      font-size: 16px;
    }
    .img6{
      margin-top: 0px;
    height: 23px;
    }
    .adhr .brcd {
      width: 5%;
    }
    .adhr .brcd p {
        font-size: 6px;
        margin-top: 10px;
    }
    .b_rgt{
      width: 36%;
      float: right;
    }
    .b_lft{
      width: 64%;
      float: left;
    max-height: 112px;
    margin-top: 0%;
    }
    .adhr2 ul li{
      font-size: 10px;
      line-height: 10px;
    }
    .adhr2 ul{
      padding: 0;
      margin: 0;
      margin-bottom: 8px;
      margin-left: 10px;
    }
    .adhr2 ul li span{
      font-weight: bold;
    }
    .blank{
      min-height: 124px;
    }
    .adhr h3 span{
      border-bottom: solid 0px;
    }
    .cut{
      width: 12px;
      position: absolute;
      padding: 2px 0px 0px 5px;
    }
    .cut2{
      position: absolute;
      width: 8px;
      margin: 8px 0 0 -4px;
    }
    .brcd h5{
      margin: 0;
      font-weight: normal;
      font-size: 12px;
    }
    .brcd ul li{
      font-size: 7px;
      line-height: 8px;
    }
    .one{
        height: 500px;
    }
    .two{
        height: 110px;
    }
     .three{
        height: 178px;
    position: relative;
    margin-top: -11px;
    }
    .rtt_rt ul{
        width: 45%;
    }
    .info h4{
        color:#f60000;
        letter-spacing: .5px;
        text-transform: uppercase;
        font-size: 12px;
        padding-top: 10px;
    }
    .info ul li, .info2 ul li{
        font-size: 11px;
        line-height: 16px;
    }
    .info ul li span, .info2 ul li span{
        color:#f60000;
    }
    .info2 ul li{
        padding: 4px 0;
    }
    .info2, .info{
        padding: 0 20px;
    }
    .info li::before, .info2 li::before {
      content: "■";
      color: #D60F26;
      font-size: 12px;
      padding-right: 5px;
    }
    .info2 ul{
        border: solid 1px #666;
        padding: 5px;
    }
    .info2{
        padding: 0 15px;
    }
    .info2 ul li .brk, .info ul li .brk{
        color: #333;
        padding-left: 12px;
    }
    .img7{
        border-top: solid #e70000 2px;
        height: 18px;
        padding-top: 2px;
    }

    img.img2.img--013 {
    padding: 0;
    width: 332px;
    padding-left: 1px;
   }
   img.img6.image--010 {
    border: 0px;
    padding: 0px;
}
.right img.cut-008 {
    margin-left: 1px;
}

img.cut-verti {
    height: 841px;
    width: 10px;
}

p.download-date {
    font-weight: bold;
    transform: rotate(90deg);
    font-size: 7px;
    position: absolute;
    top: 97px;
    left: -31px;
}

p.download-date.issue {
    right: -314px;
}
    </style>

    <body>
        <div class="pdf">
            <div class="left">
                <div class="one">
                    <img src="images/gu/img38.jpg">
                    <p> નામાંકન ક્રમ સંખ્યા / Enrollment No: 4986/15632/9514 <?php echo $b['srno']?> </p>
                    <div class="rtt">
                        <p>Download&nbsp;Date:&nbsp;<?php echo date('d/m/Y')?></p>
                        <div class="clr"></div>
                    </div>
                    <div class="rtt_rt">
                        <ul>
                            <li>To</li>
                            <li><?php echo $b['namelocal']?></li>
                            <li><?php echo $b['name']?></li>
                            <li><?php echo $b['address']?></li>
                        </ul>
                        <div class="clr"></div>
                    </div>

                    <div class="rtt">
                        <p style="margin-top: 77px;">Issue&nbsp;Date:&nbsp;<?php echo date('d/m/Y',strtotime('-30 days'))?></p>
                        <div class="clr"></div>
                    </div>
                    <div class="brcd print">
                        <div class="prnt">
                            <h5>Signature Valid</h5>
                            <ul>
                                <li>Digitally signed by DS</li>
                                <li>UNIQUE IDENTIFICATION</li>
                                <li>AUTHORITY OF INDIA 03</li>
                                <li>Date: 2019.05.23 03:02:17</li>
                                <li>IST</li>
                            </ul>
                        </div>
                        <div class="clr"></div>
                    </div>
                    <div class="vld">
<?php
if ($b['gender']=='MALE'){
  $sex='M';
} 
else {
  $sex='F';
}
   /// qr code xml string start
   libxml_use_internal_errors(true);
   $simplexml= new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><books/>');
   $book1= $simplexml->addChild('book',"<PrintLetterBarcodeData uid=&quot;".addSpaceAfter4Digits($b['aadharno'])."&quot; name=&quot;".$b['name']."&quot; gender=&quot;".$sex."&quot; dob=&quot;".$b['dobadhar']."&quot; co=&quot;".$b['fathername']."&quot; po=&quot;".$b['vtcandpost']."&quot; address=&quot;".$b['address']."&quot; pc=&quot;".$b['pincode']."&quot;/>");
   $str='<?xml version="1.0" encoding="UTF-8"?>'.$book1;
   $codeContents = $str;

  
   ?>                   
                        <img src='https://quickchart.io/chart?chs=140x140&cht=qr&chl=<?php echo $codeContents;?>' title="" />
                        
                      
                        
                        <div class="clr"></div>
                    </div>

                    <div class="clr"></div>

                </div> <!--one-->

                <div class="two">
                    <img src="images/gu/img34.jpg" class="aapka-aadhar">

                    <h3><span><?php echo addSpaceAfter4Digits($b['aadharno'])?></span></h3>
                    
                    <img src="images/gu/img36.jpg" class="meri-image">

                </div>  <!--two-->

                <div class="adhr">
                    <img src="images/image--008.png" class="cut-008">
                    <div class="three">
                        <p class="download-date">Download&nbsp;Date:&nbsp;<?php echo date('d/m/Y')?></p>
                        <img src="images/gu/img28.jpg" class="img2">
                        <div class="a_lft">
        
                         <img src="<?php echo $b['imgdata']?>" />
       
                        </div>
                        <div class="a_rgt">
                            <ul>
                                <li><?php echo $b['namelocal']?></li>
                                <li><?php echo $b['name']?></li>
                                <li><?php echo $b['birthtithilocal'].' / '.'DOB : '?><?php echo $b['dobadhar']?></li>
                                <li><?php echo $b['genderlocal'].' / '?><?php echo $b['gender']?></li>
                            </ul>
                            
                            <?php /*
                            <img src='https://chart.googleapis.com/chart?chs=140x140&cht=qr&chl=<?php echo $codeContents; ?>' >
                            */ ?>
                            <p class="download-date issue">Issue&nbsp;Date:&nbsp;<?php echo date('d/m/Y',strtotime('-30 days'))?></p>
                        </div>
                    </div>  <!--three-->
                    <h3><span><?php echo addSpaceAfter4Digits($b['aadharno'])?></span></h3>
                    <!-- <h2>मेरा <span>आधार</span>, मेरी पहचान</h2> -->
                    <img src="images/gu/img30.jpg" class="img6 image--010">
                </div>

                <div class="clr"></div>
            </div>
            <div class="cntr">
                <img src="images/image--004.png" class="cut-verti">
                <div class="clr"></div>
            </div>
            <div class="right">
                <div class="one">
                    <img src="images/gu/img29.jpg" class="img4">
                    <?php /*
                    <div class="info">
                        <h4>सूचना</h4>
                        <ul>
                            <li><span>आधार </span> पहचान का प्रमाण है, नागरिकता का नहीं।</li>
                            <li>पहचान का प्रमाण ऑनलाइन ऑथेन्टिकेशन द्वारा प्राप्त करें |</li>
                            <li>यह एक इलेक्ट्रॉनिक प्रक्रिया द्वारा बना हुआ पत्र है |</li>
                        </ul>
                        <h4>Information</h4>
                        <ul>
                            <li><span><b>Aadhaar</b></span> is a proof of identity, not of citizenship.</li>
                            <li>To establish identity, authenticate online.</li>
                            <li>This is electronically generated letter.</li>
                        </ul>
                    </div>
                    <div class="info2">
                        <ul>
                            <li><span>आधार</span> देश भर में मान्य है |</li>
                            <li><span>आधार</span> भविष्य में सरकारी और गैर-सरकारी सेवाओं  <br><span class="brk"> का लाभ उठाने में उपयोगी होगा ।</span></li>
                            <li><span>Aadhaar</span> is valid throughout the country.</li>
                            <li><span>Aadhaar</span> will be helpfull in availing Government <br><span class="brk">and Non-Government services in future.</span></li>
                        </ul>
                    </div>*/
                    ?>
                    <img src="images/gu/img31.jpg" class="img4">
  
                </div> <!--one-->
                <div class="two"></div>

                <div class="adhr adhr2">
                    <img src="images/image--012.png" class="cut-008">
                    <div class="three">
                        <img src="images/gu/img32.jpg" class="img2 img--013">
                        <div class="b_lft">
                            <ul>
                                <li><span>સરનામું:</span></li>
                                <li><?php echo $b['addresslocal']?></li>
                            </ul>
                            <ul>
                                <li><span>Address:</span></li>
                                <li><?php echo $b['address']?></li>
                            </ul>
                        </div>
                        <div class="b_rgt">
                            
                         
                            <img src='https://quickchart.io/chart?chs=140x140&cht=qr&chl=<?php echo $codeContents; ?>' >
                           
                              
                             
                        </div>

                        <div class="clr"></div>
                    </div>  <!--three-->
                    <h3><span><?php echo addSpaceAfter4Digits($b['aadharno'])?></span></h3>
                    <img src="images/gu/img35.jpg" class="img6">
                </div>

                <div class="clr"></div>
            </div>
            <div class="clr"></div>
        </div>
    </body>
</html>