<?php

ini_set('memory_limit', -1);
require_once("../main_includes/init.php");

require_once("phpqrcode/qrlib.php");

require('fpdf/fpdf.php');
// include('../includes/configpdo.php');
if (!isset($_GET['record'], $_SESSION['user_id'], $_GET['service_id'])) {
    redirect("../");
}

$user = User::find_by_id($_SESSION['user_id']);
if (!$user) {
    redirect("../");
}

$sub_service = SubService::find_by_id($_GET['service_id']);
if (!$sub_service) {
    redirect("../");
}

$service_fee = intval($sub_service->service_fee);
$status = 1;
$service = $sub_service->service_name;

$my_wallet = Wallet::find_by_query("SELECT * FROM wallet WHERE user_id =" . $user->id . " LIMIT 1");
$my_wallet = array_shift($my_wallet);
$my_wallet_balance = intval($my_wallet->balance);



function generateRandomString() {
    $characters = 'abcdef0123456789';
    $string = '';
    for ($i = 0; $i < 8; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
    $string .= '-';
    for ($i = 0; $i < 4; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
    $string .= '-';
    for ($i = 0; $i < 4; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
    $string .= '-';
    for ($i = 0; $i < 4; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
    $string .= '-';
    for ($i = 0; $i < 12; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $string;
}
// if ($my_wallet_balance < $service_fee) {
//     redirect("../");
//     return false;
// }

$service_record = ServiceRecord::find_by_id($_GET['record']);
if (!$service_record) {

    redirect("../");
    return false;
}

$in_transaction = new InTransaction;

// $new_wallet_balance = $my_wallet_balance  - $service_fee;
// $my_wallet->balance = $new_wallet_balance;
// $my_wallet->date_updated = $date;
// $my_wallet->save();

$in_transaction->user_id = $user->id;
$in_transaction->wallet_id = $my_wallet->id;
$in_transaction->amount = $service_fee;
$in_transaction->remaining_balance = $my_wallet_balance;
$in_transaction->service = $service;
$in_transaction->date = $status == 1 ? $date : $in_transaction->date;
$in_transaction->service_id = intval($sub_service->service_id);
$in_transaction->status = $status;
$in_transaction->record_id = $service_record->id;
$in_transaction->search_query = $service_record->search_query;

if (!isset($_GET['redownload'])) {
    $in_transaction->save();
}
$response_std = json_decode($service_record->response);

// $nin = $response_std->nin_data->nin;
$nin = $response_std->nin_data->nin != '' ? $response_std->nin_data->nin : $service_record->search_query;


$date_string = strtotime($response_std->nin_data->birthdate);
$birthdate =  date("d M Y", $date_string);

$qr_file = "qr_temp/test.png";

$names = $response_std->nin_data->firstname . ($response_std->nin_data->middlename == "****" || $response_std->nin_data->middlename == "" ? "" : " " . $response_std->nin_data->middlename) . " " . $response_std->nin_data->surname;

QRcode::png('{"NIN":"' . $nin . '", "Names": "' . $names . '", "Date of Birth":"' . $birthdate . '", "Status":"Verified"}', $qr_file, QR_ECLEVEL_M);
// QRcode::png('{"l": "n", "h":"e696da32e11c1cd69d7224f8d15637fd1de1faa8", "sig":"mjyhuogy7y08luiy98yuhoih98"}', $qr_file, QR_ECLEVEL_M);
$sub1 = substr($nin, 0, 4);
$sub2 = substr($nin, 4, 3);
$sub3 = substr($nin, 7, 4);


$currentDate = new DateTime();
$formattedTimestamp = $currentDate->format("Y-m-d\TH:i:s.00");

// echo "<pre>";
// print_r($response_std);
// return false;
$timestamp = $response_std->nin_data->ts ?? $formattedTimestamp;
$txn_id = $response_std->nin_data->txid ?? generateRandomString();
$verification_type = "TOKEN";
$verification_status = "OK";
$agent ="JZLHTW-8978";
// $agent = $response_std->nin_data->agentID;

class PDF extends FPDF
{
    public $agent = 'AS';


    function Header()
    {
        // Select Arial bold 15
        $this->AddFont('OCR-B 10 BT', '', 'OCR-B 10 BT.php');
        $this->SetFont('OCR-B 10 BT', '', 26);
        $this->SetTextColor(0, 0, 0);
        $this->SetDrawColor(0, 0, 155);
        $this->Ln(1);
        $this->SetFont('Arial', 'B', 12);
        $this->image("nimc_logo.jpg", 85, 20, 38, 37);
        $this->Ln(43);
        // $this->Cell(0, 5, "Verification-as-a-Service", 0, 1, 'C', false);

        $this->SetTextColor(230, 230, 230);
        $this->SetFont('OCR-B 10 BT', '', 40);
      
        $this->TextWithRotation(20, 122, $this->agent, 45);
        $this->TextWithRotation(72, 122, $this->agent, 45);
        $this->TextWithRotation(132, 122, $this->agent, 45);

        $this->Image('new_nin_bg.jpg', 18, 61, 58, 37);
        // $this->Image('improved_nin_bg.jpg', 66, 51, 80, 99);
        // Line break 
        $this->Ln(2);
    }

    function TextWithRotation($x, $y, $txt, $txt_angle, $font_angle = 0)
    {
        $font_angle += 90 + $txt_angle;
        $txt_angle *= M_PI / 180;
        $font_angle *= M_PI / 180;

        $txt_dx = cos($txt_angle);
        $txt_dy = sin($txt_angle);
        $font_dx = cos($font_angle);
        $font_dy = sin($font_angle);

        $s = sprintf('BT %.2F %.2F %.2F %.2F %.2F %.2F Tm (%s) Tj ET', $txt_dx, $txt_dy, $font_dx, $font_dy, $x * $this->k, ($this->h - $y) * $this->k, $this->_escape($txt));
        if ($this->ColorFlag)
            $s = 'q ' . $this->TextColor . ' ' . $s . ' Q';
        $this->_out($s);
    }

    function Footer()
    {
        // Go to 0.9 cm from bottom
        // $this->SetY(-9);
        // $this->SetFont('Arial', 'I', 8);
        // Print centered page number
        // $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
    }
}



$pdf = new PDF();
$pdf->agent = $agent;

// $pdf->AddFont('ocr-a-bt', '', "C:/xamppp/htdocs/yamala_dash/print/fpdf/font/ocr-a-bt.php");
$pdf->AliasNbPages();
$pdf->AddPage('P', 'A4');
$pdf->SetFont('Arial', 'B', 12);

$pdf->Cell(0, 5, "Verification-as-a-Service", 0, 1, 'C', false);
$pdf->SetFont('OCR-B 10 BT', '', 10);
$pdf->SetFillColor(240, 240, 255);
if ($response_std->nin_data->photo != '') {
    $filename = './tmp/t' . rand(00000000, 99999999) . '.jpeg';
    if (file_exists($filename)) {
        unlink($filename);
    }
    $img_o = base64_decode($response_std->nin_data->photo);
    $img =  imagecreatefromstring($img_o);
    imagejpeg($img, $filename);
    $pdf->Image($filename, 19, 72, 13, 16);
}
// $pdf->Image("nimc_logo.jpg", 69, 63, 19, 25);
$pdf->Image($qr_file, 55, 70, 20);
$pdf->Image("qr_temp/big_qr.png", 157, 56, 40,43);

// $pdf->Image("qr_temp/qr_center.png", 135.5, 70, 7);


$pdf->SetTextColor(230, 230, 230);
$pdf->SetFont('OCR-B 10 BT', '', 40);

// $pdf->TextWithRotation(20, 122, "UETHAV-123", 45);
// $pdf->TextWithRotation(72, 122, "UETHAV-123", 45);
// $pdf->TextWithRotation(132, 122, "UETHAV-123", 45);

$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('Arial', 'B', 9);
$pdf->TextWithRotation(78, 70, "Surname/Nom", 0);

$pdf->SetFont('Arial', 'B', 15);
$pdf->TextWithRotation(78, 75, $response_std->nin_data->surname, 0);

$pdf->SetFont('Arial', 'B', 9);
$pdf->TextWithRotation(78, 81, "Given Names/Prenoms", 0);

$pdf->SetFont('Arial', 'B', 15);
$pdf->TextWithRotation(78, 86, $response_std->nin_data->firstname . ($response_std->nin_data->middlename == "****" || $response_std->nin_data->middlename == '' ? '' : ", " . $response_std->nin_data->middlename), 0);


$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('OCR-B 10 BT', '', 9);
$pdf->Ln(7);
$pdf->Cell(111, 4, 'NGA', 0, 1, 'C', false);

// $pdf->Ln(4);

$pdf->Cell(23, 2, '', 0, 0, 'L', false);
$pdf->SetTextColor(130, 130, 130);
$pdf->SetFont('Arial', 'B', 5);
$pdf->Cell(37, 2, 'Surname/Nom', 0, 0, 'L', false);
$pdf->Cell(20.5, 2, '', 0, 1, 'L', false);


$pdf->Cell(23, 2, '', 0, 0, 'L', false);

$pdf->SetFont('OCR-B 10 BT', '', 7);
$pdf->SetTextColor(0, 0, 0);
$pdf->Cell(37, 2, $response_std->nin_data->surname, 0, 0, 'L', false);
$pdf->Cell(20.5, 2, '', 0, 1, 'L', false);

$pdf->Ln(2);
$pdf->Cell(23, 2, '', 0, 0, 'L', false);
$pdf->SetTextColor(130, 130, 130);
$pdf->SetFont('Arial', 'B', 5);
$pdf->Cell(37, 2, 'Given Names/Prenoms', 0, 0, 'L', false);
$pdf->Cell(20.5, 2, '', 0, 1, 'L', false);

$pdf->Cell(23, 2, '', 0, 0, 'L', false);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('OCR-B 10 BT', '', 7);
$pdf->Cell(37, 2, $response_std->nin_data->firstname . ($response_std->nin_data->middlename == "****" || $response_std->nin_data->middlename == '' ? '' : ", " . $response_std->nin_data->middlename), 0, 0, 'L', false);
$pdf->Cell(20.5, 2, '', 0, 1, 'L', false);
$pdf->Ln(2);

$pdf->Cell(23, 2, '', 0, 0, 'L', false);
$pdf->SetTextColor(130, 130, 130);
$pdf->SetFont('Arial', 'B', 5);
$pdf->Cell(37, 2, 'Date of Birth', 0, 0, 'L', false);
$pdf->Cell(20.5, 2, '', 0, 1, 'L', false);

$pdf->Cell(23, 2, '', 0, 0, 'L', false);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('OCR-B 10 BT', '', 7);
$pdf->Cell(37, 2, strtoupper($birthdate), 0, 0, 'L', false);
$pdf->Cell(20.5, 2, '', 0, 1, 'L', false);

// $pdf->Ln(6);
// $pdf->SetFont('Arial', 'B', 7);
// $pdf->Cell(81, 3, '', 0, 0, 'L', false);
// $pdf->Cell(39, 3, 'National Identification Number (NIN)', 0, 0, 'C', false);
// $pdf->Cell(20.5, 3, '', 0, 1, 'L', false);
$pdf->SetFillColor(200,200,200);

$pdf->SetFont('Arial', 'B', 7);

$pdf->Ln(12);
$pdf->Cell(8,7,'',0,0,'C');
$pdf->Cell(30,5,'TimeStamp',0,0,'C',true);
$pdf->Cell(55,5,'Transaction ID',0,0,'C',true);
$pdf->Cell(28,5,'Verification Type',0,0,'C',true);
$pdf->Cell(28,5,'Verification Status',0,0,'C',true);
$pdf->Cell(38,5,'Verification Agent ID',0,1,'C',true);
$pdf->Cell(8,2,'',0,0,'C');
$pdf->Cell(30,2,'',0,0,'C',true);
$pdf->Cell(55,2,'',0,0,'C',true);
$pdf->Cell(28,2,'',0,0,'C',true);
$pdf->Cell(28,2,'',0,0,'C',true);
$pdf->Cell(38,2,'',0,1,'C',true);

$pdf->SetFont('OCR-B 10 BT', '', 7);
$pdf->Cell(8,7,'',0,0,'C');
$pdf->Cell(30,7,$timestamp,1,0,'L');
$pdf->Cell(55,7,$txn_id,1,0,'C');
$pdf->Cell(28,7,$verification_type,1,0,'C');
$pdf->Cell(28,7,$verification_status,1,0,'C');
$pdf->Cell(38,7,$agent,1,1,'C');
// $pdf->Cell(10,7,'',1,1,'C',true);



if ($response_std->nin_data->photo != '') {
    if (file_exists($filename)) {
        unlink($filename);
    }
}
// $pdf->Ln(5);
// $pdf->MultiCell(0, 5, 'NOTE:.', 0, 1, 'C', true);


$doc_name = $nin . "_VNIN_verification_slip.pdf";
// ob_clean();
// $pdf->Output();
$pdf->Output("D", $doc_name);