<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');

// Fix Database Encoding
mysqli_set_charset($conn, "utf8mb4");

require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$utype = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? 'Retailer';

// Fetch Logs
$filter = ($utype == 'TitanAdmin') ? "" : "WHERE user_id = '$uid'";
$query = "SELECT * FROM ration_to_aadhar_find $filter ORDER BY id DESC";
$result = $conn->query($query);
?>

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-success-subtle shadow-none me-3">
                        <span class="fas fa-list text-success fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-success fs-10 mb-0">History Log</h6>
                        <h4 class="text-primary fw-bold mb-0">Ration To Aadhar <span class="fw-medium">Find Records</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="Ration_To_Uid.php" class="btn btn-sm btn-success shadow-none fw-bold">
                        <i class="fas fa-search me-1"></i> Search New Ration
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3 border-0 shadow-sm border-top border-4 border-success">
    <div class="card-body p-0">
        <div class="table-responsive scrollbar">
            <table class="table table-sm table-striped fs-10 mb-0 text-center align-middle">
                <thead class="bg-200 text-900">
                    <tr>
                        <th class="py-2">#ID</th>
                        <th>Ration No.</th>
                        <th>Transaction ID</th>
                        <th>Total Members</th>
                        <th>Status</th>
                        <th>Date & Time</th>
                        <th class="text-end pe-4">Action</th>
                    </tr>
                </thead>
                <tbody class="list">
                    <?php if($result && $result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): 
                            // Decode structure to pull member metrics
                            $raw_member_data = $row['member_data'] ?? '[]';
                            $members = json_decode($raw_member_data, true);
                            $total_members = is_array($members) ? count($members) : 0;
                            
                            $secure_json_data = htmlspecialchars($raw_member_data, ENT_QUOTES, 'UTF-8');
                            
                            $status = strtolower($row['status'] ?? 'pending');
                            if($status == 'success') {
                                $status_badge = '<span class="badge badge-subtle-success fs-11"><i class="fas fa-check-circle me-1"></i>Success</span>';
                            } elseif($status == 'failed') {
                                $status_badge = '<span class="badge badge-subtle-danger fs-11"><i class="fas fa-times-circle me-1"></i>Failed</span>';
                            } else {
                                $status_badge = '<span class="badge badge-subtle-warning fs-11"><i class="fas fa-clock me-1"></i>Pending</span>';
                            }
                        ?>
                            <tr>
                                <td class="py-3 fw-bold">#<?php echo $row['id']; ?></td>
                                <td>
                                    <span class="badge badge-subtle-primary fs-11 px-3 py-2 font-monospace border border-primary">
                                        <i class="fas fa-hashtag me-1"></i> <?php echo htmlspecialchars($row['ration_number']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-secondary fs-11 px-3 py-2 border border-secondary">
                                        <i class="fas fa-receipt me-1"></i> <?php echo htmlspecialchars($row['transaction_id'] ?? 'N/A'); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-info fs-11 px-3 py-2 border border-info">
                                        <i class="fas fa-users me-1"></i> <?php echo $total_members; ?> Members
                                    </span>
                                </td>
                                <td>
                                    <?php echo $status_badge; ?>
                                </td>
                                <td class="text-600">
                                    <?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?>
                                </td>
                                <td class="text-end pe-4">
                                    <button class="btn btn-sm btn-falcon-success fw-bold px-3 shadow-none" 
                                            data-json="<?php echo $secure_json_data; ?>" 
                                            data-ration="<?php echo htmlspecialchars($row['ration_number']); ?>" 
                                            data-txn="<?php echo htmlspecialchars($row['transaction_id'] ?? 'N/A'); ?>"
                                            onclick="viewRationMembers(this)"
                                            <?php echo ($total_members == 0) ? 'disabled' : ''; ?>>
                                        <i class="fas fa-eye me-1"></i> View Details
                                    </button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="py-4 text-500 fst-italic">
                                <i class="fas fa-inbox me-2"></i>No records found.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    function viewRationMembers(btn) {
        let ration_no = btn.getAttribute('data-ration');
        let txn_id = btn.getAttribute('data-txn');
        let rawData = btn.getAttribute('data-json');
        
        let members = [];
        try {
            members = JSON.parse(rawData);
        } catch (e) {
            console.error("Error parsing member JSON configuration", e);
        }

        let htmlTable = `
            <div class="table-responsive mt-3" style="max-height: 400px; overflow-y: auto;">
                <table class="table table-bordered table-sm fs-10 text-start align-middle">
                    <thead class="bg-200 text-900 position-sticky top-0 shadow-sm">
                        <tr>
                            <th class="text-center" style="width: 12%;">Sr. No.</th>
                            <th style="width: 44%;">Member Name</th>
                            <th style="width: 44%;">Aadhar Number</th>
                        </tr>
                    </thead>
                    <tbody>
        `;

        if (Array.isArray(members) && members.length > 0) {
            // Updated to fetch 'aadhaar' based on new JSON API response
            members.forEach((m, index) => {
                let aadharNumber = m.aadhaar || m.AadharNumber || 'N/A'; // Fallback added just in case
                htmlTable += `
                    <tr>
                        <td class="text-center fw-bold text-muted">${index + 1}</td>
                        <td>
                            <strong class="text-primary">${m.name || 'N/A'}</strong>
                        </td>
                        <td>
                            <span class="badge badge-subtle-success fs-11 px-2 py-1 border border-success">
                                <i class="fas fa-fingerprint me-1"></i> ${aadharNumber}
                            </span>
                        </td>
                    </tr>
                `;
            });
        } else {
            htmlTable += `
                <tr>
                    <td colspan="3" class="text-center text-muted py-3">
                        <i class="fas fa-info-circle me-2"></i>No data logs available
                    </td>
                </tr>
            `;
        }

        htmlTable += `</tbody></table></div>`;

        Swal.fire({
            title: `<h5 class="mb-0 text-success"><i class="fas fa-id-card me-2"></i>Ration Card Members</h5>
                    <div class="mt-2">
                        <span class="badge badge-subtle-primary fs-11">Ration No: ${ration_no}</span>
                        <span class="badge badge-subtle-secondary fs-11 ms-2">TXN: ${txn_id}</span>
                    </div>`,
            html: htmlTable,
            width: '600px',
            confirmButtonText: 'Close',
            customClass: { 
                confirmButton: 'btn btn-success shadow-none px-4',
                title: 'text-success'
            },
            buttonsStyling: false
        });
    }
</script>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>