<?php
ob_start();
require_once("../layouts/members/head.php");

/* ============================================================
   0) Helper: cURL (same as your working version)
============================================================ */
function execute_curl_request($url, $postData) {
    $maxRetries = 5; 
    $retryDelay = 2; 
    $response = null;
    $error = null;
    $info = null;

    for ($i = 0; $i < $maxRetries; $i++) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        if ($response !== false && isset($info['http_code']) && $info['http_code'] >= 200 && $info['http_code'] < 300) {
            break;
        }
        if ($i < $maxRetries - 1) {
            sleep($retryDelay);
        }
    }

    if ($error || !$response) {
        return [
            'error' => $error ?: 'No response from server after multiple attempts.',
            'http_code' => $info['http_code'] ?? null,
        ];
    }

    return [
        'response' => $response,
        'content_type' => $info['content_type'] ?? '',
        'http_code' => $info['http_code'] ?? 0,
    ];
}

/* ============================================================
   0.1) Safe output / JSON helpers for action buttons
============================================================ */
if (!function_exists('pr_h')) {
    function pr_h($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('pr_base64_json')) {
    function pr_base64_json($value) {
        if (!isset($value) || trim((string)$value) === '') {
            return [];
        }

        $decoded = base64_decode((string)$value, true);
        if ($decoded === false) {
            $decoded = (string)$value;
        }

        $data = json_decode($decoded, true);
        return is_array($data) ? $data : [];
    }
}

if (!function_exists('pr_first_value')) {
    function pr_first_value($values) {
        foreach ((array)$values as $value) {
            if (is_array($value) || is_object($value)) {
                continue;
            }

            if (isset($value) && trim((string)$value) !== '') {
                return trim((string)$value);
            }
        }

        return '';
    }
}

/* ============================================================
   1) Print options (same as yours)
============================================================ */
$printOptions = [
    // 'Aadhar_FingerPrint' => [
    //     'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/aadhaar', 'label' => 'Old Card'],
    //     'pvc_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/aadhaar-pvc', 'label' => 'PVC Card']
    // ],
    // 'AADHAR_OTP' => [
    //     'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/aadhaar', 'label' => 'Old Card'],
    //     'pvc_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/aadhaar-pvc', 'label' => 'PVC Card']
    // ],
    // 'Aadhar Manual' => [
    //     'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/aadhaar', 'label' => 'Old Card'],
    //     'pvc_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/aadhaar-pvc', 'label' => 'PVC Card']
    // ],
    // 'VOTER PRINT' => [
    //     'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/Voter_Add', 'label' => 'New Card'],
    //     'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/Voter', 'label' => 'Old Card'],
    // ],
    'VEHICALRCPDF' => [
        'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/RC-pvc', 'label' => 'New Card', 'rccardFormate' => 'new_card'],
        'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/RC-pvc', 'label' => 'Chip Card', 'rccardFormate' => 'old_card'],
    ],
    'DL PDF' => [
        'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/dlPrint', 'label' => 'New Card', 'rccardFormate' => 'new_card'],
        'blue_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/dlPrint', 'label' => 'Blue Card', 'rccardFormate' => 'blue_card'],
        'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/dlPrint', 'label' => 'Chip Card', 'rccardFormate' => 'old_card'],
    ],
    'RATIONPDF' => [
        'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/RationPrint-New', 'label' => 'New Card'],
        'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/RationPrint', 'label' => 'Old Card'],
    ],
    // 'PAN PRINT' => [
    //     'nsdl' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/Pan_Preview', 'label' => 'e-Pan NSDL', 'company' => 'NSDL'],
    //     'uti' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/Pan_Preview', 'label' => 'e-Pan UTI', 'company' => 'UTI']
    // ],
    'e_Sharm_Verification' => [
        'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/e-sharm', 'label' => 'Server 1'],
        'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/e-sharm', 'label' => 'Server 2'],
    ],
    'FAMILYIDPDF' => [
        'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/familyhr', 'label' => 'Server 1'],
        'old_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/familyhr', 'label' => 'Server 2'],
    ],
    'Farmer_Certificate' => [
        'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/dbtFarmer', 'label' => 'Server 1'],
    ],
    'Agri_Farmer_Certificate' => [
        'new_card' => ['url' => 'https://'.p4pointsapi("cardprintApi_url").'/PrintData/farmerStak', 'label' => 'Server 1'],
    ],
];

/* ============================================================
   2) PRINT (same logic as yours)
============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['print_option'])) {
    $service = $_POST['service'] ?? '';
    $optionKey = $_POST['option_key'] ?? '';
    $token = $_POST['token'] ?? '';
    $access_token = $_POST['access_token'] ?? '';
    $printdata = $_POST['printdata'] ?? '';
    $url = $printOptions[$service][$optionKey]['url'] ?? null;
    $company = $printOptions[$service][$optionKey]['company'] ?? null;
    $rccardFormate = $printOptions[$service][$optionKey]['rccardFormate'] ?? null;

    if (!$url) {
        echo "<div class='alert alert-danger'>Invalid print option selected.</div>";
        exit;
    }

    $postData = [
        'service' => $service,
        'token' => $token,
        'access_token' => $access_token,
        'printdata' => $printdata,
    ];
    if ($company) $postData['company'] = $company;
    if ($rccardFormate) $postData['rccardFormate'] = $rccardFormate;

    $result = execute_curl_request($url, $postData);
    if (!isset($result['response'])) {
        echo "<div class='alert alert-danger'>Error: Server Busy. Please try again.</div>";
    } else {
        $json = json_decode($result['response'], true) ?? '';
        if (isset($result['content_type'], $result['http_code']) && $result['content_type'] === 'application/pdf' && $result['http_code'] === 200) {
            $filename = base64_decode($access_token) . '.pdf';
            $pdfBase64 = base64_encode($result['response']);
            echo <<<HTML
<!DOCTYPE html>
<html>
<head><title>Downloading PDF...</title></head>
<body>
<div class="alert alert-success text-center">Download Started. You will be redirected in 3 seconds.</div>
<script>
function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);
    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) byteNumbers[i] = slice.charCodeAt(i);
    byteArrays.push(new Uint8Array(byteNumbers));
  }
  return new Blob(byteArrays, { type: contentType });
}
const blob = b64toBlob("{$pdfBase64}", "application/pdf");
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "{$filename}";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setTimeout(()=>{ window.location.href = ""; }, 3000);
</script>
</body></html>
HTML;
        } else {
            if (isset($json['error'])) {
                $responseMessage = "<div class='alert alert-danger'>Error: " . htmlspecialchars($json['error']) . "</div>";
            } else {
                $responseMessage = "<div class='alert alert-danger'>Unexpected response: " . htmlspecialchars($result['response']) . "</div>";
            }
        }
    }
}

/* ============================================================
   3) UNIFIED “Check Status” for PAN + RATION (single process)
   + Guard against already refunded (record status + reports row)
============================================================ */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['service'])
    && in_array($_POST['service'], ['PanUidFind_Request','RationUidFind_Request'], true)
    && isset($_POST['id'])
) {
    $service  = $_POST['service'];
    $recordId = (int)$_POST['id'];

    $UID_CFG = [
        'PanUidFind_Request' => [
            'where'        => "id = %d AND service = 'PanUidFind_Request'",
            'id_label'     => 'panNumber',
            'runner'       => function($idNumber){ return pantoUidCheck_run(['panNumber'=>$idNumber]); },
            'fee_col'      => 'pan2uid_find_fee',
            'build_save'   => function($r){ return [
                'panNumber'=>$r['panNumber']??'',
                'name'=>$r['name']??'',
                'dob'=>$r['dob']??'',
                'gender'=>$r['gender']??'',
                'uid'=>$r['uid']??'',
            ];},
            'sms_success'  => function($save,$brand){
                $msg="Your PAN UID Find Request was Successful.\n\n";
                $msg.="*PAN:* {$save['panNumber']}\n";
                if(!empty($save['uid']))    $msg.="*UID:* {$save['uid']}\n";
                if(!empty($save['dob']))    $msg.="*DOB:* {$save['dob']}\n";
                if(!empty($save['gender'])) $msg.="*Gender:* {$save['gender']}\n";
                $msg.="\nBest Regards,\n_*{$brand}*_";
                return $msg;
            },
            'refund_desc'  => function($id,$amt){ return "Rs.{$amt} refunded for PAN UID Request Failure"; },
            'err_notrec'   => "Invalid record ID or not a PAN UID request.",
        ],
        'RationUidFind_Request' => [
            'where'        => "id = %d AND service = 'RationUidFind_Request'",
            'id_label'     => 'rationNumber',
            'runner'       => function($idNumber){ return ration2uid_find_allstate_check_status_api_run(['rationNumber'=>$idNumber]); },
            'fee_col'      => 'rationto_uid_find_all_fee',
            'build_save'   => function($r){ return [
                'rationNumber'=>$r['rationNumber']??'',
                'count'=> $r['count'] ?? (isset($r['data'])?count($r['data']):0),
                'data'=> $r['data'] ?? [],
            ];},
            'sms_success'  => function($save,$brand){
                $cnt=(int)($save['count']??0);
                $msg="Your Ration UID Find Request was Successful.\n\n";
                $msg.="*Ration No:* {$save['rationNumber']}\n";
                $msg.="*Count:* {$cnt}\n";
                $msg.="\nBest Regards,\n_*{$brand}*_";
                return $msg;
            },
            'refund_desc'  => function($id,$amt){ return "Rs.{$amt} refunded for Ration UID Request Failure"; },
            'err_notrec'   => "Invalid record ID or not a Ration UID request.",
        ],
    ];
    $cfg = $UID_CFG[$service];

    // Fetch record
    $rec = db_fetch_array("printRecords", sprintf($cfg['where'], $recordId));
    if (!$rec) {
        awal_alert_msg($cfg['err_notrec'], "error");
        redirect("printRecord", 1500);
    }

    $idNumber = trim($rec['idNumber']);
    $apiJson  = $cfg['runner']($idNumber);
    $result   = json_decode($apiJson, true) ?? [];

    // Success → save + notify
    if (isset($result['status']) && (string)$result['status']==='100') {
        $save = $cfg['build_save']($result);
        $base64Json = base64_encode(json_encode($save, JSON_UNESCAPED_UNICODE));
        $affected = db_update("printRecords", ['printData'=>$base64Json, 'status'=>'Success'], "id = {$recordId}");

        $uname = $rec['username'] ?? null;
        if ($uname) {
            $u = db_fetch_array("members", "username='{$uname}'");
            if ($u) {
                $sms = "Dear {$u['name']},\n".$cfg['sms_success']($save, $site_data['brand']);
                send_sms_credentials($u['mobile'], $sms);
            }
        }

        awal_alert_msg($affected>0 ? "UID found and record updated successfully" : "Record already updated or no change detected", $affected>0?'success':'warning');
        redirect("printRecord", 1500);
    }elseif (isset($result['statusMessage']) && strtolower($result['statusMessage'])==='refunded') {
        $errorMsg = $result['message'] ?? $result['error'] ?? 'Something went wrong.';

        // 1) Already marked refund?
        if (strtolower($rec['status'])==='refund') {
            awal_alert_msg("Already refunded for this request.", "warning");
            redirect("printRecord", 1500);
            exit;
        }

        $userid = $rec['username'] ?? null;
        if (!$userid) { awal_alert_msg("Username not found in record.", "error"); redirect("printRecord", 1500); }

        // 2) Refund already logged earlier?
        $existingRefund = db_fetch_array(
            "reports",
            "service = '{$service}' AND status = 'Refund' AND ref_id = '{$idNumber}' AND username = '{$userid}'"
        );
        if ($existingRefund) {
            // Normalize record status if needed
            if (strtolower($rec['status']) !== 'refund') {
                db_update("printRecords", ['status' => 'Refund'], "id = {$recordId}");
            }
            awal_alert_msg("Refund already processed earlier for this request.", "warning");
            redirect("printRecord", 1500);
        }

        $u = db_fetch_array("members", "username='{$userid}'");
        if (!$u) { awal_alert_msg("User not found for auto-refund.", "error"); redirect("printRecord", 1500); }

        $amount      = $u[$cfg['fee_col']] ?? 0;
        $old_balance = $u['balance'];
        $new_balance = $old_balance + $amount;
        $order_id    = order_txn_id();

        if (db_update("members", ["balance"=>$new_balance], "username='{$userid}'")) {
            db_insert("reports", [
                'site_id'=>$u['site_id'],'user_id'=>$u['user_id'],'username'=>$u['username'],'name'=>$u['name'],
                'operator'=>$u['usertype'],'parent_id'=>$u['parent_id'],'order_id'=>$order_id,'service'=>$service,
                'type'=>"Credit",'account_number'=>$idNumber,'app_type'=>$service,'amount'=>$amount,'main_amount'=>$amount,
                'old_balance'=>$old_balance,'new_balance'=>$new_balance,'txn_id'=>$order_id,'ref_id'=>$idNumber,
                'description'=>$cfg['refund_desc']($idNumber,$amount),'date_time'=>current_timestamp(),'status'=>"Refund",
            ]);
            db_update("printRecords", ['status'=>'Refund'], "id = {$recordId}");

            $whamessage  = "Dear {$u['name']},\nYour Request for {$service} *Rejected*.\n";
            $whamessage .= "{$cfg['id_label']}: *{$idNumber}*\n";
            $whamessage .= "Reason: *{$errorMsg}*\n";
            $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}*_";
            send_sms_credentials($u['mobile'], $whamessage);

            awal_alert_msg(($errorMsg ?: "Request failed. Amount has been refunded."), "error");
            redirect("printRecord", 1500);
            exit;
        }

        awal_alert_msg("Refund failed due to wallet update error.", "error");
        redirect("printRecord", 1500);
        exit;
    }else{
    $errorMsg = $result['message'] ?? $result['error'] ?? "Server may be temporarily down.";
    awal_alert_msg($errorMsg, "error");
    redirect("printRecord", 1500);
}
}
/* ============================================================
   5) Admin manual status update (with double-refund guard)
============================================================ */
if (isset($_POST['submit']) && $_POST['status_update'] && $_POST['record_id'] && $_POST['applicationNumber'] && $_POST['userid']) {
    if (in_array($user_data['user_id'], ['1'])) { // Only Admin
        $status_update = $_POST['status_update'];
        $record_id = (int)$_POST['record_id'];
        $applicationNumber = $_POST['applicationNumber'];
        $order_id = order_txn_id();
        $amount = $_POST['amount'];
        $userid = $_POST['userid'];
        $reasonRR = $_POST['reason'] ?? '';
        $serviceName = $_POST['service'] ?? 'Unknown Service';

        $refund_user_info = db_fetch_array("members", "username = '{$userid}'");
        $old_balance = $refund_user_info['balance'];

        $record = db_fetch_array("printRecords", "id = $record_id");
        $current_status = $record['status'] ?? null;

        // Prevent double-update to same status
        if ($current_status != $status_update) {

            $insData = [
                'status' => $status_update,
            ];

            if ($status_update === 'Success' && isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
                $fileType = mime_content_type($_FILES['photo']['tmp_name']);
                if (in_array($fileType, ['application/pdf', 'image/jpeg', 'image/png'])) {
                    $fileData = file_get_contents($_FILES['photo']['tmp_name']);
                    $base64 = base64_encode($fileData);
                    $mimePrefix = "data:" . $fileType . ";base64,";
                    $insData['photo'] = $mimePrefix . $base64;
                } else {
                    echo "<div class='alert alert-danger'>Only PDF, JPEG, or PNG files are allowed.</div>";
                }

            } elseif ($status_update === 'Refund') {

                // 0) Block if already refunded by status
                if ($current_status === 'Refund') {
                    awal_alert_msg("Already Refunded, Please Don't Try Again!", 'error');
                    redirect('printRecord', 2000);
                }

                // 1) Block if refund log already exists
                $existingRefund = db_fetch_array(
                    "reports",
                    "service = '{$serviceName}' AND status = 'Refund' AND ref_id = '{$applicationNumber}' AND username = '{$userid}'"
                );
                if ($existingRefund) {
                    // Normalize record to Refund to reflect true state
                    db_update("printRecords", ['status' => 'Refund'], "id = {$record_id}");
                    awal_alert_msg("Refund already processed earlier for this request.", 'warning');
                    redirect('printRecord', 2000);
                }

                // 2) Proceed with refund
                $new_balance = $old_balance + $amount;
                $updateSuccess = db_update("members", ["balance" => $new_balance], "username='{$userid}'");

                if ($updateSuccess) {
                    $insDatarefund = [
                        'site_id'        => $refund_user_info['site_id'],
                        'user_id'        => $refund_user_info['user_id'],
                        'username'       => $refund_user_info['username'],
                        'name'           => $refund_user_info['name'],
                        'operator'       => $refund_user_info['usertype'],
                        'parent_id'      => $refund_user_info['parent_id'],
                        'order_id'       => $order_id,
                        'service'        => $serviceName,
                        'type'           => "Credit",
                        'account_number' => $applicationNumber,
                        'app_type'       => $serviceName,
                        'amount'         => $amount,
                        'main_amount'    => $amount,
                        'old_balance'    => $old_balance,
                        'new_balance'    => $new_balance,
                        'txn_id'         => $order_id,
                        'ref_id'         => $applicationNumber,
                        'description'    => "Rs.{$amount} Has Been Refunded From Wallet for $serviceName - $reasonRR Application Number",
                        'date_time'      => current_timestamp(),
                        'status'         => "Refund",
                    ];
                    db_insert("reports", $insDatarefund);
                    $insData['photo'] = "";
                }

            } else {
                $insData['photo'] = ""; // Clear photo field if not success
            }

            $insertId = db_update("printRecords", $insData, "id = $record_id");

            $whamessage = "Dear {$refund_user_info['name']},\nYour Request for $serviceName *{$applicationNumber}* has been {$status_update}.\n";
            if (!empty($reasonRR)) {
                $whamessage .= "Reason: {$reasonRR}\n";
            }
            $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}*_";
            send_sms_credentials($refund_user_info['mobile'], $whamessage);

            if ($insertId) {
                awal_alert_msg("Update Successful!", 'success');
                redirect('printRecord', 2000);
            } else {
                awal_alert_msg("Data Not Update!", 'error');
            }

        } else {
            awal_alert_msg("Already Updated To {$status_update}!", 'error');
            redirect('printRecord', 2000);
        }
    } else {
        awal_alert_msg("Unauthorized Access!", 'error');
        redirect('printRecord', 2000);
    }
}
?>

<div class="row">
<?php if (in_array($user_data['usertype'], ['Admin', 'Master Distributor', 'Distributor', 'Retailer'])) { ?>
    <div class="col-lg-12 col-md-12 col-12 mb-4 hand">
        <div class="card pmd-card hand"><?php if (isset($responseMessage)) echo $responseMessage; ?>
            <div class="card-header bg-primary text-white py-2">
                <div class="d-flex align-items-center">
                    <span class="mr-auto"><?= file_name() ?></span>
                </div>
            </div>

            <div class="card-body p-0">
                <form class="row px-4 py-3" method="POST" action="">
                    <div class="col-md-2 mb-2">
                        <label>From Date</label>
                        <input type="date" name="fromDate" value="<?= date("Y-m-d") ?>" class="form-control" required>
                    </div>
                    <div class="col-md-2 mb-2">
                        <label>To Date</label>
                        <input type="date" name="toDate" value="<?= date("Y-m-d") ?>" class="form-control" required>
                    </div>
                    <div class="col-md-2 mb-2">
                        <label>Status</label>
                        <select name="status" class="form-control">
                            <option value="">Select</option>
                            <option value="Success">Success</option>
                            <option value="Failed">Failed</option>
                            <option value="Refund">Refund</option>
                            <option value="Pending">Pending</option>
                            <option value="Process">Process</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-2">
                        <label>Search</label>
                        <input type="text" name="searchInput" placeholder="Username / Order ID / IdNumber / Etc" class="form-control">
                    </div>
                    <div class="col-md-2 mb-2">
                        <label>&nbsp;</label>
                        <button type="submit" name="search" class="btn btn-primary btn-block">Search</button>
                    </div>
                </form>

                <div class="table-responsive scroll">
                    <table class="table w-100" id="dataTable">
                        <thead>
                            <tr class="bg-secondary">
                                <th style="text-align:center;">SL No.</th>
                                <th style="text-align:center;">Order ID</th>
                                <th style="text-align:center;">Date Time</th>
                                <th style="text-align:center;">Name</th>
                                <th style="text-align:center;">ID Number</th>
                                <th style="text-align:center;">Service</th>
                                <th style="text-align:center;">Status</th>
                                <th style="text-align:center;">PRINT / ACTION</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                        $fromDate = date("Y-m-d");
                        $toDate = date("Y-m-d");
                        $status = false;
                        $searchInput = false;

                        if (isset($_POST['search'])) {
                            $fromDate = date("Y-m-d", strtotime($_POST['fromDate']));
                            $toDate = date("Y-m-d", strtotime($_POST['toDate']));
                            $status = htmlspecialchars($_POST['status']);
                            $searchInput = htmlspecialchars($_POST['searchInput']);
                        }

                        $condition = "date_time >= '$fromDate 00:00:00' AND date_time <= '$toDate 23:59:59'";
                        if (!in_array($user_data['usertype'], ['Admin'])) {
                            $condition .= " AND username = '" . $user_data['username'] . "'";
                        }
                        if (!empty($status)) {
                            $condition .= " AND status = '$status'";
                        }
                        if (!empty($searchInput)) {
                            $condition .= " AND CONCAT(`username`, `name`, `idNumber`, `order_id`, `service`, `printData`) LIKE '%$searchInput%'";
                        }

                        $records = db_fetch_all("printRecords", "$condition ORDER BY id DESC");
                        if (!$records) $records = [];

                        $sl = 1;
                        foreach ($records as $record) {
                            $record['date_time'] = date("d-M-Y h:i:s A", strtotime($record['date_time']));
                            $statusBadge = '';
                            $printdata = '';

                            if ($record['status'] === 'Success') {
                                $statusBadge = '<span class="badge badge-success">Success</span>';
                            } elseif (in_array($record['status'], ['Pending', 'Process'])) {
                                $statusBadge = '<span class="badge badge-warning">' . $record['status'] . '</span>';
                            } elseif (in_array($record['status'], ['Failed', 'Refund'])) {
                                $statusBadge = '<span class="badge badge-danger">' . $record['status'] . '</span>';
                            }

                            if (isset($printOptions[$record['service']])) {
                                $printdata = '<div class="dropdown">';
                                $printdata .= '<button class="btn btn-primary btn-sm dropdown-toggle" type="button" data-toggle="dropdown">Print Options</button>';
                                $printdata .= '<div class="dropdown-menu dropdown-menu-end">';
                                foreach ($printOptions[$record['service']] as $key => $option) {
                                    $printdata .= '<form method="POST" action="">';
                                    $printdata .= '<input type="hidden" name="service" value="' . $record['service'] . '">';
                                    $printdata .= '<input type="hidden" name="option_key" value="' . $key . '">';
                                    $printdata .= '<input type="hidden" name="token" value="' . base64_encode($record['id']) . '">';
                                    $printdata .= '<input type="hidden" name="access_token" value="' . base64_encode($record['idNumber']) . '">';
                                    $printdata .= '<input type="hidden" name="printdata" value="' . $record['printData'] . '">';
                                    $printdata .= '<button type="submit" name="print_option" class="dropdown-item">' . $option['label'] . '</button>';
                                    $printdata .= '</form>';
                                }
                                $printdata .= '</div></div>';

                            } else if (in_array($record['service'], ['LL_Request', 'add another manual services']) && $record['status'] === 'Pending' && $user_data['user_id'] == 1) {
                                $decodedJson = base64_decode($record['printData']);
                                $data = json_decode($decodedJson, true);
                                $applicationNumber = $data['applicationNumber'] ?? 'Not found';
                                $amount = $data['amount'] ?? '0';
                                $userdataname = $data['username'] ?? $user_data['username'];
                                $orderidsave = $data['order_id'] ?? 'Not Found';

                                $printdata .= '<form method="POST" action="" enctype="multipart/form-data">';
                                $printdata .= '<input type="hidden" name="userid" value="' . $userdataname . '">';
                                $printdata .= '<input type="hidden" name="record_id" value="' . $record['id'] . '">';
                                $printdata .= '<input type="hidden" name="applicationNumber" value="' . $applicationNumber . '">';
                                $printdata .= '<input type="hidden" name="amount" value="' . $amount . '">';
                                $printdata .= '<input type="hidden" name="order_id" value="' . $orderidsave . '">';
                                $printdata .= '<input type="hidden" name="service" value="' . $record['service'] . '">';
                                $printdata .= '<select name="status_update" class="form-control mb-2 status-selector" onchange="toggleFileUpload(this, ' . $record['id'] . ')">';
                                $printdata .= '<option value="" disabled selected>Select Status</option>';
                                $printdata .= '<option value="Success">Success</option>';
                                $printdata .= '<option value="Refund">Refund</option>';
                                $printdata .= '<option value="Failed">Rejected</option>';
                                $printdata .= '</select>';
                                $printdata .= '<div id="file_upload_' . $record['id'] . '" style="display:none;">';
                                $printdata .= '<input type="file" name="photo" class="form-control mb-2" accept="image/*,application/pdf">';
                                $printdata .= '</div>';
                                $printdata .= '<div id="reason_box_' . $record['id'] . '" style="display:none;">';
                                $printdata .= '<textarea name="reason" class="form-control mb-2" placeholder="Enter Reason" rows="2"></textarea>';
                                $printdata .= '</div>';
                                $printdata .= '<div class="d-flex justify-content-between mt-2">';
                                $printdata .= '<button type="submit" name="submit" class="btn btn-success btn-sm" style="width:48%;">Update</button>';
                                $printdata .= '<button type="button" class="btn btn-info btn-sm" style="width:48%;" data-toggle="modal" data-target="#detailsModal_' . $record['id'] . '">Details</button>';
                                $printdata .= '</div>';
                                $printdata .= '</form>';

                                $password = $data['password'] ?? 'N/A';
                                $dob = $data['dob'] ?? 'N/A';
                                $examsecretpin = $data['examsecretpin'] ?? '';
                                $state = $data['state'] ?? 'N/A';
                                $username = $data['username'] ?? 'N/A';
                                $printdata .= '
                                <div class="modal fade" id="detailsModal_' . $record['id'] . '" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel_' . $record['id'] . '" aria-hidden="true">
                                    <div class="modal-dialog" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header bg-primary text-white">
                                                <h5 class="modal-title">Application Details</h5>
                                                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
                                            </div>
                                            <div class="modal-body text-left">
                                                <table class="table table-bordered">
                                                    <tr><th>Application Number</th><td>' . htmlspecialchars($applicationNumber) . '</td></tr>
                                                    <tr><th>Password</th><td>' . htmlspecialchars($password) . '</td></tr>';
                                                    if (!empty($examsecretpin)) {
                                                        $printdata .= '<tr><th>Exam Pin</th><td>' . htmlspecialchars($examsecretpin) . '</td></tr>';
                                                    }
                                $printdata .= '<tr><th>DOB</th><td>' . htmlspecialchars($dob) . '</td></tr>
                                                    <tr><th>State</th><td>' . htmlspecialchars($state) . '</td></tr>
                                                    <tr><th>Username</th><td>' . htmlspecialchars($username) . '</td></tr>
                                                    <tr><th>Amount</th><td>₹' . htmlspecialchars($amount) . '</td></tr>
                                                </table>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>';

                            } else if (in_array($record['service'], ['PanUidFind_Request', 'RationUidFind_Request', 'VCM_Request'], true)) {

                                $currentService = $record['service'] ?? '';
                                $currentStatus  = $record['status'] ?? '';
                                $currentStatusLower = strtolower((string)$currentStatus);

                                /*
                                 * VCM REQUEST
                                 * Status check is handled by /members/vcmStatusCheck.php
                                 * Required POST fields: order_id, voterNumber, mobileNumber
                                 */
                                if ($currentService === 'VCM_Request') {

                                    $vcmPrintPack = pr_base64_json($record['printData'] ?? '');
                                    $vcmApiPack   = pr_base64_json($record['api_response'] ?? '');
                                    $vcmPack      = array_merge($vcmPrintPack, $vcmApiPack);

                                    $vcmOrderId = pr_first_value([
                                        $record['order_id'] ?? null,
                                        $vcmPack['order_id'] ?? null,
                                    ]);

                                    $vcmVoterNumber = pr_first_value([
                                        $record['voterNumber'] ?? null,
                                        $record['epicNumber'] ?? null,
                                        $record['voter_number'] ?? null,
                                        $vcmPack['voterNumber'] ?? null,
                                        $vcmPack['epicNumber'] ?? null,
                                        $vcmPack['voter_number'] ?? null,
                                        $record['idNumber'] ?? null,
                                    ]);

                                    $vcmMobileNumber = pr_first_value([
                                        $record['mobileNumber'] ?? null,
                                        $record['MobileNumber'] ?? null,
                                        $record['mobile_number'] ?? null,
                                        $record['mobile'] ?? null,
                                        $record['phone'] ?? null,
                                        $vcmPack['mobileNumber'] ?? null,
                                        $vcmPack['MobileNumber'] ?? null,
                                        $vcmPack['mobile_number'] ?? null,
                                        $vcmPack['mobile'] ?? null,
                                        $vcmPack['phone'] ?? null,
                                    ]);

                                    if (in_array($currentStatus, ['Process', 'Pending'], true)) {

                                        if ($vcmOrderId !== '' && $vcmVoterNumber !== '' && $vcmMobileNumber !== '') {
                                            $printdata .= '<form method="POST" action="/members/vcmStatusCheck.php" class="d-inline-block">'
                                                        . '<input type="hidden" name="order_id" value="' . pr_h($vcmOrderId) . '">'
                                                        . '<input type="hidden" name="voterNumber" value="' . pr_h($vcmVoterNumber) . '">'
                                                        . '<input type="hidden" name="mobileNumber" value="' . pr_h($vcmMobileNumber) . '">'
                                                        . '<button type="submit" class="btn btn-sm btn-warning">'
                                                        . '<span class="oi oi-media-record pulse mr-1"></span> Check VCM Status'
                                                        . '</button>'
                                                        . '</form>';
                                        } else {
                                            $missingModalId = 'vcm_missing_' . (int)$record['id'];

                                            $printdata .= '<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#' . pr_h($missingModalId) . '">VCM Data Missing</button>';

                                            $printdata .= '<div class="modal fade" id="' . pr_h($missingModalId) . '" tabindex="-1" role="dialog">'
                                                        . '  <div class="modal-dialog modal-sm" role="document"><div class="modal-content">'
                                                        . '    <div class="modal-header bg-danger text-white"><h5 class="modal-title">VCM Status Check Error</h5>'
                                                        . '    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>'
                                                        . '    <div class="modal-body text-left">'
                                                        . '      <p class="mb-1"><strong>Order ID:</strong> ' . pr_h($vcmOrderId ?: 'Missing') . '</p>'
                                                        . '      <p class="mb-1"><strong>Voter Number:</strong> ' . pr_h($vcmVoterNumber ?: 'Missing') . '</p>'
                                                        . '      <p class="mb-0"><strong>Mobile Number:</strong> ' . pr_h($vcmMobileNumber ?: 'Missing') . '</p>'
                                                        . '      <hr><small class="text-muted">VCM status check requires order_id, voterNumber and mobileNumber.</small>'
                                                        . '    </div>'
                                                        . '    <div class="modal-footer"><button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button></div>'
                                                        . '  </div></div></div>';
                                        }

                                    } elseif (in_array($currentStatusLower, ['success', 'refund', 'refunded'], true)) {

                                        $modalId = 'vcm_details_' . (int)$record['id'];

                                        $vcmName = pr_first_value([
                                            $vcmPack['name'] ?? null,
                                            $record['name'] ?? null,
                                        ]);

                                        $vcmFinalStatus = pr_first_value([
                                            $vcmPack['statusMessage'] ?? null,
                                            $vcmPack['status'] ?? null,
                                            $record['status'] ?? null,
                                        ]);

                                        $vcmUsername = pr_first_value([
                                            $vcmPack['username'] ?? null,
                                            $record['username'] ?? null,
                                        ]);

                                        $btnClass = in_array($currentStatusLower, ['refund', 'refunded'], true) ? 'btn-danger' : 'btn-success';
                                        $btnText  = in_array($currentStatusLower, ['refund', 'refunded'], true) ? 'View Refund Details' : 'View VCM Details';

                                        $printdata .= '<button type="button" class="btn btn-sm ' . $btnClass . '" data-toggle="modal" data-target="#' . pr_h($modalId) . '">' . pr_h($btnText) . '</button>';

                                        $printdata .= '<div class="modal fade" id="' . pr_h($modalId) . '" tabindex="-1" role="dialog">'
                                                    . '  <div class="modal-dialog modal-sm" role="document"><div class="modal-content">'
                                                    . '    <div class="modal-header bg-primary text-white"><h5 class="modal-title">VCM Details</h5>'
                                                    . '    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>'
                                                    . '    <div class="modal-body text-left">'
                                                    . '      <p><strong>Order ID:</strong> ' . pr_h($vcmOrderId) . '</p>'
                                                    . '      <p><strong>Voter Number:</strong> ' . pr_h($vcmVoterNumber) . '</p>'
                                                    . '      <p><strong>Name:</strong> ' . pr_h($vcmName) . '</p>'
                                                    . '      <p><strong>Mobile:</strong> ' . pr_h($vcmMobileNumber) . '</p>'
                                                    . '      <p><strong>Status:</strong> ' . pr_h(ucwords($vcmFinalStatus)) . '</p>'
                                                    . '      <p><strong>Username:</strong> ' . pr_h($vcmUsername) . '</p>'
                                                    . '    </div>'
                                                    . '    <div class="modal-footer"><button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button></div>'
                                                    . '  </div></div></div>';

                                    } else {
                                        $printdata .= '<span class="text-muted">No action available</span>';
                                    }

                                } else {

                                    // PAN UID / RATION UID Processing → Check Status
                                    if (in_array($currentStatus, ['Process', 'Pending'], true)) {
                                        $printdata .= '<form method="POST" action="" class="d-inline-block">'
                                                    . '<input type="hidden" name="service" value="' . pr_h($currentService) . '">'
                                                    . '<input type="hidden" name="id" value="' . (int)$record['id'] . '">'
                                                    . '<button type="submit" class="btn btn-sm btn-warning">Check Status</button>'
                                                    . '</form>';
                                    }

                                    // PAN UID / RATION UID Success → modal
                                    if ($currentStatus === 'Success') {
                                        $pack = pr_base64_json($record['printData'] ?? '');

                                        if ($currentService === 'PanUidFind_Request') {
                                            $modalId = 'uid_pan_' . (int)$record['id'];

                                            $printdata .= '<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#' . pr_h($modalId) . '">View Details</button>';
                                            $printdata .= '<div class="modal fade" id="' . pr_h($modalId) . '" tabindex="-1" role="dialog">'
                                                        . '  <div class="modal-dialog modal-sm" role="document"><div class="modal-content">'
                                                        . '    <div class="modal-header bg-primary text-white"><h5 class="modal-title">UID Details</h5>'
                                                        . '    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>'
                                                        . '    <div class="modal-body text-left">'
                                                        . '      <p><strong>PAN:</strong> ' . pr_h($pack['panNumber'] ?? '') . '</p>'
                                                        . '      <p><strong>Name:</strong> ' . pr_h($pack['name'] ?? '') . '</p>'
                                                        . '      <p><strong>UID:</strong> ' . pr_h($pack['uid'] ?? '') . '</p>'
                                                        . '      <p><strong>DOB:</strong> ' . pr_h($pack['dob'] ?? '') . '</p>'
                                                        . '      <p><strong>Gender:</strong> ' . pr_h($pack['gender'] ?? '') . '</p>'
                                                        . '    </div>'
                                                        . '    <div class="modal-footer"><button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button></div>'
                                                        . '  </div></div></div>';
                                        } else {
                                            $modalId = 'uid_ration_' . (int)$record['id'];
                                            $ration = pr_h($pack['rationNumber'] ?? $record['idNumber']);
                                            $rows   = (isset($pack['data']) && is_array($pack['data'])) ? $pack['data'] : [];
                                            $count  = (int)($pack['count'] ?? count($rows));

                                            $printdata .= '<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#' . pr_h($modalId) . '">View UID List (' . $count . ')</button>';
                                            $printdata .= '<div class="modal fade" id="' . pr_h($modalId) . '" tabindex="-1" role="dialog">'
                                                        . '  <div class="modal-dialog" role="document"><div class="modal-content">'
                                                        . '    <div class="modal-header bg-primary text-white"><h5 class="modal-title">Ration UID(s) — ' . $ration . '</h5>'
                                                        . '    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>'
                                                        . '    <div class="modal-body text-left">';
                                            if (!empty($rows)) {
                                                $printdata .= '<div class="table-responsive"><table class="table table-bordered mb-0"><thead><tr><th>Name</th><th>UID</th></tr></thead><tbody>';
                                                foreach ($rows as $r) {
                                                    $printdata .= '<tr><td>' . pr_h($r['name'] ?? '') . '</td><td>' . pr_h($r['uidNumber'] ?? '') . '</td></tr>';
                                                }
                                                $printdata .= '</tbody></table></div>';
                                            } else {
                                                $printdata .= '<div class="text-muted">No UID entries returned.</div>';
                                            }
                                            $printdata .= '    </div><div class="modal-footer"><button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button></div>'
                                                        . '  </div></div></div>';
                                        }
                                    }
                                }

                            } elseif ($record['service'] === 'NSDL_PAN') {
                                if (in_array($record['status'], ['Process', 'Pending'], true)) {
                                    $dropdownId = 'statusDropdown' . (int)$record['id'];
                                    $printdata .= '<div class="dropdown d-inline-block">'
                                        . '<button class="btn btn-primary btn-sm dropdown-toggle" type="button" id="' . pr_h($dropdownId) . '" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'
                                        . '<span class="oi oi-media-record pulse mr-1"></span> Check Status'                                        . '</button>'
                                        . '<div class="dropdown-menu dropdown-menu-sm" aria-labelledby="' . pr_h($dropdownId) . '">'
                                        . '<form method="POST" action="https://' . pr_h(baseurl()) . '/members/incompletePan">'
                                        . '<input type="hidden" name="order_id" value="' . pr_h($record['order_id']) . '">'
                                        . '<button type="submit" class="dropdown-item py-1 px-2">Incomplete Pan</button>'
                                        . '</form>'
                                        . '<form method="POST" action="https://' . pr_h(baseurl()) . '/members/nsdlApplicationStatus">'
                                        . '<input type="hidden" name="order_id" value="' . pr_h($record['order_id']) . '">'
                                        . '<button type="submit" class="dropdown-item py-1 px-2">Application Status</button>'
                                        . '</form>'
                                        . '</div></div>';
                                } elseif ($record['status'] === 'Success' && !empty($record['photo'])) {
                                    $photoData = (string)$record['photo'];
                                    if (preg_match('/^data:(application\\/pdf|image\\/jpeg|image\\/png);base64,/', $photoData, $matches)) {
                                        $extensions = [
                                            'application/pdf' => 'pdf',
                                            'image/jpeg' => 'jpg',
                                            'image/png' => 'png',
                                        ];
                                        $extension = $extensions[strtolower($matches[1])] ?? '';
                                        $downloadName = preg_replace('/[^a-zA-Z0-9_-]/', '_', $record['service'])
                                            . '_' . (int)$record['id'] . '.' . $extension;
                                        $printdata .= '<a href="' . pr_h($photoData) . '" class="btn btn-sm btn-primary" download="' . pr_h($downloadName) . '">Download File</a>';
                                    } else {
                                        $printdata .= '<span class="text-danger">Invalid Format</span>';
                                    }
                                } else {
                                    $printdata .= '<span class="text-muted">No action available</span>';
                                }

                            } elseif ($record['service'] === 'PAN PRINT' && $record['status'] === 'Success') {
                                $printdata .= '<a href="basep/ePan-PDF?M0peiXzhJkM0eiXzhJkR=' . rawurlencode(base64_encode($record['id'])) . '" class="btn btn-sm btn-primary" target="_blank">Print PDF</a>';

} elseif (
    in_array($record['service'], ['Aadhar Manual', 'Aadhar_FingerPrint', 'AADHAR_OTP'], true) &&
    $record['status'] === 'Success'
) {
    $encryptedSearchId = encryptSearchId(
        (string)$record['id']
    );

    if ($encryptedSearchId !== false) {
        $printUrl = 'basea/eAadhaar-PDF?UB8RM0X3pIs0peiXzhJkREd7YHrSLG0oqTwRYfqH0q='
            . rawurlencode($encryptedSearchId);

        $printdata .= '<a href="'
            . pr_h($printUrl)
            . '" class="btn btn-sm btn-primary"'
            . ' target="_blank" rel="noopener noreferrer">'
            . 'Print PDF</a>';
    } else {
        $printdata .= '<span class="text-danger">'
            . 'Unable to encrypt print record ID'
            . '</span>';
    }

                            } elseif ($record['service'] === 'VOTER PRINT' && $record['status'] === 'Success') {
                                $printdata .= '<a href="basev/eVoter-PDF?U3pIsKJHHLIU876fh3y37HrSLG0oqTwRYfqH0q=' . rawurlencode(base64_encode($record['id'])) . '" class="btn btn-sm btn-primary" target="_blank">Print PDF</a>';

                            } elseif ($record['status'] === 'Success' && !empty($record['photo'])) {
                                $photoData = (string)$record['photo'];
                                if (preg_match('/^data:(application\\/pdf|image\\/jpeg|image\\/png);base64,/', $photoData, $matches)) {
                                    $extensions = [
                                        'application/pdf' => 'pdf',
                                        'image/jpeg' => 'jpg',
                                        'image/png' => 'png',
                                    ];
                                    $extension = $extensions[strtolower($matches[1])] ?? '';
                                    $downloadName = preg_replace('/[^a-zA-Z0-9_-]/', '_', $record['service'])
                                        . '_' . (int)$record['id'] . '.' . $extension;
                                    $printdata .= '<a href="' . pr_h($photoData) . '" class="btn btn-sm btn-primary" download="' . pr_h($downloadName) . '">Download File</a>';
                                } else {
                                    $printdata .= '<span class="text-danger">Invalid Format</span>';
                                }

                            } else {
                                $printdata .= '<span class="text-muted">No action available</span>';
                            }

                            echo '<tr style="text-align:center;">';
                            echo '<td>' . (int)$sl . '</td>';
                            echo '<td>' . pr_h($record['order_id'] ?? '') . '</td>';
                            echo '<td>' . pr_h($record['date_time'] ?? '') . '</td>';
                            echo '<td>' . pr_h($record['name'] ?? '') . '</td>';
                            echo '<td>' . pr_h($record['idNumber'] ?? '') . '</td>';
                            echo '<td>' . pr_h($record['service'] ?? '') . '</td>';
                            echo '<td>' . $statusBadge . '</td>';
                            echo '<td>' . $printdata . '</td>';
                            echo '</tr>';

                            $sl++;
                        }
                        ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

<script>
function toggleFileUpload(selectEl, id) {
    const fileDiv = document.getElementById('file_upload_' + id);
    const reasonDiv = document.getElementById('reason_box_' + id);

    if (selectEl.value === 'Success') {
        fileDiv.style.display = 'block';
        reasonDiv.style.display = 'none';
        fileDiv.querySelector('input[type="file"]').required = true;
        const t = reasonDiv.querySelector('textarea'); if (t) t.removeAttribute('required');
    } else if (selectEl.value === 'Refund' || selectEl.value === 'Failed') {
        fileDiv.style.display = 'none';
        reasonDiv.style.display = 'block';
        reasonDiv.querySelector('textarea').required = true;
        fileDiv.querySelector('input[type="file"]').required = false;
    } else {
        fileDiv.style.display = 'none';
        reasonDiv.style.display = 'none';
        fileDiv.querySelector('input[type="file"]').required = false;
        const t = reasonDiv.querySelector('textarea'); if (t) t.removeAttribute('required');
    }
}
</script>

<?php } else { require_once("404.php"); } ?>
</div>

<?php
require_once("../layouts/members/foot.php"); 
data_table('#dataTable');
?>