<?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,
    ];
}

/* ============================================================
   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'], true)) {
                                // Processing → Check Status
                                if (in_array($record['status'], ['Process','Pending'], true)) {
                                    $printdata .= '<form method="POST" action="">'
                                                . '<input type="hidden" name="service" value="' . htmlspecialchars($record['service']) . '">'
                                                . '<input type="hidden" name="id" value="' . (int)$record['id'] . '">'
                                                . '<button type="submit" class="btn btn-sm btn-warning">Check Status</button>'
                                                . '</form>';
                                }
                                // Success → modal
                                if ($record['status'] === 'Success') {
                                    $pack = json_decode(base64_decode($record['printData']), true) ?: [];
                                    if ($record['service'] === 'PanUidFind_Request') {
                                        $printdata .= '<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#uid_pan_' . $record['id'] . '">View Details</button>';
                                        $printdata .= '<div class="modal fade" id="uid_pan_' . $record['id'] . '" 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> ' . htmlspecialchars($pack['panNumber'] ?? '') . '</p>'
                                                    . '      <p><strong>Name:</strong> ' . htmlspecialchars($pack['name'] ?? '') . '</p>'
                                                    . '      <p><strong>UID:</strong> ' . htmlspecialchars($pack['uid'] ?? '') . '</p>'
                                                    . '      <p><strong>DOB:</strong> ' . htmlspecialchars($pack['dob'] ?? '') . '</p>'
                                                    . '      <p><strong>Gender:</strong> ' . htmlspecialchars($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 {
                                        $ration = htmlspecialchars($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="#uid_ration_' . $record['id'] . '">View UID List (' . $count . ')</button>';
                                        $printdata .= '<div class="modal fade" id="uid_ration_' . $record['id'] . '" 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>' . htmlspecialchars($r['name'] ?? '') . '</td><td>' . htmlspecialchars($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>';
                                    }
                                }
                                } else if (in_array($record['service'], ['NSDL_PAN',''], true)) {
                                     if (in_array($record['status'], ['Process','Pending'], true)) {
                                        $printdata .= '
                                           <div class="dropdown d-inline-block">
                                             <button class="btn btn-primary btn-sm dropdown-toggle" 
                                                     type="button" 
                                                     id="statusDropdown' . $record['order_id'] . '" 
                                                     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="statusDropdown' . $record['order_id'] . '">
       
                                               <form method="POST" action="https://' . baseurl() . '/members/incompletePan">
                                                 <input type="hidden" name="order_id" value="' . $record['order_id'] . '">
                                                 <button type="submit" class="dropdown-item py-1 px-2">Incomplete Pan</button>
                                               </form>
    
                                               <form method="POST" action="https://' . baseurl() . '/members/nsdlApplicationStatus">
                                                 <input type="hidden" name="order_id" value="' . $record['order_id'] . '">
                                                 <button type="submit" class="dropdown-item py-1 px-2">Application Status</button>
                                               </form>
                                               
                                             </div>
                                           </div>';
                                }

                            } else if ($record['status'] === 'Success' && !empty($record['photo']) && strpos($record['photo'], 'base64') !== false) {
                                $fileType = explode(';', explode(':', $record['photo'])[1])[0];
                                if (in_array($fileType, ['application/pdf', 'image/jpeg', 'image/png'])) {
                                    $extension = ($fileType === 'application/pdf') ? 'pdf' : (($fileType === 'image/jpeg') ? 'jpg' : 'png');
                                    $printdata .= '<a href="' . $record['photo'] . '" class="btn btn-sm btn-primary" download="' . $record['service'] . '_' . $record['id'] . '.' . $extension . '" target="_blank">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>{$sl}</td>";
                            echo "<td>{$record['order_id']}</td>";
                            echo "<td>{$record['date_time']}</td>";
                            echo "<td>{$record['name']}</td>";
                            echo "<td>{$record['idNumber']}</td>";
                            echo "<td>{$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');
?>
