<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\OrderedDocument;
use App\DocumentComplains;
use App\TransactionDetailsModel;
use Session;
use \stdClass;
use DB;

class MainPageController extends Controller
{
    //

    public function index() {
      
        return view('dashboard.index');
    }

    public function verificationPage() {
        $countries = [];
        $programmes = [];

        $data = [
            'countries' => $countries,
            'programmes' => $programmes,
        ];
        return view('verification_page.index', $data);
    }

    public function applyNow() {
        return view('apply.index');
    }

    public function getPrograms() {
        
        // $url = 'http://portal.kstu.edu.gh/sois/ilo_details.php';
        $post_arr = array('action' => 'get_program', 'param' => 'btech');
        // $respons = $this->sois_connect($url, $post_arr);
        // $program_response = json_decode($respons, true);
        $programs = $this->get_sois_program($post_arr);
        return $programs;
    }

    public function verifyTransactionId(Request $request) {
        $transaction_id = $request->transaction_id;
       
        $emailaddress = "src@htu.edu.gh";
        $password = "htu@src2021";
        $merchant_id = "46";

        $data = [
            'email' => $emailaddress,
            'password' => $password,
            'merchant_id' => $merchant_id,
        ];

        $data_ = json_encode($data);
        $response = $this->getToken($data_);
        $decoded_response = json_decode($response, true);
        if ($decoded_response) {
            if (in_array($merchant_id, $decoded_response)) {
                $the_token = $decoded_response['access_token'];
                session()->put('current_user.token', $the_token);
            }

            $data = [
                "transaction_id" => $transaction_id,
            ];

            $ordered_document = OrderedDocument::where('transaction_id', $transaction_id)->first();
            
            $data_ = json_encode($data);

            $response = $this->verifyTransaction($data_, $the_token);
            
            $decoded_response = json_decode($response, true);
            if ($decoded_response) {
                if (!in_array('R0122', $decoded_response)) { 
                    session()->put('current_user.document_information', $decoded_response);
                }
                
                $check_transaction_id = TransactionDetailsModel::where('transaction_id', $transaction_id)->first();
                if ($check_transaction_id) {
                    return 'failed';
                }
            }
            return $decoded_response; 
        }
        return $decoded_response;
    }

    public function saveTransactionDetails(Request $request) {
        $decoded_response = json_decode($request->transaction_details);
        $transaction_details = new TransactionDetailsModel;
        $transaction_details->transaction_id = $decoded_response->transaction_id;
        $transaction_details->amount = $decoded_response->amount;
        $transaction_details->api_user_id = $decoded_response->api_user_id;
        $transaction_details->balance = $decoded_response->balance;
        $transaction_details->balancebf = $decoded_response->balancebf;
        $transaction_details->bank_account = $decoded_response->bank_account;
        $transaction_details->client_id = $decoded_response->client_id;
        $transaction_details->company_id = $decoded_response->company_id;
        $transaction_details->customer_charge = $decoded_response->customer_charge;
        $transaction_details->dates = $decoded_response->dates;
        $transaction_details->fetched = $decoded_response->fetched;
        $transaction_details->merchant_amount = $decoded_response->merchant_amount;
        $transaction_details->merchant_charge = $decoded_response->merchant_charge;
        $transaction_details->product_id = $decoded_response->product_id;
        $transaction_details->product_type = $decoded_response->product_type;
        $transaction_details->receiptno = $decoded_response->receiptno;
        $transaction_details->sold_by = $decoded_response->sold_by;
        $transaction_details->telegramed = $decoded_response->telegramed; 
        $response = $transaction_details->save();   
        if ($response) {
            return 'success';
        } else {
            return 'failed';
        }
    }

    public function trackDocument() {
        return view('enter_information.transcript_details');
    }
    
    public function getStudentInformation($index_number) {
        $student_data = $this->getStudentResult($index_number);
        return $student_data;
    }

    public function transcriptDetails(Request $request) {
        $tracking_no = $request->tracking_no;
        $ordered_document = OrderedDocument::where('tracking_no', $tracking_no)->first();
        if ($ordered_document) {
            return $ordered_document;
        } 

        return "failed";
        
    }


    public function verifyIndexNumber(Request $request) {
        $token = Session::get('current_user.token');
        $index_number = $request->index_number;
        $response = $this->getStudent($index_number);
        $decoded_response = json_decode($response, true);
        if ($decoded_response) {
            if (!in_array('R0122', $decoded_response)) { 
                session()->put('current_user.student_information', $decoded_response);
            }
        }
        
        return $decoded_response;
    }

    public function paymentOptions() {
        return view('payment_options.index');
    }

    public function enterInformation() {
        return view('enter_information.index');
    }

   public function saveOrderedDocumentInformation(Request $request) {
        $index_no = $request->index_no;
        $phone_no = $request->phone_no;
        $applicant_name = empty($request->applicant_name) ? " " : $request->applicant_name;
        $emailaddress = empty($request->emailaddress) ? " " : $request->emailaddress;
        $postal_address = empty($request->postal_address) ? " " : $request->postal_address;
        $tracking_no = empty($request->tracking_no) ? " " : $request->tracking_no;
        $type_of_document = empty($request->type_of_document) ? " " : $request->type_of_document;
        $transaction_id = $request->transaction_id;
        $year_of_admission = $request->year_of_admission;
        $year_of_completion = $request->year_of_completion;
        $program_code = $request->program_code;
        $program = empty($request->program) ? "" : $request->program;
        $delivery_mode = $request->delivery_mode;
        $country = empty($request->country) ? " " : $request->country;
        $state = empty($request->state) ? " " : $request->state;
        $zip_code = empty($request->zip_code) ? " " : $request->zip_code;
        $d_mode = "";
        $status = "Ordered";
        $created_at = $request->created_at;

        $check_if_exists = DB::select('select * from ordered_document where tracking_no = ?', [$tracking_no]);
    
        if (sizeof($check_if_exists) > 0 ) {
            return 'failed';
        } else {
            $response = DB::insert("insert into ordered_document(tracking_no, index_no, applicant_name, phone_no, emailaddress, year_of_admission, year_of_completion, program_code, program, postal_address, type_of_document, transaction_id, delivery_mode, zip_code, country, state, d_mode, status) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [$tracking_no, $index_no, $applicant_name, $phone_no, $emailaddress, $year_of_admission, $year_of_completion, $program_code, $program, $postal_address, $type_of_document, $transaction_id, $delivery_mode, $zip_code, $country, $state, $d_mode, $status]);
            if ($response) {
                $message = "Your application has been received and is being processed. You can proceed to https://app.htu.edu.gh/drs/track-document with this tracking number:- " . $tracking_no . ". You can track the status of the document while it is being processed. Thank you." ;
                $sms = $this->send_sms($phone_no, $message);
                return 'success';
            } else {
                return 'failed';
            }
        }
    }

    public function makeAComplain(Request $request) {
        $tracking_no = $request->tracking_no;
        $complain = $request->complain;
        $status = "Not Attended";

        $document_complain = new DocumentComplains;
        $document_complain->tracking_no = $tracking_no;
        $document_complain->complain = $complain;
        $document_complain->status = $status;
        
        $response = $document_complain->save();
        if ($response) {
            return "success";
        } else {
            return "failed";
        }
    }
    
    
    public function makeMigration()
    {
        $old_records = DB::select('select * from transcript');
        if ($old_records) {
            foreach ($old_records as $key => $value) {
                $status = "";
                switch ($value->status) {
                    case 'ORDERED':
                         $status = "Just Applied";
                        break;
                    case 'PRINTED':
                        $status = 'Printed';
                        break;
                    default:
                        # code...
                        $status = 'Just Applied';
                        break;
                }
                $index_no = $value->indexno;
                $phone_no = $value->tel;
                $applicant_name = $value->name;
                $emailaddress = " ";
                $postal_address = $value->contactAddress;
                $tracking_no = $value->trackingno;
                $type_of_document = $value->product;
                $transaction_id = $this->generateRandomString(15);
                $year_of_admission = "";
                $year_of_completion = "";
                $program = "";
                $delivery_mode = $value->delivery;
                $country = $value->country;
                $state = "";
                $zip_code = "";
                $d_mode = "";
                $status = $status;
                $created_at = "";
                $response = DB::insert("insert into ordered_document(tracking_no, index_no, applicant_name, phone_no, emailaddress, year_of_admission, year_of_completion, program, postal_address, type_of_document, transaction_id, delivery_mode, zip_code, country, state, d_mode, status) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [$tracking_no, $index_no, $applicant_name, $phone_no, $emailaddress, $year_of_admission, $year_of_completion, $program, $postal_address, $type_of_document, $transaction_id, $delivery_mode, $zip_code, $country, $state, $d_mode, $status]);

            }
        }
        return "success";
    }
    
    public function generateRandomString($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }


}