<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');

// Helper fallbacks (if not defined elsewhere in your app)
if (!function_exists('getSafe')) {
    function getSafe($v) { return is_string($v) ? trim($v) : $v; }
}
if (!function_exists('showAlert')) {
    function showAlert($title, $text = '', $type = 'info') {
        $t = addslashes($title); $s = addslashes($text);
        echo "<script>console.log('ALERT: {$t} - {$s} - {$type}');</script>";
    }
}
?>
<div class="page-wrapper">
    <div class="page-content">
        <!-- Breadcrumb with Action Buttons -->
        <div class="page-breadcrumb d-flex align-items-center justify-content-between mb-4 p-3 bg-white rounded shadow-sm">
            <div class="d-flex align-items-center">
                <div class="breadcrumb-title pe-3">History</div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 ps-2">
                        <li class="breadcrumb-item active text-muted" aria-current="page">Learning Licence List</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <a href="ll_request" class="btn btn-success">
                    <i class="bi bi-list-ul me-1"></i> New Apply
                </a>
                <a href="javascript:history.back()" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>
        <div class="card radius-10">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div>
                        <h5 class="mb-0">LL TEST REQUEST LIST</h5>
                    </div>
                </div>
                <hr>
                <div class="table-responsive">
                    <table id="example2" class="table align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="text-center">#</th>
                                <th class="text-center">Application No</th>
                                <th class="text-center">Date of Birth</th>
                                <th class="text-center">Password</th>
                                <th class="text-center">Exam Date</th>
                                <th class="text-center">Fee</th>
                                <th class="text-center">Aadhaar / Status</th>
                                <th class="text-center">Result</th>
                            </tr>
                        </thead>
                        <tbody>
<?php

// Optional: tracking flow (keeps your previous behaviour if used)
if (isset($_GET['apid']) && isset($_GET['track']) && $_GET['track'] === 'true') {
    $apid_raw = getSafe($_GET['apid']);
    $application_no = $apid_raw;
    $maybe_decoded = @base64_decode($apid_raw, true);
    if ($maybe_decoded !== false && $maybe_decoded !== $apid_raw) $application_no = $maybe_decoded;

    $api_key = isset($webdata['nsdl_api_key']) ? $webdata['nsdl_api_key'] : '';
    if (!empty($api_key) && !empty($application_no)) {
        // Replace with your actual tracking endpoint
        $url = 'https://your-domain.example/api/v1/services/aadhaar_pdf/track_pdf.php?application_no=' . urlencode($application_no) . '&api_key=' . urlencode($api_key);

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
        ]);
        $response = curl_exec($curl);
        $curl_err = curl_error($curl);
        curl_close($curl);

        if ($curl_err) {
            showAlert('Tracking Error', $curl_err, 'error');
        } else {
            $resdata = json_decode($response, true);
            if (is_array($resdata) && isset($resdata['status'])) {
                if ((string)$resdata['status'] === '1') {
                    $apid_for_db     = mysqli_real_escape_string($ahk_conn, $application_no);
                    $aadhaar_no_new  = isset($resdata['aadhaar_no']) ? mysqli_real_escape_string($ahk_conn, $resdata['aadhaar_no']) : '';
                    $pdf_link_new    = isset($resdata['pdf_link']) ? mysqli_real_escape_string($ahk_conn, $resdata['pdf_link']) : '';
                    $upd_sql = "UPDATE larning_exam SET aadhaar_no = '$aadhaar_no_new', status = 'success', pdf_link = '$pdf_link_new' WHERE application_no = '$apid_for_db' LIMIT 1";
                    if (mysqli_query($ahk_conn, $upd_sql)) {
                        showAlert('Aadhaar PDF generated', $resdata['aadhaar_no'] ?? '', 'success');
                    } else {
                        showAlert('DB Update Failed', mysqli_error($ahk_conn), 'error');
                    }
                } else {
                    $msg = $resdata['message'] ?? 'Unknown response';
                    showAlert('Tracking Failed', $msg, 'error');
                }
            } else {
                showAlert('Invalid tracking response', $response, 'error');
            }
        }
    } else {
        showAlert('Missing API key or application number', '', 'error');
    }
}

// Fetch applications for the logged-in user
$phone = isset($udata['phone']) ? mysqli_real_escape_string($ahk_conn, $udata['phone']) : '';
$res = mysqli_query($ahk_conn, "SELECT * FROM larning_exam WHERE appliedby = '$phone' ORDER BY id DESC");
if ($res && mysqli_num_rows($res) > 0) {
    $x = 0;
    while ($data = mysqli_fetch_assoc($res)) {
        $x++;
        // Normalize & sanitize fields
        $status_raw = isset($data['status']) ? $data['status'] : '';
        $status = strtolower(trim($status_raw));
        $name = isset($data['name']) ? htmlspecialchars($data['name']) : '';
        $rasan_no = isset($data['rasan_no']) ? htmlspecialchars($data['rasan_no']) : '';
        $dob = isset($data['date']) ? htmlspecialchars($data['date']) : '';
        $apply_date = isset($data['apply_date']) ? htmlspecialchars($data['apply_date']) : '';
        $fee = isset($data['fee']) ? htmlspecialchars($data['fee']) : '';
        $aadhaar_no = isset($data['aadhaar_no']) ? htmlspecialchars($data['aadhaar_no']) : '';
        $pdf_link = isset($data['pdf_link']) ? htmlspecialchars($data['pdf_link']) : '';

        $is_cancelled = ($status === 'cancelled' || $status === 'refunded');
        $is_success = ($status === 'success');
        ?>
        <tr>
            <td class="text-center"><?= $x; ?></td>

            <td class="text-center">
                <div class="d-flex align-items-center">
                    <div class="ms-2">
                        <h6 class="mb-1 font-14"><?php echo strtoupper($name); ?></h6>
                    </div>
                </div>
            </td>

            <td class="text-center"><?php echo strtoupper($rasan_no); ?></td>
            <td class="text-center"><?php echo strtoupper($dob); ?></td>
            <td class="text-center"><?php echo strtoupper($apply_date); ?></td>

            <td class="text-center"><?php echo strtoupper($fee); ?></td>

            <!-- Aadhaar / Status column -->
            <td class="text-center">
                <?php
                if ($is_cancelled) {
                    // Cancelled: show Cancelled badge only
                    echo '<div class="badge rounded-pill bg-light-danger text-danger w-100">Cancelled</div>';
                } elseif ($is_success) {
                    // Success: show Aadhaar number if available + Success badge
                    if (!empty($aadhaar_no)) {
                        echo '<div>' . strtoupper($aadhaar_no) . '</div>';
                    } else {
                        echo '<div class="text-muted">-</div>';
                    }
                    echo '<div class="mt-1"><span class="badge rounded-pill bg-light-success text-success">Success</span></div>';
                } else {
                    // Pending or other statuses
                    if (!empty($aadhaar_no)) {
                        echo strtoupper($aadhaar_no);
                    } else {
                        echo '<div class="badge rounded-pill bg-light-warning text-warning w-100">Pending...</div>';
                    }
                }
                ?>
            </td>

            <!-- Result column -->
            <td class="text-center">
                <?php
                if ($is_cancelled) {
                    echo '<div class="badge rounded-pill bg-light-danger text-danger">Cancelled</div>';
                } elseif ($is_success) {
                    // Only show download when status == success and pdf_link exists
                    if (!empty($pdf_link)) {
                        ?>
                        <div class="text-center">
                            <a download="<?php echo $aadhaar_no ?: 'aadhaar'; ?>"
                               href="<?php echo $pdf_link; ?>"
                               class="btn btn-sm btn-success" target="_blank" rel="noopener">
                                View Certificate
                            </a>
                        </div>
                        <?php
                    } else {
                        echo '<div class="badge rounded-pill bg-light-success text-success">Generated</div>';
                    }
                } elseif ($status === 'pending' || $status === '1' || $status === '') {
                    echo '<div class="badge rounded-pill bg-light-warning text-warning">Pending</div>';
                } else {
                    echo '<div class="badge rounded-pill bg-secondary">' . strtoupper(htmlspecialchars($data['status'])) . '</div>';
                }
                ?>
            </td>
        </tr>
        <?php
    }
} else {
    echo '<tr><td colspan="8" class="text-center">No records found.</td></tr>';
}
?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
</div>
<!-- end page wrapper -->
<?php
include('footer.php');
?>
