<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
if (isset($_POST['screenName'])) {
    require_once('../config/db_config.php');
    
    $screenName = $_POST['screenName'];

    $date_obj = DateTime::createFromFormat('d/m/Y', $_POST['minDate']);
    $fromDate = $date_obj->format('Y-m-d');

    $date_obj1 = DateTime::createFromFormat('d/m/Y', $_POST['maxDate']);
    $toDate = $date_obj1->format('Y-m-d');
    $email = $_POST['email'];
    $user = $_POST['username'];
    $paymentStatus = $_POST['paymentStatus'];

    $failedStatus = ['failed', 'fail','cancelled','Error: You cannot use a Stripe token more tha','Declined' , 'TXN_FAILURE'];
    $processingStatus = ['captured', 'initiate','started','pending'];
    $successStatus = ['success','captured','guaranteed','txn-success','completed','settledSuccessfully','capturedPendingSettlement','Approved' , 'TXN_SUCCESS'];
    $results = [];
    if (
        $screenName == 'online_payment' ||
        $screenName == 'enrollment_payment' ||
        $screenName == 'declaration_payment' ||
        $screenName == 'assessment_payment' ||
        $screenName == 'reval_payment' ||
        $screenName == 'sendPaymentLink_payment'||
        $screenName == 'advance_payment'|| 
        $screenName == 'donation_payment' ||
        $screenName == 'course_registration_payment' ||
        $screenName == 'course_registration_pending_payment'
    )
    {
        $fieldName = 'name';
        // if ($screenName == 'assessment_payment' || $screenName == 'reval_payment') {
        //     $fieldName = 'firstName';
        // }

        if ($paymentStatus === 'failed') {
            $statusQuery = " AND LOWER(`paymentStatus`) IN ('" . implode("', '", array_map('strtolower', $failedStatus)) . "')";
        } elseif ($paymentStatus === 'all') {
            $statusQuery = " AND LOWER(`paymentStatus`) != ''";
        } elseif ($paymentStatus === 'success') {
            $statusQuery = " AND LOWER(`paymentStatus`) IN ('" . implode("', '", array_map('strtolower', $successStatus)) . "')";
        }

        if($screenName == 'sendPaymentLink_payment' || $screenName == 'online_payment')
        {
            if($screenName == 'sendPaymentLink_payment'){
                   $screenName = 'online_payment';
                $query = "SELECT *  FROM `$screenName` WHERE DATE(paymentDate) BETWEEN '$fromDate' AND '$toDate' $statusQuery AND ('$email' = '' OR `email` = '$email') AND ('$user' = '' OR `$fieldName` LIKE '%$user%') AND `paymentType` = 'SendPaymentLink-PAYMENT'";
            }else{
                $query = "SELECT * FROM `$screenName` WHERE DATE(paymentDate) BETWEEN '$fromDate' AND '$toDate' $statusQuery AND ('$email' = '' OR `email` = '$email') AND ('$user' = '' OR `$fieldName` LIKE '%$user%') AND `paymentType` != 'SendPaymentLink-PAYMENT' ";

            }
        }else{
            $query = "SELECT * FROM `$screenName` WHERE DATE(paymentDate) BETWEEN '$fromDate' AND '$toDate' $statusQuery AND ('$email' = '' OR `email` = '$email') AND ('$user' = '' OR `$fieldName` LIKE '%$user%')";
        }



        if (!empty($email)) {
            $query .= " AND `email` = '$email'";
        }
        if (!empty($user)) {
            $query .= " AND `$fieldName` LIKE '%$user%'";
        }

        $dta = mysqli_query($conn, $query);
        while ($row = mysqli_fetch_assoc($dta)) {
            unset($row['paymentRequest']);
            unset($row['gatewayConfig']);
            $results[] = $row;
        }
    }

    $obj = '';
    $rawdata = [];

    if (count($results) > 0) {
        for ($i = 0; $i < count($results); $i++) {
            $a = $i + 1;
            $paymentDate = date('d/m/Y', strtotime($results[$i]['paymentDate']));
            $fieldName = isset($results[$i]['name']) ? 'name' : 'firstName';
            $paymentStatus = isset($results[$i]['paymentStatus'])?strtolower($results[$i]['paymentStatus']):'';
            $receiptStatus = isset($results[$i]['receiptStatus'])?strtolower($results[$i]['receiptStatus']):'';
            if (in_array($paymentStatus, $failedStatus)) {
                $paymentStatus = 'FAILED';
            } elseif (in_array($paymentStatus, $processingStatus)) {
                if($paymentStatus === 'captured')
                {
                    $paymentStatus = 'SUCCESS';
                }
                else
                {
                    $paymentStatus = 'PROCESSING';
                }

            }
            if (in_array($receiptStatus, $successStatus)) {
                $receiptStatus = 'SUCCESS';
            }
            $obj .= '<tr>';
            $obj .= '<td>' . $a . '</td>';
            $obj .= '<td>' . ucwords(strtolower($results[$i][$fieldName])) . '</td>';
            $obj .= '<td>' . $results[$i]['email'] . '</td>';
            if($screenName == 'donation_payment')
            {
                $obj .= '<td>N/A</td>';
            }
            else
            {
                $obj .= '<td>' . (isset($results[$i]['code']) ? $results[$i]['code'] : $results[$i]['studentCode']) . '</td>';
            }
            
            
            $obj .= '<td>' . $results[$i]['txnId'] . '</td>';
            $obj .= '<td>' . $paymentDate . '</td>';
            $obj .= '<td>' . strtoupper($paymentStatus) . '</td>';
            $obj .= '<td>' . (isset($receiptStatus) ? strtoupper($receiptStatus) : '') . '</td>';
            $obj .= '<td>' . $results[$i]['amount'] . '</td>';
            $obj .= '</tr>';

            $rawdata[] = $results[$i];
        }
        echo json_encode(array(
            'html' => $obj,
            'rawdata' => $rawdata
        ));
    } else {
        echo json_encode(array(
            'html' => '<tr><td colspan="6">No data found</td></tr>',
            'rawdata' => $rawdata
        ));

    }
} else {
    echo json_encode(array(
        'html' => '<tr><td colspan="6">No data found</td></tr>',
        'rawdata' => $rawdata
    ));
}
