<?php
// -------------------------
// medical_record_profile.php
// -------------------------

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../dripend/includes/db.php';

// Get patient ID from query string
$patient_id = isset($_GET['patient_id']) ? $_GET['patient_id'] : null;
$record = null;

if ($patient_id && $conn) {
    // Fetch patient main record
    $stmt = $conn->prepare("
        SELECT patient_no, prefix, first_name, middle_name, last_name, gender_id, dob, age, nhis_no, 
               other_insurance_id, other_insurance_no, staff_status_id
        FROM patient
        WHERE patient_no = ?
        LIMIT 1
    ");
    $stmt->bind_param("s", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();

        // Resolve prefix
        $prefix = '';
        if (!empty($row['prefix'])) {
            $pstmt = $conn->prepare("SELECT prefix_name FROM prefix WHERE id = ?");
            $pstmt->bind_param("i", $row['prefix']);
            $pstmt->execute();
            $pres = $pstmt->get_result();
            if ($pres && $pres->num_rows > 0) $prefix = $pres->fetch_assoc()['prefix_name'];
            $pstmt->close();
        }

        // Resolve gender
        $gender = '';
        if (!empty($row['gender_id'])) {
            $gpstmt = $conn->prepare("SELECT gender_name FROM gender WHERE id = ?");
            $gpstmt->bind_param("i", $row['gender_id']);
            $gpstmt->execute();
            $gres = $gpstmt->get_result();
            if ($gres && $gres->num_rows > 0) $gender = $gres->fetch_assoc()['gender_name'];
            $gpstmt->close();
        }

        // Resolve insurance
        $insurance = '';
        if (!empty($row['other_insurance_id'])) {
            $ipstmt = $conn->prepare("SELECT insurance_name FROM insurance_type WHERE id = ?");
            $ipstmt->bind_param("i", $row['other_insurance_id']);
            $ipstmt->execute();
            $ires = $ipstmt->get_result();
            if ($ires && $ires->num_rows > 0) $insurance = $ires->fetch_assoc()['insurance_name'];
            $ipstmt->close();
        }

        $record = [
            'name' => trim($prefix . ' ' . $row['first_name'] . ' ' . $row['middle_name'] . ' ' . $row['last_name']),
            'gender' => $gender,
            'age' => $row['age'],
            'insurance' => $insurance,
            'nhis' => $row['nhis_no'],
            'private_ins' => $row['other_insurance_no'],
            'dob' => $row['dob'],
            'is_staff' => $row['staff_status_id'] == 1 ? 'Yes' : 'No'
        ];
    }

    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Medical Record Profile | DripDental Hospital</title>

<style>
:root {
  --primary: #005b96;
  --secondary: #0077b6;
  --accent: #00b4d8;
  --bg: #f5f7fb;
  --white: #ffffff;
  --green: #2a9d8f;
  --red: #e63946;
  --border: #e0e4ea;
}

/* GLOBAL STYLING */
body {
  margin: 0;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  background-color: var(--bg);
  color: #1c1c1c;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  overflow-y: auto;
  padding: 40px 0;
}

/* MAIN CONTENT CENTERING */
.main-content {
  width: 95%;
  max-width: 1200px;
  background: var(--bg);
  padding: 0 20px 60px 20px;
  box-sizing: border-box;
}

/* PAGE HEADER */
.page-header {
  background: linear-gradient(to right, var(--primary), var(--secondary));
  color: #fff;
  padding: 18px 25px;
  border-radius: 12px;
  margin-bottom: 25px;
  box-shadow: 0 3px 12px rgba(0,0,0,0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h1 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
}

/* CARD BASE */
.card {
  background: var(--white);
  border-radius: 15px;
  padding: 25px 30px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.07);
  margin-bottom: 30px;
}

/* PATIENT HEADER */
.patient-header {
  display: flex;
  align-items: flex-start;
  gap: 25px;
  flex-wrap: wrap;
}

.patient-header img {
  width: 120px;
  height: 120px;
  border-radius: 15px;
  border: 2px solid var(--border);
  object-fit: cover;
  background: #e9f6ff;
}

.patient-details {
  flex: 1;
}

.patient-details h2 {
  color: var(--primary);
  font-size: 25px;
  font-weight: 700;
  margin: 0 0 10px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
  gap: 8px 20px;
}

.info-grid p {
  margin: 2px 0;
  font-size: 15px;
}

.info-grid strong {
  color: var(--secondary);
}

/* HEADER TABS */
.header-tabs {
  display: flex;
  gap: 10px;
  background: #eef5fb;
  border-radius: 8px;
  padding: 6px;
  margin-top: 15px;
  flex-wrap: wrap;
}

.header-tabs button {
  background: transparent;
  border: none;
  color: #333;
  font-size: 15px;
  font-weight: 600;
  padding: 8px 20px;
  border-radius: 25px;
  cursor: pointer;
  transition: 0.3s;
}

.header-tabs button.active {
  background: var(--secondary);
  color: #fff;
}

.header-tabs button:hover {
  background: var(--accent);
  color: #fff;
}

.tab-content { display: none; margin-top: 12px; }
.tab-content.active { display: block; }

/* RECORDS GRID */
.records-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(480px, 1fr));
  gap: 25px;
}

/* SECTION CARD */
.section-card {
  background: var(--white);
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  padding: 20px 25px;
  animation: fadeIn 0.4s ease-in-out;
}

.section-card h3 {
  font-size: 17px;
  color: var(--primary);
  border-bottom: 2px solid var(--border);
  padding-bottom: 5px;
  margin-bottom: 10px;
}

/* TABLES */
.table-wrap { overflow-x: auto; }

table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

th, td {
  padding: 9px 10px;
  border-bottom: 1px solid var(--border);
}

th {
  background: #f8fafc;
  color: #333;
  text-align: left;
}

tr:hover { background: #f1f5f9; }

.status-good { color: var(--green); font-weight: 600; }
.status-high { color: var(--red); font-weight: 600; }

/* BUTTONS */
.action-btn {
  background: var(--primary);
  color: #fff;
  padding: 10px 22px;
  border-radius: 8px;
  border: none;
  font-weight: 600;
  cursor: pointer;
  transition: 0.3s;
  text-decoration: none;
  display: inline-block;
}

.action-btn:hover {
  background: var(--secondary);
}

.back-btn {
  background: #5c6bc0;
  color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 600;
  margin-top: 30px;
  display: inline-block;
}

.back-btn:hover {
  background: #3f51b5;
}

/* ANIMATION */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
</head>
<body>
<div class="main-content">

<div class="page-header">
  <h1>Medical Record Profile</h1>
  <a href="../../dashboard.php" class="action-btn">Go to Main Dashboard</a>
</div>

<?php if($record): ?>
<div class="card">
  <div class="patient-header">
    <img src="https://cdn-icons-png.flaticon.com/512/847/847969.png" alt="patient-avatar">
    <div class="patient-details">
      <h2><?= htmlspecialchars($record['name']) ?></h2>
      <div class="info-grid">
        <p><strong>Hospital ID:</strong> <?= htmlspecialchars($patient_id) ?></p>
        <p><strong>Gender:</strong> <?= htmlspecialchars($record['gender']) ?></p>
        <p><strong>Date of Birth:</strong> <?= date('d-m-Y', strtotime($record['dob'])) ?></p>
        <p><strong>Age:</strong> <?= htmlspecialchars($record['age']) ?> yrs</p>
        <p><strong>Insurance:</strong> <?= htmlspecialchars($record['insurance']) ?></p>
        <p><strong>NHIS No.:</strong> <?= htmlspecialchars($record['nhis']) ?></p>
        <p><strong>Private Ins.:</strong> <?= htmlspecialchars($record['private_ins']) ?></p>
        <p><strong>Staff:</strong> <?= htmlspecialchars($record['is_staff']) ?></p>
        <p><strong>Last Visit:</strong> 2025-07-10</p>
      </div>
    </div>
  </div>

  <div class="header-tabs">
    <button class="tab-btn active" data-tab="basic">Basic Info</button>
    <button class="tab-btn" data-tab="contact">Contact</button>
    <button class="tab-btn" data-tab="plan">Plan</button>
    <button class="tab-btn" data-tab="actions">Actions</button>
  </div>

  <div id="basic" class="tab-content active">
    <p>This section summarizes the patient’s demographic and insurance overview details.</p>
  </div>

  <div id="contact" class="tab-content">
    <p><strong>Phone:</strong> +233 24 567 8123</p>
    <p><strong>Email:</strong> patient@example.com</p>
    <p><strong>Address:</strong> 23 Nii Amugi Street, East Legon, Accra</p>
    <p><strong>Emergency Contact:</strong> 020 556 1234</p>
  </div>

  <div id="plan" class="tab-content">
    <p><strong>Insurance Type:</strong> <?= htmlspecialchars($record['insurance']) ?></p>
    <p><strong>Plan Validity:</strong> 01-Jan-2025 to 31-Dec-2025</p>
    <p><strong>Coverage:</strong> General OPD, Laboratory, Pharmacy, Dental</p>
  </div>

  <div id="actions" class="tab-content">
    <a href="../../lab/lab_requests_and_recommendations.php" class="action-btn">View Lab Requests</a>
    <a href="../../billing/insurance_claims_dashboard.php" class="action-btn" style="background:#2a9d8f;">Insurance Claims</a>
  </div>
</div>

<div class="records-grid">
  <div class="section-card">
    <h3>Visit Summary</h3>
    <div class="table-wrap">
      <table>
        <thead><tr><th>Date</th><th>Department</th><th>Physician</th><th>Diagnosis</th><th>Status</th></tr></thead>
        <tbody>
          <tr><td>2025-03-21</td><td>General OPD</td><td>Dr. Boateng</td><td>Malaria</td><td>Recovered</td></tr>
          <tr><td>2025-07-10</td><td>Dental Unit</td><td>Dr. Nyarko</td><td>Tooth Extraction</td><td>Completed</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <div class="section-card">
    <h3>Lab History</h3>
    <div class="table-wrap">
      <table>
        <thead><tr><th>Date</th><th>Test</th><th>Result</th><th>Range</th><th>Status</th></tr></thead>
        <tbody>
          <tr><td>2025-02-14</td><td>Full Blood Count</td><td>13.5 g/dL</td><td>12–16</td><td class="status-good">Normal</td></tr>
          <tr><td>2025-04-08</td><td>FBS</td><td>7.2 mmol/L</td><td>3.9–6.1</td><td class="status-high">High</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <div class="section-card">
    <h3>Consultation Notes</h3>
    <p><strong>2025-03-21:</strong> Presented with fever and fatigue. Prescribed antimalarial medication.</p>
    <p><strong>2025-07-10:</strong> Dental extraction performed. Follow-up scheduled in two weeks.</p>
  </div>

  <div class="section-card">
    <h3>Prescription History</h3>
    <div class="table-wrap">
      <table>
        <thead><tr><th>Date</th><th>Drug</th><th>Dose</th><th>Frequency</th><th>Duration</th></tr></thead>
        <tbody>
          <tr><td>2025-03-21</td><td>Artemether-Lumefantrine</td><td>1 Tab</td><td>BID</td><td>3 Days</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<a href="search_patient.php" class="back-btn">Back to Search</a>

<?php else: ?>
<p style="text-align:center;color:#777;">No patient record found.</p>
<?php endif; ?>
</div>

<script>
const tabs = document.querySelectorAll('.tab-btn');
const contents = document.querySelectorAll('.tab-content');
tabs.forEach(btn => {
  btn.addEventListener('click', () => {
    tabs.forEach(b => b.classList.remove('active'));
    contents.forEach(c => c.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById(btn.dataset.tab).classList.add('active');
  });
});
</script>
</body>
</html>
