<?php
require_once('head.php');
require_once('header.php');
$clientName = isset($_SESSION['clientName']) ? $_SESSION['clientName'] : 'Client';
requirePermission($pdo, $_SESSION['clientId'], 'insights');

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Physician Insights - <?= htmlspecialchars($clientName) ?></title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
  <style>
    :root{--bg:#f8fafc; --card:#ffffff; --muted:#64748b; --accent:#3b82f6; --border:#e2e8f0; --success:#059669; --warning:#f59e0b; --danger:#dc2626;}
    *{box-sizing:border-box}
    body{font-family:'Inter',ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif; background:var(--bg); color:#0f172a; margin:0; padding:0; line-height:1.5;}
    .container-fluid{max-width:95%;margin:0 auto; padding:20px;margin: 0px 30px;}
    
    /* Header Section */
    .dashboard-header{background:linear-gradient(135deg, #667eea 0%, #764ba2 100%); color:white; padding:24px 0; margin:60px 0px 0px 0px; box-shadow:0 4px 12px rgba(0,0,0,0.1);position: sticky; top: 60px;z-index:20;}
    .header-content{max-width:95%; margin:0 auto; padding:0 20px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:16px;}
    .header-left h1{font-size:28px; font-weight:700; margin:0; text-shadow:0 2px 4px rgba(0,0,0,0.1);}
    .header-left .subtitle{font-size:14px; opacity:0.9; margin-top:4px;}
    .header-controls{display:flex; gap:12px; align-items:center; flex-wrap:wrap;}
    .header-controls select, .header-controls input{padding:8px 12px; border:1px solid rgba(255,255,255,0.3); border-radius:6px; background:rgba(255,255,255,0.1); color:white; font-size:14px;}
    .header-controls input[type="date"]{color:white; background:rgba(255,255,255,0.1);}
    .header-controls input[type="date"]::-webkit-calendar-picker-indicator{filter:invert(1);}
    .header-controls select option{color:#111; background:white;}
    .header-controls .btn{background:rgba(255,255,255,0.2); border:1px solid rgba(255,255,255,0.3); color:white; font-weight:500;}
    .header-controls .btn:hover{background:rgba(255,255,255,0.3);}
    
    /* Cards and Layout */
    .card-grid{display:grid; grid-template-columns:repeat(auto-fit, minmax(240px, 1fr)); gap:16px; margin-bottom:24px;}
    .card{background:var(--card); padding:20px; border-radius:12px; border:1px solid var(--border); box-shadow: 0 2px 8px rgba(15,23,42,0.04); transition:all 0.2s ease; position: relative;}
    .card:hover{box-shadow: 0 4px 16px rgba(15,23,42,0.08); transform:translateY(-1px);}
    .card .label{color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:0.05em; font-weight:600; margin-bottom:8px;}
    .card .value{font-size:32px; font-weight:700; margin-bottom:4px; color:#0f172a;}
    .card .subtitle{color:var(--muted); font-size:13px; margin-bottom:8px;}
    
    /* Grid Layout */
    .grid{display:grid; grid-template-columns:2fr 1fr; gap:20px; align-items:start;}
    .grid-2{display:grid; grid-template-columns:1fr 1fr; gap:20px;}
    .chart-card{padding:20px;}
    .metrics{display:flex; gap:12px; margin-top:12px; flex-wrap:wrap;}
    .metric{background:#f1f5f9; padding:10px 14px; border-radius:8px; font-weight:600; color:var(--accent); font-size:13px;}
    
    /* Buttons */
    .btn{display:inline-flex; gap:8px; align-items:center; padding:10px 16px; border-radius:8px; text-decoration:none; border:1px solid var(--border); background:#fff; cursor:pointer; font-size:14px; font-weight:500; transition:all 0.2s ease;}
    .btn:hover{background:#f8fafc; border-color:var(--accent);}
    .btn.primary{background:var(--accent); color:white; border-color:var(--accent);}
    .btn.primary:hover{background:#2563eb;}
    
    /* Tables */
    .table-container{background:white; border-radius:12px; border:1px solid var(--border); overflow:hidden; margin-bottom:24px;}
    .table-header{padding:20px 24px; border-bottom:2px solid var(--border); display:flex; justify-content:space-between; align-items:center;}
    .table-header h3{margin:0; font-size:18px; font-weight:600; color:#111;}
    table{width:100%; border-collapse:collapse;}
    th,td{text-align:left; padding:12px 8px; border-bottom:1px solid #eef2f7; font-size:13px;}
    th{background:#f8fafc; font-weight:600; color:#374151; position:sticky; top:0; z-index:10;}
    tbody tr:hover{background:#f8fafc;}
    tbody tr{cursor:pointer; transition:background 0.15s;}
    
    /* Charts */
    .chart-container{background:white; border-radius:12px; border:1px solid var(--border); padding:24px; margin-bottom:24px;}
    .chart-header{display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;}
    .chart-header h3{margin:0; font-size:18px; font-weight:600; color:#111;}
    
    /* Status badges */
    .badge{display:inline-block; padding:4px 10px; border-radius:6px; font-size:11px; font-weight:600; text-transform:uppercase;}
    .badge.high{background:#d1fae5; color:#065f46;}
    .badge.medium{background:#fef3c7; color:#92400e;}
    .badge.low{background:#fee2e2; color:#991b1b;}
    
    /* Trend */
    .trend{font-size:12px; margin-top:6px; display:flex; align-items:center; gap:4px; font-weight:500;}
    .trend.up{color:var(--success);} .trend.down{color:var(--danger);} .trend.neutral{color:var(--muted);}
    .trend i{font-size:10px;}
    
    /* Loading */
    .loading{display:flex; align-items:center; justify-content:center; padding:60px; color:var(--muted);}
    .loading i{margin-right:8px; animation:spin 1s linear infinite;}
    @keyframes spin{0%{transform:rotate(0deg);} 100%{transform:rotate(360deg);}}
    
    /* Responsive */
    @media(max-width:1200px){.grid,.grid-2{grid-template-columns:1fr;}}
    @media(max-width:768px){
      .header-content{flex-direction:column; align-items:flex-start;}
      .header-controls{width:100%; flex-direction:column;}
      .header-controls select, .header-controls input, .header-controls .btn{width:100%;}
      .card-grid{grid-template-columns:1fr;}
    }
  </style>
</head>
<body>
  <div class="dashboard-header">
    <div class="header-content">
      <div class="header-left">
        <h1><i class="fas fa-user-md"></i> Physician Insights & Analytics</h1>
        <div class="subtitle">Comprehensive prescriber performance and prescribing patterns</div>
      </div>
      <div class="header-controls">
        <select id="physicianFilter"><option value="">All Physicians</option></select>
        <select id="drugFilter"><option value="">All Drugs</option></select>
        <select id="indicationFilter"><option value="">All Indications</option></select>
        <input type="date" id="dateFrom" value="2025-07-26" onkeydown="return false" onpaste="return false" ondrop="return false" min="2025-07-26" />
        <input type="date" id="dateTo" />
        <button class="btn" id="clearFilters"><i class="fas fa-redo"></i> Reset</button>
        <button class="btn primary" id="exportData"><i class="fas fa-download"></i> Export</button>
      </div>
    </div>
  </div>
  <div class="container-fluid">
    <div class="card-grid">
      <div class="card">
        <div class="label"><i class="fas fa-user-md"></i> Total Physicians</div>
        <div class="value" id="totalPhysicians">0</div>
        <div class="subtitle">Active prescribers</div>
      </div>
      
      <div class="card">
        <div class="label"><i class="fas fa-users"></i> Total Patients</div>
        <div class="value" id="totalPatients">0</div>
        <div class="subtitle">Across all physicians</div>
      </div>
      <!--<div class="card">-->
      <!--  <div class="label"><i class="fas fa-pills"></i> Total Prescriptions</div>-->
      <!--  <div class="value" id="totalPrescriptions">0</div>-->
      <!--  <div class="subtitle">Active prescriptions</div>-->
      <!--</div>-->
      <div class="card">
        <div class="label"><i class="fas fa-chart-line"></i> Avg Patients/Physician</div>
        <div class="value" id="avgPatients">0</div>
        <div class="subtitle">Average per prescriber</div>
      </div>
      <div class="card">
        <div class="label"><i class="fas fa-star"></i> Top Physician</div>
        <div class="value" style="font-size:20px;" id="topPhysician">-</div>
        <div class="subtitle" id="topPhysicianCount">0 patients</div>
      </div>
      <div class="card">
        <div class="label"><i class="fas fa-trophy"></i> Top Drug</div>
        <div class="value" style="font-size:20px;" id="topDrug">-</div>
        <div class="subtitle" id="topDrugCount">0 prescriptions</div>
      </div>
    </div>
    
    <div class="grid-2">
        
      <div class="chart-container">
        <div class="chart-header">
          <div>
            <strong style="font-size: 18px; color: #374151;"><i class="fas fa-chart-pie"></i> Drug Distribution</strong>
            <div style="color: var(--muted); font-size: 14px; margin-top: 4px;">Prescribed medications breakdown</div>
          </div>
          <button class="btn" id="exportDrugChart"><i class="fas fa-download"></i></button>
        </div>
        <canvas id="drugChart" style="max-height:300px;"></canvas>
      </div>
      
      <div class="chart-container">
        <div class="chart-header">
          <div>
            <strong style="font-size: 18px; color: #374151;"><i class="fas fa-chart-pie"></i> Indication Distribution</strong>
            <div style="color: var(--muted); font-size: 14px; margin-top: 4px;">Treatment indications breakdown</div>
          </div>
          <button class="btn" id="exportIndicationChart"><i class="fas fa-download"></i></button>
        </div>
        <canvas id="indicationChart" style="max-height:300px;"></canvas>
      </div>
   
    
    <div class="chart-container">
      <div class="chart-header">
        <div>
          <strong style="font-size: 18px; color: #374151;"><i class="fas fa-heartbeat"></i> Patient Current Status Distribution</strong>
          <div style="color: var(--muted); font-size: 14px; margin-top: 4px;">Patient status across the program</div>
        </div>
        <button class="btn" id="exportStatusChart"><i class="fas fa-download"></i></button>
      </div>
      <canvas id="statusChart" style="max-height:320px;"></canvas>
    </div>
    
    <div class="chart-container">
      <div class="chart-header">
        <div>
          <strong style="font-size: 18px; color: #374151;"><i class="fas fa-chart-line"></i> Physician Enrollment Trends</strong>
          <div style="color: var(--muted); font-size: 14px; margin-top: 4px;">Monthly enrollment patterns</div>
        </div>
        <button class="btn" id="exportTrendChart"><i class="fas fa-download"></i></button>
      </div>
      <canvas id="trendChart" style="max-height:350px;"></canvas>
    </div>
    
   </div>
   
    <div class="table-container">
      <div class="table-header">
        <div>
          <strong style="font-size: 18px; color: #374151;"><i class="fas fa-table"></i> Physician Performance Overview</strong>
          <div style="color: var(--muted); font-size: 14px; margin-top: 4px;">Detailed performance metrics by physician</div>
        </div>
        <div style="display:flex; gap:12px;">
          <input type="text" id="searchPhysician" placeholder="Search physician..." style="padding:8px 12px; border:1px solid var(--border); border-radius:6px; font-size:13px; min-width:200px;">
          <button class="btn" id="sortByPatients"><i class="fas fa-sort"></i> Sort</button>
          <button class="btn primary" id="exportTable"><i class="fas fa-download"></i> Export</button>
        </div>
      </div>
      <div style="overflow-x:auto; max-height:700px; overflow-y:auto;">
        <table id="physicianTable">
          <thead>
            <tr>
              <th><i class="fas fa-user-md"></i> Physician Name</th>
              <th style="text-align:center;"><i class="fas fa-users"></i> Patients</th>
              <th style="text-align:center;"><i class="fas fa-pills"></i> Drugs</th>
              <th style="text-align:center;"><i class="fas fa-notes-medical"></i> Indications</th>
              <!--<th style="text-align:center;"><i class="fas fa-percentage"></i> Rate</th>-->
              <th style="text-align:center;"><i class="fas fa-chart-line"></i> Performance</th>
              <th style="text-align:center;"><i class="fas fa-calendar"></i> Last Activity</th>
              <th style="text-align:center;"><i class="fas fa-eye"></i> Actions</th>
            </tr>
          </thead>
          <tbody id="physicianTableBody">
            <tr><td colspan="8" class="loading"><i class="fas fa-spinner"></i> Loading physician data...</td></tr>
          </tbody>
        </table>
      </div>
    </div>
    <div id="detailsSection" style="display:none;">
      <div class="chart-container">
        <div class="chart-header">
          <div>
            <strong style="font-size: 18px; color: #374151;"><i class="fas fa-user-md"></i> <span id="selectedPhysicianName">Physician Details</span></strong>
            <div style="color: var(--muted); font-size: 14px; margin-top: 4px;">Detailed breakdown for selected physician</div>
          </div>
          <button class="btn" id="closeDetails"><i class="fas fa-times"></i> Close</button>
        </div>
        <div class="card-grid" style="margin-bottom:24px;">
          <div class="card">
            <div class="label"><i class="fas fa-users"></i> Total Patients</div>
            <div class="value" id="detailTotalPatients">0</div>
          </div>
          <div class="card">
            <div class="label"><i class="fas fa-pills"></i> Drugs Prescribed</div>
            <div class="value" id="detailDrugs">0</div>
          </div>
          <div class="card">
            <div class="label"><i class="fas fa-notes-medical"></i> Indications Treated</div>
            <div class="value" id="detailIndications">0</div>
          </div>
        </div>
        <div class="grid-2">
          <div>
            <h4 style="margin:0 0 20px 0; font-size:18px; color:#0f172a; font-weight:700;"><i class="fas fa-pills" style="color:#3b82f6;"></i> Drug Breakdown</h4>
            <div style="background:white; border-radius:16px; border:1px solid var(--border); overflow:hidden; box-shadow:0 2px 12px rgba(15,23,42,0.06);">
              <table style="width:100%;">
                <thead><tr style="background:#f8fafc;"><th>Drug Name</th><th style="text-align:center;">Patients</th><th style="text-align:center;">%</th></tr></thead>
                <tbody id="detailDrugTable"><tr><td colspan="3" style="text-align:center; padding:30px; color:#9ca3af;">No data</td></tr></tbody>
              </table>
            </div>
          </div>
          <div>
            <h4 style="margin:0 0 20px 0; font-size:18px; color:#0f172a; font-weight:700;"><i class="fas fa-notes-medical" style="color:#3b82f6;"></i> Indication Breakdown</h4>
            <div style="background:white; border-radius:16px; border:1px solid var(--border); overflow:hidden; box-shadow:0 2px 12px rgba(15,23,42,0.06);">
              <table style="width:100%;">
                <thead><tr style="background:#f8fafc;"><th>Indication</th><th style="text-align:center;">Patients</th><th style="text-align:center;">%</th></tr></thead>
                <tbody id="detailIndicationTable"><tr><td colspan="3" style="text-align:center; padding:30px; color:#9ca3af;">No data</td></tr></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
<?php  require_once('footer.php'); ?>
<script>
$(function(){
  const api = 'api_physician_dashboard.php';
  let physicianDataCache = null;
  let allPhysiciansData = null;
  let drugChart = null;
  let indicationChart = null;
  let trendChart = null;
  let statusChart = null;
  const today = new Date();
  $('#dateTo').val(today.toISOString().split('T')[0]);
  loadPhysicianData();
  loadPatientStatusData();
  
  function loadPhysicianData() {
    const dateFrom = $('#dateFrom').val();
    const dateTo = $('#dateTo').val();
    $.getJSON(api, { action: 'physician_details', dateFrom: dateFrom, dateTo: dateTo }, function(res) {
      if (res && res.success) {
        physicianDataCache = res.data.physicianData;
        allPhysiciansData = res.data.allPhysicians;
        populateFilters();
        applyFilters();
      } else {
        console.error('Failed to load physician data:', res.error);
      }
    }).fail(function(xhr) {
      console.error('Failed to fetch physician data:', xhr.responseText);
    });
  }
  
  function populateFilters() {
    const physicianDropdown = $('#physicianFilter');
    physicianDropdown.empty().append('<option value="">All Physicians</option>');
    if (physicianDataCache) {
      Object.keys(physicianDataCache).sort().forEach(function(physician) {
        const data = physicianDataCache[physician];
        const totalPatients = data.drugs.reduce((sum, d) => sum + d.patient_count, 0);
        physicianDropdown.append(`<option value="${physician}">${physician} (${totalPatients})</option>`);
      });
    }
    const drugDropdown = $('#drugFilter');
    drugDropdown.empty().append('<option value="">All Drugs</option>');
    const drugsSet = new Set();
    if (physicianDataCache) {
      Object.keys(physicianDataCache).forEach(function(physician) {
        const data = physicianDataCache[physician];
        if (data.drugs) { data.drugs.forEach(d => drugsSet.add(d.drug_name)); }
      });
      Array.from(drugsSet).sort().forEach(function(drug) {
        drugDropdown.append(`<option value="${drug}">${drug}</option>`);
      });
    }
    const indicationDropdown = $('#indicationFilter');
    indicationDropdown.empty().append('<option value="">All Indications</option>');
    const indicationsSet = new Set();
    if (physicianDataCache) {
      Object.keys(physicianDataCache).forEach(function(physician) {
        const data = physicianDataCache[physician];
        if (data.indications) { data.indications.forEach(i => indicationsSet.add(i.indication)); }
      });
      Array.from(indicationsSet).sort().forEach(function(indication) {
        indicationDropdown.append(`<option value="${indication}">${indication}</option>`);
      });
    }
  }
  
  function applyFilters() {
    if (!physicianDataCache) return;
    const selectedPhysician = $('#physicianFilter').val();
    const selectedDrug = $('#drugFilter').val();
    const selectedIndication = $('#indicationFilter').val();
    let filteredData = {};
    Object.keys(physicianDataCache).forEach(function(physician) {
      if (selectedPhysician && physician !== selectedPhysician) return;
      const data = physicianDataCache[physician];
      let filteredDrugs = data.drugs || [];
      let filteredIndications = data.indications || [];
      
      // Apply drug filter
      if (selectedDrug) { 
        filteredDrugs = filteredDrugs.filter(d => d.drug_name === selectedDrug); 
      }
      
      // Apply indication filter
      if (selectedIndication) { 
        filteredIndications = filteredIndications.filter(i => i.indication === selectedIndication); 
      }
      
      // Only include physician if they have matching data after filtering
      // When indication is selected, we need to ensure the physician has that indication
      if (selectedIndication && filteredIndications.length === 0) {
        return; // Skip this physician if they don't have the selected indication
      }
      
      // When drug is selected, we need to ensure the physician has that drug
      if (selectedDrug && filteredDrugs.length === 0) {
        return; // Skip this physician if they don't have the selected drug
      }
      
      // Include physician if they have any matching data
      if (filteredDrugs.length > 0 || filteredIndications.length > 0) {
        filteredData[physician] = { 
          drugs: filteredDrugs, 
          indications: filteredIndications,
          last_activity: data.last_activity 
        };
      }
    });
    updateKPIs(filteredData);
    updateCharts(filteredData);
    updateTable(filteredData);
  }
  
  function updateKPIs(data) {
    const physicians = Object.keys(data);
    let totalPatients = 0;
    let totalPrescriptions = 0;
    let drugCounts = {};
    let topPhysician = { name: '-', count: 0 };
    physicians.forEach(function(physician) {
      
      const physicianData = data[physician];
      const patientCount = physicianData.drugs.reduce((sum, d) => sum + d.patient_count, 0);
      
      totalPatients += patientCount;
      totalPrescriptions += physicianData.drugs.length;
      console.log("hello"+JSON.stringify(physicianData));
      if (patientCount > topPhysician.count) {
        topPhysician = { name: physician, count: patientCount };
      }
      physicianData.drugs.forEach(function(drug) {
        drugCounts[drug.drug_name] = (drugCounts[drug.drug_name] || 0) + drug.patient_count;
      });
    });
    const topDrug = Object.keys(drugCounts).length > 0 ? Object.keys(drugCounts).reduce((a, b) => drugCounts[a] > drugCounts[b] ? a : b) : '-';
    const avgPatients = physicians.length > 0 ? Math.round(totalPatients / physicians.length) : 0;
    const uniqueDrugs = Object.keys(drugCounts).length;
    $('#totalPhysicians').text(physicians.length);
    $('#totalPatients').text(totalPatients);
    $('#totalPrescriptions').text(totalPrescriptions);
    $('#avgPatients').text(avgPatients);
    $('#topPhysician').text(topPhysician.name);
    $('#topPhysicianCount').text(topPhysician.count + ' patients');
    $('#topDrug').text(topDrug);
    $('#topDrugCount').text((drugCounts[topDrug] || 0) + ' prescriptions');
  }
  
  function updateCharts(data) {
    let drugCounts = {};
    let indicationCounts = {};
    let statusCounts = {};
    
    Object.keys(data).forEach(function(physician) {
      const physicianData = data[physician];
      physicianData.drugs.forEach(function(drug) {
        drugCounts[drug.drug_name] = (drugCounts[drug.drug_name] || 0) + drug.patient_count;
      });
      physicianData.indications.forEach(function(indication) {
        indicationCounts[indication.indication] = (indicationCounts[indication.indication] || 0) + indication.patient_count;
      });
    });
    
    // Get status distribution from physician data
    // Note: This requires the physician_details API to include status information
    // For now, we'll fetch it separately but filter by the selected filters
    updateStatusChartFiltered();
    updateTrendChartFiltered();
    
    const drugLabels = Object.keys(drugCounts);
    const drugData = Object.values(drugCounts);
    if (drugChart) drugChart.destroy();
    const drugCtx = document.getElementById('drugChart').getContext('2d');
    drugChart = new Chart(drugCtx, {
      type: 'doughnut',
      data: {
        labels: drugLabels,
        datasets: [{
          data: drugData,
          backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#84cc16', '#f97316', '#6366f1'],
          borderWidth: 3,
          borderColor: '#ffffff'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
        layout: {
          padding: 20
        },
        plugins: {
          legend: { position: 'bottom', labels: { padding: 16, font: { size: 12, weight: '600' }, color: '#374151' } },
          tooltip: {
            backgroundColor: '#1f2937',
            padding: 14,
            titleFont: { size: 14, weight: '700' },
            bodyFont: { size: 13 },
            callbacks: {
              label: function(context) {
                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                const pct = ((context.parsed / total) * 100).toFixed(1);
                return ` ${context.label}: ${context.parsed} (${pct}%)`;
              }
            }
          }
        }
      },
      plugins: [{
        id: 'datalabels',
        afterDatasetsDraw: function(chart) {
          const ctx = chart.ctx;
          chart.data.datasets.forEach(function(dataset, i) {
            const meta = chart.getDatasetMeta(i);
            if (!meta.hidden) {
              meta.data.forEach(function(element, index) {
                const total = dataset.data.reduce((a, b) => a + b, 0);
                const value = dataset.data[index];
                const percentage = ((value / total) * 100);
                
                // Only show label if slice is large enough (>5%)
                if (percentage >= 5) {
                  ctx.fillStyle = '#fff';
                  ctx.font = 'bold 13px Inter, sans-serif';
                  ctx.textAlign = 'center';
                  ctx.textBaseline = 'middle';
                  const position = element.tooltipPosition();
                  ctx.fillText(value, position.x, position.y);
                }
              });
            }
          });
        }
      }]
    });
    const indicationLabels = Object.keys(indicationCounts);
    const indicationData = Object.values(indicationCounts);
    if (indicationChart) indicationChart.destroy();
    const indicationCtx = document.getElementById('indicationChart').getContext('2d');
    indicationChart = new Chart(indicationCtx, {
      type: 'doughnut',
      data: {
        labels: indicationLabels,
        datasets: [{
          data: indicationData,
          backgroundColor: ['#10b981', '#3b82f6', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#84cc16', '#f97316', '#6366f1'],
          borderWidth: 3,
          borderColor: '#ffffff'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
        layout: {
          padding: 20
        },
        plugins: {
          legend: { position: 'bottom', labels: { padding: 16, font: { size: 12, weight: '600' }, color: '#374151' } },
          tooltip: {
            backgroundColor: '#1f2937',
            padding: 14,
            titleFont: { size: 14, weight: '700' },
            bodyFont: { size: 13 },
            callbacks: {
              label: function(context) {
                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                const pct = ((context.parsed / total) * 100).toFixed(1);
                return ` ${context.label}: ${context.parsed} (${pct}%)`;
              }
            }
          }
        }
      },
      plugins: [{
        id: 'indicationLabels',
        afterDatasetsDraw: function(chart) {
          const ctx = chart.ctx;
          chart.data.datasets.forEach(function(dataset, i) {
            const meta = chart.getDatasetMeta(i);
            if (!meta.hidden) {
              meta.data.forEach(function(element, index) {
                const total = dataset.data.reduce((a, b) => a + b, 0);
                const value = dataset.data[index];
                const percentage = ((value / total) * 100);
                
                // Only show label if slice is large enough (>5%)
                if (percentage >= 5) {
                  ctx.fillStyle = '#fff';
                  ctx.font = 'bold 13px Inter, sans-serif';
                  ctx.textAlign = 'center';
                  ctx.textBaseline = 'middle';
                  const position = element.tooltipPosition();
                  ctx.fillText(value, position.x, position.y);
                }
              });
            }
          });
        }
      }]
    });
    
    // Initial trend chart load
    updateTrendChartFiltered();
  }
  
  function updateTrendChart(trendData) {
    const labels = trendData.labels || [];
    const data = trendData.data || [];
    
    if (trendChart) trendChart.destroy();
    const trendCtx = document.getElementById('trendChart').getContext('2d');
    trendChart = new Chart(trendCtx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'Enrollments',
          data: data,
          borderColor: '#3b82f6',
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          tension: 0.4,
          fill: true,
          borderWidth: 3,
          pointRadius: 6,
          pointHoverRadius: 8,
          pointBackgroundColor: '#3b82f6',
          pointBorderColor: '#ffffff',
          pointBorderWidth: 2
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
        layout: {
          padding: {
            top: 30,
            right: 10,
            bottom: 10,
            left: 10
          }
        },
        plugins: { 
          legend: { display: false },
          tooltip: {
            backgroundColor: '#1f2937',
            padding: 14,
            titleFont: { size: 14, weight: '700' },
            bodyFont: { size: 13 }
          }
        },
        scales: {
          y: { 
            beginAtZero: true, 
            grid: { color: '#f1f5f9' }, 
            ticks: { 
              font: { size: 12, weight: '600' }, 
              color: '#64748b',
              stepSize: 5
            },
            title: {
              display: true,
              text: 'Number of Enrollments',
              font: { size: 13, weight: '700' },
              color: '#374151'
            }
          },
          x: { 
            grid: { display: false }, 
            ticks: { 
              font: { size: 12, weight: '600' }, 
              color: '#64748b' 
            }
          }
        }
      },
      plugins: [{
        id: 'lineLabels',
        afterDatasetsDraw: function(chart) {
          const ctx = chart.ctx;
          chart.data.datasets.forEach(function(dataset, i) {
            const meta = chart.getDatasetMeta(i);
            if (!meta.hidden) {
              meta.data.forEach(function(point, index) {
                const data = dataset.data[index];
                if (data > 0) {
                  ctx.fillStyle = '#1f2937';
                  ctx.font = 'bold 11px Inter, sans-serif';
                  ctx.textAlign = 'center';
                  ctx.textBaseline = 'bottom';
                  ctx.fillText(data, point.x, point.y - 8);
                }
              });
            }
          });
        }
      }]
    });
  }
  
  function loadPatientStatusData() {
    const dateFrom = $('#dateFrom').val();
    const dateTo = $('#dateTo').val();
    
    // Fetch patient status distribution
    $.getJSON(api, { 
      action: 'get_patient_status_distribution', 
      dateFrom: dateFrom, 
      dateTo: dateTo 
    }, function(res) {
      if (res && res.success && res.data) {
        updateStatusChart(res.data);
      } else {
        console.error('Failed to load status data');
      }
    }).fail(function() {
      console.error('API call failed for status data');
    });
  }
  
  function updateStatusChartFiltered() {
    const dateFrom = $('#dateFrom').val();
    const dateTo = $('#dateTo').val();
    const selectedPhysician = $('#physicianFilter').val();
    const selectedDrug = $('#drugFilter').val();
    const selectedIndication = $('#indicationFilter').val();
    
    // Fetch patient status distribution with filters
    $.getJSON(api, { 
      action: 'get_patient_status_distribution', 
      dateFrom: dateFrom, 
      dateTo: dateTo,
      physician: selectedPhysician,
      drug: selectedDrug,
      indication: selectedIndication
    }, function(res) {
      if (res && res.success && res.data) {
        updateStatusChart(res.data);
      }
    });
  }
  
  function updateTrendChartFiltered() {
    const dateFrom = $('#dateFrom').val();
    const dateTo = $('#dateTo').val();
    const selectedPhysician = $('#physicianFilter').val();
    const selectedDrug = $('#drugFilter').val();
    const selectedIndication = $('#indicationFilter').val();
    
    // Fetch enrollment trends with filters
    $.getJSON(api, { 
      action: 'get_enrollment_trends', 
      dateFrom: dateFrom, 
      dateTo: dateTo,
      physician: selectedPhysician,
      drug: selectedDrug,
      indication: selectedIndication
    }, function(res) {
      if (res && res.success && res.data) {
        updateTrendChart(res.data);
      }
    });
  }
  
  function updateStatusChart(statusData) {
    const labels = Object.keys(statusData);
    const data = Object.values(statusData);
    
    if (statusChart) statusChart.destroy();
    const statusCtx = document.getElementById('statusChart').getContext('2d');
    statusChart = new Chart(statusCtx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: 'Number of Patients',
          data: data,
          backgroundColor: [
            'rgba(16, 185, 129, 0.8)',
            'rgba(59, 130, 246, 0.8)',
            'rgba(245, 158, 11, 0.8)',
            'rgba(139, 92, 246, 0.8)',
            'rgba(239, 68, 68, 0.8)',
            'rgba(107, 114, 128, 0.8)'
          ],
          borderColor: [
            '#10b981',
            '#3b82f6',
            '#f59e0b',
            '#8b5cf6',
            '#ef4444',
            '#6b7280'
          ],
          borderWidth: 2,
          borderRadius: 8,
          barThickness: 50
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
        layout: {
          padding: {
            top: 30,
            right: 10,
            bottom: 10,
            left: 10
          }
        },
        plugins: {
          legend: { display: false },
          tooltip: {
            backgroundColor: '#1f2937',
            padding: 14,
            titleFont: { size: 14, weight: '700' },
            bodyFont: { size: 13 },
            callbacks: {
              label: function(context) {
                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                const pct = ((context.parsed.y / total) * 100).toFixed(1);
                return ` ${context.parsed.y} patients (${pct}%)`;
              }
            }
          }
        },
        scales: {
          y: { 
            beginAtZero: true, 
            grid: { color: '#f1f5f9' }, 
            ticks: { 
              font: { size: 12, weight: '600' }, 
              color: '#64748b',
              stepSize: 5
            },
            title: {
              display: true,
              text: 'Number of Patients',
              font: { size: 13, weight: '700' },
              color: '#374151'
            }
          },
          x: { 
            grid: { display: false }, 
            ticks: { 
              font: { size: 11, weight: '600' }, 
              color: '#64748b',
              maxRotation: 45,
              minRotation: 45
            }
          }
        }
      },
      plugins: [{
        id: 'barLabels',
        afterDatasetsDraw: function(chart) {
          const ctx = chart.ctx;
          chart.data.datasets.forEach(function(dataset, i) {
            const meta = chart.getDatasetMeta(i);
            if (!meta.hidden) {
              meta.data.forEach(function(bar, index) {
                const data = dataset.data[index];
                if (data > 0) {
                  ctx.fillStyle = '#1f2937';
                  ctx.font = 'bold 12px Inter, sans-serif';
                  ctx.textAlign = 'center';
                  ctx.textBaseline = 'bottom';
                  ctx.fillText(data, bar.x, bar.y - 5);
                }
              });
            }
          });
        }
      }]
    });
  }
  
  function updateTable(data) {
    const tbody = $('#physicianTableBody');
    tbody.empty();
    const physicians = Object.keys(data).sort();
    if (physicians.length === 0) {
      tbody.html('<tr><td colspan="8" style="text-align:center; padding:60px; color:#9ca3af; font-size:15px;"><i class="fas fa-inbox" style="font-size:48px; display:block; margin-bottom:16px; opacity:0.3;"></i>No physician data available</td></tr>');
      return;
    }
    physicians.forEach(function(physician) {
      const physicianData = data[physician];
      const totalPatients = physicianData.drugs.reduce((sum, d) => sum + d.patient_count, 0);
      const drugCount = physicianData.drugs.length;
      const indicationCount = physicianData.indications.length;
      
      // Calculate success rate: (completed enrollments / total patients) * 100
      // For now, we'll use a simplified calculation based on patient count
      // You may need to adjust this based on your actual enrollment completion data
      const enrollmentRate = totalPatients > 0 ? Math.min(100, Math.round((totalPatients / (totalPatients + Math.max(0, 10 - totalPatients))) * 100)) : 0;
      
      let performanceBadge = '';
      if (totalPatients >= 20) {
        performanceBadge = '<span class="badge high">High</span>';
      } else if (totalPatients >= 10) {
        performanceBadge = '<span class="badge medium">Medium</span>';
      } else {
        performanceBadge = '<span class="badge low">Low</span>';
      }
      
      // Format last activity date
      const lastActivity = physicianData.last_activity ? new Date(physicianData.last_activity).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : 'N/A';
      
      tbody.append(`
        <tr data-physician="${physician}">
          <td style="font-weight:600; color:#0f172a;">${physician}</td>
          <td style="text-align:center; font-weight:700; color:#3b82f6; font-size:15px;">${totalPatients}</td>
          <td style="text-align:center; font-weight:600;">${drugCount}</td>
          <td style="text-align:center; font-weight:600;">${indicationCount}</td>
       
          <td style="text-align:center;">${performanceBadge}</td>
          <td style="text-align:center; color:#6b7280; font-weight:500;">${lastActivity}</td>
          <td style="text-align:center;">
            <button class="btn primary" style="padding:8px 16px; font-size:12px;" onclick="viewPhysicianDetails('${physician}')">
              <i class="fas fa-eye"></i> View
            </button>
          </td>
        </tr>
      `);
    });
  }
  
  window.viewPhysicianDetails = function(physician) {
    if (!physicianDataCache || !physicianDataCache[physician]) return;
    const data = physicianDataCache[physician];
    const totalPatients = data.drugs.reduce((sum, d) => sum + d.patient_count, 0);
    $('#selectedPhysicianName').text(physician);
    $('#detailTotalPatients').text(totalPatients);
    $('#detailDrugs').text(data.drugs.length);
    $('#detailIndications').text(data.indications.length);
    const drugTableBody = $('#detailDrugTable');
    drugTableBody.empty();
    if (data.drugs.length > 0) {
      const total = data.drugs.reduce((sum, d) => sum + d.patient_count, 0);
      data.drugs.forEach(function(drug) {
        const pct = ((drug.patient_count / total) * 100).toFixed(1);
        drugTableBody.append(`
          <tr style="border-bottom:1px solid #f1f5f9;">
            <td style="padding:16px; font-weight:500;">${drug.drug_name}</td>
            <td style="text-align:center; font-weight:700; color:#3b82f6; padding:16px;">${drug.patient_count}</td>
            <td style="text-align:center; padding:16px;"><span style="background:#dbeafe; color:#1e40af; padding:4px 12px; border-radius:6px; font-weight:700; font-size:12px;">${pct}%</span></td>
          </tr>
        `);
      });
    } else {
      drugTableBody.html('<tr><td colspan="3" style="text-align:center; padding:30px; color:#9ca3af;">No drug data</td></tr>');
    }
    const indicationTableBody = $('#detailIndicationTable');
    indicationTableBody.empty();
    if (data.indications.length > 0) {
      const total = data.indications.reduce((sum, i) => sum + i.patient_count, 0);
      data.indications.forEach(function(indication) {
        const pct = ((indication.patient_count / total) * 100).toFixed(1);
        indicationTableBody.append(`
          <tr style="border-bottom:1px solid #f1f5f9;">
            <td style="padding:16px; font-weight:500;">${indication.indication}</td>
            <td style="text-align:center; font-weight:700; color:#10b981; padding:16px;">${indication.patient_count}</td>
            <td style="text-align:center; padding:16px;"><span style="background:#d1fae5; color:#065f46; padding:4px 12px; border-radius:6px; font-weight:700; font-size:12px;">${pct}%</span></td>
          </tr>
        `);
      });
    } else {
      indicationTableBody.html('<tr><td colspan="3" style="text-align:center; padding:30px; color:#9ca3af;">No indication data</td></tr>');
    }
    $('#detailsSection').slideDown();
    $('html, body').animate({ scrollTop: $('#detailsSection').offset().top - 100 }, 500);
  };
  
  // Auto-filter on change
  $('#physicianFilter, #drugFilter, #indicationFilter, #dateFrom, #dateTo').on('change', function() {
    if ($(this).attr('id') === 'dateFrom' || $(this).attr('id') === 'dateTo') {
      loadPhysicianData();
      loadPatientStatusData();
    } else {
      applyFilters();
    }
  });
  
  $('#clearFilters').on('click', function() {
    $('#physicianFilter').val('');
    $('#drugFilter').val('');
    $('#indicationFilter').val('');
    $('#dateFrom').val('2025-07-26');
    $('#dateTo').val(today.toISOString().split('T')[0]);
    loadPhysicianData();
    loadPatientStatusData();
  });
  
  $('#closeDetails').on('click', function() {
    $('#detailsSection').slideUp();
  });
  
  $('#searchPhysician').on('input', function() {
    const searchTerm = $(this).val().toLowerCase();
    $('#physicianTableBody tr').each(function() {
      const physicianName = $(this).find('td:first').text().toLowerCase();
      if (physicianName.includes(searchTerm)) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  });
  
  let sortDirection = 'desc'; // Track sort direction
  
  $('#sortByPatients').on('click', function() {
    const tbody = $('#physicianTableBody');
    const rows = tbody.find('tr').toArray().filter(function(row) {
      // Only sort actual data rows, not the "no data" message
      return $(row).find('td').length > 1;
    });
    
    rows.sort(function(a, b) {
      const aVal = parseInt($(a).find('td:eq(1)').text()) || 0;
      const bVal = parseInt($(b).find('td:eq(1)').text()) || 0;
      return sortDirection === 'desc' ? bVal - aVal : aVal - bVal;
    });
    
    // Toggle direction for next click
    sortDirection = sortDirection === 'desc' ? 'asc' : 'desc';
    
    // Update button icon
    const icon = sortDirection === 'desc' ? 'fa-sort-amount-down' : 'fa-sort-amount-up';
    $(this).find('i').removeClass('fa-sort fa-sort-amount-down fa-sort-amount-up').addClass(icon);
    
    tbody.empty().append(rows);
  });
  
  $('#exportData, #exportTable').on('click', function() {
    // Prepare data for export
    const exportData = [];
    
    // Add headers
    exportData.push(['Physician Name', 'Total Patients', 'Drugs Prescribed', 'Indications Treated', 'Success Rate (%)', 'Performance', 'Last Activity']);
    
    // Add data rows
    $('#physicianTableBody tr').each(function() {
      if ($(this).is(':visible') && $(this).find('td').length > 1) {
        const row = [];
        row.push($(this).find('td:eq(0)').text().trim()); // Physician Name
        row.push($(this).find('td:eq(1)').text().trim()); // Total Patients
        row.push($(this).find('td:eq(2)').text().trim()); // Drugs
        row.push($(this).find('td:eq(3)').text().trim()); // Indications
        row.push($(this).find('td:eq(4)').text().trim()); // Success Rate
        row.push($(this).find('td:eq(5)').text().trim()); // Performance
        row.push($(this).find('td:eq(6)').text().trim()); // Last Activity
        exportData.push(row);
      }
    });
    
    // Convert to CSV
    let csvContent = '';
    exportData.forEach(function(rowArray) {
      const row = rowArray.map(function(cell) {
        // Escape quotes and wrap in quotes if contains comma
        const cellStr = String(cell).replace(/"/g, '""');
        return cellStr.includes(',') || cellStr.includes('\n') ? '"' + cellStr + '"' : cellStr;
      }).join(',');
      csvContent += row + '\r\n';
    });
    
    // Create download link
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    const dateStr = new Date().toISOString().split('T')[0];
    link.setAttribute('href', url);
    link.setAttribute('download', 'physician_insights_' + dateStr + '.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
  
  $('#exportDrugChart').on('click', function() {
    const url = drugChart.toBase64Image();
    const link = document.createElement('a');
    link.download = 'drug-distribution.png';
    link.href = url;
    link.click();
  });
  
  $('#exportIndicationChart').on('click', function() {
    const url = indicationChart.toBase64Image();
    const link = document.createElement('a');
    link.download = 'indication-distribution.png';
    link.href = url;
    link.click();
  });
  
  $('#exportTrendChart').on('click', function() {
    const url = trendChart.toBase64Image();
    const link = document.createElement('a');
    link.download = 'enrollment-trends.png';
    link.href = url;
    link.click();
  });
  
  $('#exportStatusChart').on('click', function() {
    const url = statusChart.toBase64Image();
    const link = document.createElement('a');
    link.download = 'patient-status-distribution.png';
    link.href = url;
    link.click();
  });
});
</script>
</body>
</html>
