<?php
require 'config.php';
require_login();

// Fetch Cost
$cost_api1 = (float)($settings['smartcard_cost'] ?? 40);

// Fetch History
$stmt = $pdo->prepare("SELECT * FROM server_copy WHERE user_id = ? ORDER BY id DESC LIMIT 20");
$stmt->execute([$_SESSION['user_id']]);
$history = $stmt->fetchAll();

require_once 'header.php';
?>

<style>
    /* -------------------------------------------------------------------------
       GOVERNMENT LIGHT THEME STYLES
       ------------------------------------------------------------------------- */
    :root {
        --gov-green: #006a4e;
        --gov-red: #f42a41;
        --gov-bg: #f0f2f5;
        --card-border: #d1d5db;
    }

    body {
        background-color: var(--gov-bg);
    }

    /* Loading Overlay */
    #loddingPdf {
        position: fixed;
        inset: 0;
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(8px);
        z-index: 9999;
        display: none;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    .spinner-ring {
        width: 60px; height: 60px;
        border: 5px solid #e2e8f0;
        border-left-color: var(--gov-green);
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    @keyframes spin { 100% { transform: rotate(360deg); } }

    /* Gov Card Design */
    .gov-card {
        background: #ffffff;
        border-radius: 8px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        border: 1px solid var(--card-border);
        overflow: hidden;
    }

    .gov-card-header {
        background: var(--gov-green);
        color: white;
        padding: 15px 20px;
        font-weight: 700;
        border-bottom: 3px solid var(--gov-red);
    }

    .form-content {
        padding: 30px;
    }

    .cost-badge {
        background: #e6f4f1;
        color: var(--gov-green);
        padding: 8px 15px;
        border-radius: 5px;
        font-weight: 700;
        display: inline-block;
        margin-bottom: 20px;
        border: 1px solid #b2dfdb;
    }

    /* Form Elements */
    .gov-label {
        font-weight: 600;
        color: #334155;
        font-size: 0.9rem;
        margin-bottom: 8px;
        display: block;
    }

    .gov-input {
        background: #ffffff;
        border: 1px solid #cbd5e1;
        color: #1e293b;
        padding: 12px 15px;
        border-radius: 6px;
        width: 100%;
        transition: 0.3s;
    }
    .gov-input:focus {
        border-color: var(--gov-green);
        box-shadow: 0 0 0 3px rgba(0, 106, 78, 0.1);
        outline: none;
    }

    .btn-gov-submit {
        background: var(--gov-green);
        color: white;
        border: none;
        padding: 12px 25px;
        border-radius: 6px;
        font-weight: 700;
        transition: 0.3s;
        width: 100%;
    }
    .btn-gov-submit:hover {
        background: #004d39;
        box-shadow: 0 4px 10px rgba(0, 106, 78, 0.2);
    }

    /* History Table */
    .table-gov {
        width: 100%;
        background: white;
        border-collapse: collapse;
    }
    .table-gov thead {
        background: #f8fafc;
    }
    .table-gov th {
        padding: 15px;
        color: #475569;
        font-weight: 700;
        font-size: 0.85rem;
        text-transform: uppercase;
        border-bottom: 2px solid #e2e8f0;
    }
    .table-gov td {
        padding: 15px;
        color: #1e293b;
        border-bottom: 1px solid #f1f5f9;
        vertical-align: middle;
    }
    .table-gov tr:hover td { background: #f1f5f9; }

    .nid-pill {
        background: #f1f5f9;
        color: #475569;
        padding: 4px 10px;
        border-radius: 4px;
        font-family: monospace;
        font-weight: 600;
        border: 1px solid #e2e8f0;
    }

    .btn-download-pdf {
        background: var(--gov-red);
        color: white;
        padding: 8px 12px;
        border-radius: 5px;
        text-decoration: none;
        font-size: 0.85rem;
        font-weight: 600;
        transition: 0.2s;
    }
    .btn-download-pdf:hover {
        background: #d92135;
        color: white;
    }

    @media (max-width: 768px) {
        .table-gov thead { display: none; }
        .table-gov tr { display: block; border-bottom: 10px solid #f0f2f5; }
        .table-gov td {
            display: flex; justify-content: space-between;
            padding: 10px 15px; border: none;
        }
        .table-gov td::before {
            content: attr(data-label);
            font-weight: 700; color: #64748b;
        }
    }
</style>

<div id="loddingPdf">
    <div class="spinner-ring mb-3"></div>
    <h5 class="fw-bold text-dark">প্রসেসিং হচ্ছে...</h5>
    <p class="text-muted">দয়া করে অপেক্ষা করুন, পেজটি রিলোড করবেন না</p>
</div>

<div class="row g-4 justify-content-center">
    
    <div class="col-lg-8">
        <div class="gov-card mb-4">
            <div class="gov-card-header">
                <i class="fas fa-id-card me-2"></i> সার্ভার কপি অনুসন্ধান ফরম
            </div>
            <div class="form-content">
                <div class="text-center">
                    <div class="cost-badge">
                        <i class="fas fa-coins me-1"></i> চার্জ: ৳ <?php echo number_format($cost_api1, 0); ?>
                    </div>
                </div>

                <form id="serverCopyForm" autocomplete="off">
                    <div class="row g-4">
                        <div class="col-md-6">
                            <label class="gov-label">জাতীয় পরিচয়পত্র নম্বর (NID)</label>
                            <input type="tel" name="nid" id="nidNumber" 
                                   class="gov-input" 
                                   placeholder="১০ অথবা ১৭ ডিজিট" 
                                   maxlength="17" required>
                        </div>
                        <div class="col-md-6">
                            <label class="gov-label">জন্ম তারিখ (YYYY-MM-DD)</label>
                            <input type="tel" name="dob" id="dateOfBirth" 
                                   class="gov-input" 
                                   placeholder="উদাহরণ: 1990-12-31" 
                                   maxlength="10" required>
                        </div>
                        
                        <div class="col-12 mt-4">
                            <button type="submit" id="submitButton" class="btn-gov-submit">
                                তথ্য অনুসন্ধান করুন <i class="fas fa-search ms-2"></i>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="gov-card">
            <div class="gov-card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-history me-2"></i> সাম্প্রতিক অনুসন্ধানের রেকর্ড</span>
                <span class="badge bg-light text-dark"><?php echo count($history); ?> টি</span>
            </div>
            <div class="table-responsive">
                <?php if ($history): ?>
                    <table class="table-gov">
                        <thead>
                            <tr>
                                <th>নাম (ইংরেজি)</th>
                                <th>NID নম্বর</th>
                                <th>তারিখ ও সময়</th>
                                <th class="text-end">অ্যাকশন</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($history as $item): ?>
                                <tr>
                                    <td data-label="নাম" class="fw-bold">
                                        <?php echo htmlspecialchars($item['nameEn'] ?? $item['nameBn'] ?? 'Unknown'); ?>
                                    </td>
                                    <td data-label="NID">
                                        <span class="nid-pill"><?php echo htmlspecialchars($item['nationalId']); ?></span>
                                    </td>
                                    <td data-label="সময়">
                                        <small class="text-muted"><?php echo date('d/m/Y h:i A', strtotime($item['created_at'])); ?></small>
                                    </td>
                                    <td data-label="ডাউনলোড" class="text-end">
                                        <a href="non_addess_down.php?id=<?php echo $item['id']; ?>" class="btn-download-pdf" target="_blank">
                                            <i class="fas fa-file-pdf me-1"></i> PDF
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="text-center py-5">
                        <i class="fas fa-folder-open fa-3x text-light mb-3"></i>
                        <p class="text-muted mb-0">এখনো পর্যন্ত কোনো রেকর্ড পাওয়া যায়নি</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('serverCopyForm');
    const loading = document.getElementById('loddingPdf');
    const nidInput = document.getElementById('nidNumber');
    const dobInput = document.getElementById('dateOfBirth');

    // Date Auto-format YYYY-MM-DD
    dobInput.addEventListener('input', function(e) {
        let v = this.value.replace(/\D/g, ''); 
        if (v.length > 8) v = v.substring(0, 8);
        if (v.length > 4) v = v.substring(0, 4) + '-' + v.substring(4);
        if (v.length > 7) v = v.substring(0, 7) + '-' + v.substring(7);
        this.value = v;
    });

    nidInput.addEventListener('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '');
    });

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const nid = nidInput.value.trim();
        const dob = dobInput.value.trim();

        if (nid.length !== 10 && nid.length !== 17) {
            Swal.fire({ icon: 'error', title: 'ত্রুটি!', text: 'NID নম্বর ১০ অথবা ১৭ ডিজিট হতে হবে' });
            return;
        }

        Swal.fire({
            title: 'নিশ্চিত করুন',
            text: `সার্ভার কপির জন্য আপনার ব্যালেন্স থেকে ৳${<?php echo $cost_api1; ?>} চার্জ করা হবে।`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#006a4e',
            cancelButtonColor: '#f42a41',
            confirmButtonText: 'হ্যাঁ, সাবমিট করুন',
            cancelButtonText: 'বাতিল'
        }).then((result) => {
            if (result.isConfirmed) {
                loading.style.display = 'flex';
                
                fetch('non_addess_handle.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ nid, dob, version: '1' })
                })
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'সফল!',
                            text: 'তথ্য খুঁজে পাওয়া গেছে।'
                        }).then(() => location.reload());
                    } else {
                        Swal.fire({ icon: 'error', title: 'ব্যর্থ!', text: data.message || 'সার্ভারে সমস্যা হয়েছে।' });
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    Swal.fire({ icon: 'error', title: 'ত্রুটি!', text: 'একটি অপ্রত্যাশিত সমস্যা হয়েছে।' });
                });
            }
        });
    });
});
</script>

<?php require_once 'footer.php'; ?>