<?php
session_start();
if (!isset($_SESSION['empId'])) {
    header("location: ../login.php");
}

// Database connection
$host = 'localhost';
$username = 'rxconne1_rxcrm';
$password = 'WM7R7Ht^TM(8';
$database = 'rxconne1_innomar'; // Replace with your database name
$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Tables to exclude
$excludedTables = ['clinic', 'payers', 'pharmacy', 'physician', 'physician_address','attachments','patient_ae','patient_appointment','patient_order','patient_order_product_item','patient_othertherapy','patient_payment','patient_reimbursements','patient_status','patient_task','reimbursements_appeal','reimbursements_sa'];

// Fetch table names containing Patient_ID_Number__c
$tablesWithColumn = [];
$result = $conn->query("SHOW TABLES");
while ($row = $result->fetch_array()) {
    $table = $row[0];
    if (in_array($table, $excludedTables)) {
        continue;
    }
    $colResult = $conn->query("SHOW COLUMNS FROM `$table` LIKE 'Patient_ID_Number__c'");
    if ($colResult->num_rows > 0) {
        $tablesWithColumn[] = $table;
    }
}

// Get search term
$searchTerm = $_GET['search'] ?? null;
$selectedTable = $_GET['table'] ?? null;
$tableData = [];
$columns = [];

if ($searchTerm && $selectedTable) {
    // Get columns and data for the selected table and Patient_ID_Number__c
    $colResult = $conn->query("SHOW COLUMNS FROM `$selectedTable`");
    while ($row = $colResult->fetch_assoc()) {
        $columns[] = $row['Field'];
    }

    $query = "SELECT * FROM `$selectedTable` WHERE `Patient_ID_Number__c` = ?";
    $stmt = $conn->prepare($query);
    if ($stmt) {
        $stmt->bind_param('s', $searchTerm);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $tableData[] = $row;
        }
        $stmt->close();
    }
}
$fileId = $_GET['search'] ?? '';   // e.g. "690257-48720"
//can we check if it contain DUP

$secondPart = null;


if (strpos($fileId, '-') !== false) {
    // split at the FIRST dash only
    list($first, $secondPart) = explode('-', $fileId, 2);
    $secondPart = trim($secondPart);
    // optional validation: ensure it's numeric
    if (!ctype_digit($secondPart)) {
        // not purely digits — handle as needed
        $secondPart = null;
    }
}
if (strpos($fileId, "DUP") !== false) {
    $secondPart = null;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Patient Data Viewer</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
    <style>
        body {
            display: flex;
            height: 100vh;
            margin: 0;
        }
        .sidebar {
            width: 250px;
            background-color: #f8f9fa;
            border-right: 1px solid #ddd;
            padding: 20px;
            overflow-y: auto;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            z-index: 1;
        }
        .content {
            margin-left: 250px;
            padding: 20px;
            flex: 1;
            overflow-x: auto;
        }
        .record-container {
            margin-bottom: 30px;
        }
        .sidebar {
    width: 250px;
    background-color: #ffffff; /* Dark Bootstrap theme color */
    color: #9c27b0; /* White text for readability */
    border-right: 1px solid #9c27b0; /* Subtle border for separation */
    padding: 20px;
    overflow-y: auto;
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 1;
}

.sidebar h3 {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
    text-transform: uppercase;
    letter-spacing: 0.05rem;
    border-bottom: 2px solid #495057; /* Underline effect */
    padding-bottom: 0.5rem;
    color: #000000; /* Bootstrap warning color for emphasis */
}

.sidebar a {
    display: block;
    color: #9c27b0; /* Subtle gray for links */
    font-weight: 600;
    padding-left: 5px;
    text-decoration: none;
    padding: 0.25rem 0.25rem;
    margin: 0.1rem 0;
    box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
    border-radius: 4px;
    transition: background-color 0.3s, color 0.3s;
}

.sidebar a:hover, .sidebar a:focus {
    background-color: #ffffff; /* Slightly lighter gray for hover effect */
    color: #000000; /* Brighter text on hover */
}

.sidebar a.active {
    background-color: #ffc107; /* Highlight active link */
    color: #343a40; /* Dark text for contrast */
    font-weight: bold;
}

.sidebar p {
    font-size: 0.9rem;
    color: #adb5bd;
    margin: 0.5rem 0 1rem;
    line-height: 1.5;
    text-align: center;
    font-style: italic;
}
th,td {
    font-size:12px;
    background-color: white;
    padding: 2px 5px !important;
}
table.table.table-bordered {
    width: max-content;
}
.sidebar a.active {
    background-color: #9c27b0;
    color: #ffffff;
    font-weight: bold;
}
h6.text-primary { color: #9C27AF !important;}
.alert-warning {
    --bs-alert-color: #000000;
    --bs-alert-bg: #fbe1ff;
    --bs-alert-border-color: #fbe1ff;
    --bs-alert-link-color: #000000;
}
    </style>
</head>
<body>
    <?php if($secondPart!=null) { 
        // Enrolment form URL (you provided)
        $enrolmentUrl = 'https://rxconnections.ca/rxcrm/rxforms/view_form_data.php?form_id=35762&entry_id='.$secondPart;
    ?>
    <div class="sidebar" bis_skin_checked="1">
        <h3>Quick Links</h3>
        <!-- Enrolment link: we keep data attributes so JS can open iframe -->
        <a href="#" id="enrolmentLink" data-url="<?= htmlspecialchars($enrolmentUrl) ?>" class="d-block mb-2 active" data-formId="35762" data-recordId="<?=$secondPart;?>">Enrolment form</a>

       
    </div>

    <div class="content">
        <div class="record-container border rounded p-3" id="iframeContainer">
            <!-- iframe will be injected here when user clicks "Enrolment form" -->
            <div class="text-muted">Click <strong>Enrolment form</strong> on the left to open the form here.</div>
        </div>
    </div>

    <!-- JS to handle opening/closing iframe -->
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        var enrolLink = document.getElementById('enrolmentLink');
        var container = document.getElementById('iframeContainer');

        if (enrolLink && container) {
            enrolLink.addEventListener('click', function (e) {
                e.preventDefault();
                var url = this.getAttribute('data-url');
                if (!url) return;

                // Build iframe and controls
                container.innerHTML = '';
                var controls = document.createElement('div');
                controls.className = 'd-flex justify-content-between align-items-center iframe-controls';

                var title = document.createElement('div');
                title.innerHTML = '<strong>Enrolment Form</strong>';
                controls.appendChild(title);

                var btnGroup = document.createElement('div');

                var openBtn = document.createElement('button');
                openBtn.className = 'btn btn-sm btn-outline-primary me-2';
                openBtn.type = 'button';
                openBtn.textContent = 'Open in new tab';
                openBtn.addEventListener('click', function () {
                    window.open(url, '_blank');
                });

                var closeBtn = document.createElement('button');
                closeBtn.className = 'btn btn-sm btn-outline-secondary';
                closeBtn.type = 'button';
                closeBtn.textContent = 'Close';
                closeBtn.addEventListener('click', function () {
                    container.innerHTML = '<div class="text-muted">Click <strong>Enrolment form</strong> on the left to open the form here.</div>';
                });

                // btnGroup.appendChild(openBtn);
                //btnGroup.appendChild(closeBtn);
                controls.appendChild(btnGroup);

                container.appendChild(controls);

                var iframeWrap = document.createElement('div');
                iframeWrap.className = 'iframe-wrapper';
                var iframe = document.createElement('iframe');
                iframe.setAttribute('src', url);
                iframe.setAttribute('frameborder', '0');
                iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts allow-forms');
                iframe.setAttribute('loading', 'lazy');
                iframe.style.width = '100%';
                iframe.style.height = '80vh';
                iframe.style.minHeight = '600px';
                iframeWrap.appendChild(iframe);

                container.appendChild(iframeWrap);

                // Optional: scroll content area to top so iframe is visible
                container.scrollIntoView({behavior: 'smooth', block: 'start'});
            });
        }
    });
    </script>

   <?php } else { ?>
<div class="sidebar">
    <h3>Quick Links</h3>
    <?php if ($searchTerm): ?>
        <?php foreach ($tablesWithColumn as $table): ?>
            <?php 
                // Convert table names to a more readable format
                $formattedTable = ucwords(str_replace('_', ' ', $table)); 
                $isActive = (isset($_GET['table']) && $_GET['table'] === $table) ? 'active' : '';

            ?>
            <a href="?search=<?= urlencode($searchTerm) ?>&table=<?= urlencode($table) ?>" 
               class="d-block mb-2 <?= $isActive ?>"><?= htmlspecialchars($formattedTable) ?></a>
        <?php endforeach; ?>
    <?php else: ?>
        <p>Search for a Patient ID to display data.</p>
    <?php endif; ?>
</div>


    <div class="content">
        <!--<form method="get" class="d-flex mb-4">-->
        <!--    <input type="text" name="search" class="form-control me-2" -->
        <!--           placeholder="Search Patient_ID_Number__c" -->
        <!--           value="<?= htmlspecialchars($searchTerm) ?>">-->
        <!--    <button type="submit" class="btn btn-primary">Search</button>-->
        <!--</form>-->

        <?php if ($searchTerm && $selectedTable): ?>
            <!--<h5 class="mb-3">Table: <?= htmlspecialchars($selectedTable) ?> (Patient ID: <?= htmlspecialchars($searchTerm) ?>)</h5>-->
            <?php if ($tableData): ?>
                <?php foreach ($tableData as $index => $record): ?>
                    <div class="record-container border rounded p-3">
                        <h6 class="text-primary">Record <?= $index + 1 ?></h6>
                        <table class="table table-bordered">
                            <tbody>
                                <?php foreach ($columns as $column): ?>
                                    <tr>
                                        <th class="table-secondary"><?= htmlspecialchars($column) ?></th>
                                        <td><?= htmlspecialchars($record[$column] ?? '') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="alert alert-warning">
                    No rows found for Patient ID: <?= htmlspecialchars($searchTerm) ?>
                </div>
            <?php endif; ?>
        <?php elseif ($searchTerm): ?>
            <!--<div class="alert alert-info">-->
            <!--    Select a table from the sidebar to view data for Patient ID: <?= htmlspecialchars($searchTerm) ?>-->
            <!--</div>-->
        <?php else: ?>
            <div class="alert alert-primary">
                Enter a Patient ID value to start.
            </div>
        <?php endif; ?>
    </div>
    <?php } ?>
</body>
</html>
