<?php  
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Require the database connection first
require_once '../../dripend/includes/db.php';

// ==============================================================================
// 1. AJAX LIVE SEARCH ENDPOINT FOR OTC (Searches Patient Table Directly)
// ==============================================================================
if (isset($_GET['otc_search'])) {
    $q = '%' . trim($_GET['otc_search']) . '%';
    
    $stmt = $conn->prepare("
        SELECT patient_no, first_name, last_name, mobile 
        FROM patient 
        WHERE patient_no LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR mobile LIKE ?
        LIMIT 8
    ");
    $stmt->bind_param("ssss", $q, $q, $q, $q);
    $stmt->execute();
    $res = $stmt->get_result();
    
    $results = [];
    while($row = $res->fetch_assoc()){
        $results[] = $row;
    }
    
    header('Content-Type: application/json');
    echo json_encode($results);
    exit; 
}

// ==============================================================================
// 2. FETCH DRUG CATALOG FOR DATALIST
// ==============================================================================
$drugs = [];
$resDrugs = $conn->query("SELECT service_name FROM service_catalog WHERE service_type = 'Drug' AND is_active = 1");
if ($resDrugs) {
    while($row = $resDrugs->fetch_assoc()) {
        $drugs[] = $row['service_name'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cash and Carry Drug Dispense | DripDental</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
:root {
  --sidebar-width: 240px;
  --bg: #f8fafc;
  --accent-dark: #0f172a;
  --accent-mid: #0284c7;
  --green: #10b981;
  --border: #e2e8f0;
  --gold: #f59e0b;
  --red: #ef4444;
  --card-bg: #ffffff;
}

* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: #334155; overflow-x: hidden; }

/* -------------------------------------
   LAYOUT & WRAPPER
   ------------------------------------- */
.page-wrapper {
  position: absolute;
  top: 0;
  left: var(--sidebar-width);
  width: calc(100% - var(--sidebar-width));
  padding: 30px 20px 60px 20px;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.form-container { width: 100%; max-width: 1400px; background: var(--card-bg); padding: 35px 40px; border-radius: 12px; border: 1px solid var(--border); box-shadow: 0 10px 25px -5px rgba(0,0,0,0.05); }

.page-title { text-align: left; font-size: 24px; font-weight: 800; color: var(--accent-dark); padding-bottom: 20px; border-bottom: 2px solid var(--border); margin-bottom: 25px; display: flex; align-items: center; gap: 12px; }
.page-title i { color: var(--green); }

/* -------------------------------------
   FORMS & INPUTS
   ------------------------------------- */
.grid-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
.form-group { display: flex; flex-direction: column; position: relative; }
.form-group label { font-size: 13px; font-weight: 700; color: var(--accent-dark); text-transform: uppercase; margin-bottom: 8px; letter-spacing: 0.5px; }

input[type="text"], input[type="number"], input[type="date"], select, textarea {
  padding: 12px 16px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 14px; outline: none; transition: 0.2s; width: 100%; background: #fff;
}
input:focus, select:focus { border-color: var(--accent-mid); box-shadow: 0 0 0 3px #e0f2fe; }
input[readonly] { background: #f1f5f9; color: #64748b; border-color: #e2e8f0; cursor: not-allowed; font-weight: 600; }

.section-header { grid-column: 1 / -1; background: #f8fafc; color: var(--accent-dark); font-weight: 800; font-size: 16px; padding: 15px 20px; border-radius: 8px; border: 1px solid var(--border); margin: 25px 0 10px 0; display: flex; align-items: center; gap: 10px; }
.section-header i { color: var(--accent-mid); }

/* -------------------------------------
   LIVE SEARCH DROPDOWN
   ------------------------------------- */
.search-results { position: absolute; top: 100%; left: 0; width: 100%; background: #fff; border: 1px solid var(--border); border-radius: 8px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); max-height: 250px; overflow-y: auto; z-index: 100; display: none; margin-top: 5px; }
.search-item { padding: 12px 15px; border-bottom: 1px solid #f1f5f9; cursor: pointer; transition: 0.2s; display: flex; flex-direction: column; gap: 4px; }
.search-item:last-child { border-bottom: none; }
.search-item:hover { background: #f8fafc; border-left: 3px solid var(--accent-mid); padding-left: 12px; }
.search-item-name { font-weight: 700; color: var(--accent-dark); font-size: 14px; }
.search-item-meta { font-size: 12px; color: #64748b; }

/* -------------------------------------
   TABLE STYLING
   ------------------------------------- */
.table-wrapper { grid-column: 1 / -1; overflow-x: auto; border: 1px solid var(--border); border-radius: 8px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; text-align: left; }
th, td { padding: 12px 15px; border-bottom: 1px solid var(--border); }
th { background: #f1f5f9; color: var(--accent-dark); font-weight: 700; text-transform: uppercase; font-size: 12px; }
td { background: #fff; vertical-align: middle; }
tbody tr:hover td { background: #f8fafc; }

table input { padding: 8px 12px; border-radius: 6px; }
.rate-input, .qty-input { max-width: 90px; text-align: right; }
.total-input { max-width: 110px; text-align: right; background: #e0f2fe !important; color: var(--accent-dark); font-weight: 800; }

.remove-btn { background: #fee2e2; color: #dc2626; border: none; width: 32px; height: 32px; border-radius: 6px; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; }
.remove-btn:hover { background: #fecaca; transform: scale(1.05); }

/* -------------------------------------
   FOOTER & BUTTONS
   ------------------------------------- */
.total-display { grid-column: 1 / -1; text-align: right; background: #f8fafc; padding: 20px; border-radius: 8px; border: 1px solid var(--border); margin-top: 15px; font-size: 16px; font-weight: 700; color: var(--accent-dark); }
.total-display span { color: var(--green); font-size: 24px; font-weight: 800; margin-left: 10px; }

.actions { grid-column: 1 / -1; display: flex; justify-content: flex-end; gap: 15px; margin-top: 20px; }
.btn { border: none; padding: 12px 25px; border-radius: 8px; font-weight: 700; font-size: 15px; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; }
.btn-gold { background: #fffbeb; color: #b45309; border: 1px solid #fde68a; }
.btn-gold:hover { background: #fef3c7; }
.btn-blue { background: var(--accent-mid); color: #fff; }
.btn-blue:hover { background: #0369a1; }
.btn-green { background: var(--green); color: #fff; box-shadow: 0 4px 10px rgba(16, 185, 129, 0.2); }
.btn-green:hover { background: #059669; transform: translateY(-2px); box-shadow: 0 6px 15px rgba(16, 185, 129, 0.3); }

.otc-badge { position: absolute; top: 35px; right: 40px; background: #d1fae5; color: #065f46; padding: 8px 16px; border-radius: 20px; font-size: 13px; font-weight: 800; border: 1px solid #a7f3d0; }
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<datalist id="drug_catalog">
    <?php foreach($drugs as $d): ?>
        <option value="<?php echo htmlspecialchars($d); ?>"></option>
    <?php endforeach; ?>
</datalist>

<div class="page-wrapper">
  <div class="form-container">
    
    <div class="otc-badge"><i class="fa-solid fa-bolt"></i> OTC / Walk-In Mode</div>
    <h1 class="page-title"><i class="fa-solid fa-cash-register"></i> Cash & Carry Drug Dispense</h1>

    <form method="post" action="save_dispense.php" id="otcForm">
      <!-- Hidden fields to identify this as a direct walk-in sale -->
      <input type="hidden" name="visit_master_id" value="0"> 
      <input type="hidden" name="is_otc_walkin" value="1">
      <input type="hidden" name="patient_no" id="patient_no" value="WALK-IN">

      <div class="section-header"><i class="fa-solid fa-user-tag"></i> 1. Patient & Dispensary Setup</div>
      
      <div class="grid-form">
          <div class="form-group">
              <label>Search Existing Patient (Optional)</label>
              <div style="position:relative;">
                  <input type="text" id="liveSearchInput" placeholder="Type Name, ID, or Phone..." autocomplete="off">
                  <div id="searchResults" class="search-results"></div>
              </div>
          </div>
          
          <div class="form-group">
              <label>Patient Name</label>
              <input type="text" name="patient_name" id="patient_name" placeholder="Walk-In Patient" required>
          </div>
          
          <div class="form-group">
              <label>Mobile Number</label>
              <input type="text" name="mobile" id="mobile" placeholder="e.g. 0240000000">
          </div>

          <div class="form-group">
              <label>Select Dispensary Pharmacy</label>
              <select name="dispensing_pharmacy" required style="border-color:var(--accent-mid); background:#f8fafc;">
                  <option value="Cash and Carry">Cash and Carry (Front Desk)</option>
                  <option value="Main Pharmacy">Main Pharmacy</option>
                  <option value="Satellite Pharmacy">Satellite Pharmacy</option>
              </select>
          </div>
      </div>

      <div class="section-header"><i class="fa-solid fa-pills"></i> 2. Direct Prescriptions / Items</div>

      <div class="table-wrapper">
        <table id="prescriptionTable">
          <thead>
            <tr>
              <th style="width: 5%; text-align:center;">#</th>
              <th style="width: 30%;">Drug / Item Name</th>
              <th style="width: 15%;">Dose / Freq</th>
              <th style="width: 10%;">Days</th>
              <th style="width: 10%; text-align:right;">Qty</th>
              <th style="width: 12%; text-align:right;">Unit Rate (GHS)</th>
              <th style="width: 13%; text-align:right;">Total (GHS)</th>
              <th style="width: 5%; text-align:center;">Action</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style="text-align:center; font-weight:700;">1</td>
              <td>
                  <input type="hidden" name="rx_id[]" value="MANUAL">
                  <input type="text" name="drug_name[]" list="drug_catalog" placeholder="Search Catalog..." required>
              </td>
              <td><input type="text" name="dose[]" placeholder="e.g. 1 tds"></td>
              <td><input type="number" name="days[]" value="1" min="1"></td>
              <td><input type="number" name="qty[]" class="qty-input" value="1" min="1" oninput="calcTotal(this)" required></td>
              <td><input type="number" step="0.01" name="rate[]" class="rate-input" placeholder="0.00" oninput="calcTotal(this)" required></td>
              <td><input type="number" step="0.01" name="total[]" class="total-input" value="0.00" readonly></td>
              <td style="text-align:center;">
                <button type="button" class="remove-btn" onclick="removeRow(this)" disabled style="opacity:0.3; cursor:not-allowed;"><i class="fa-solid fa-trash"></i></button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div style="margin-top: 15px;">
        <button type="button" class="btn btn-blue" onclick="addPrescriptionRow()"><i class="fa-solid fa-plus"></i> Add Another Item</button>
      </div>

      <div class="total-display">
          Total Amount to Collect: <span id="grandTotal">GHS 0.00</span>
      </div>

      <div class="actions">
        <button type="reset" class="btn btn-gold" onclick="resetForm()"><i class="fa-solid fa-rotate-left"></i> Reset Form</button>
        <button type="submit" class="btn btn-green" name="save_dispense"><i class="fa-solid fa-cash-register"></i> Dispense & Complete Sale</button>
      </div>

    </form>
  </div>
</div>

<script>
// ==========================================
// LIVE PATIENT SEARCH FOR OTC
// ==========================================
let searchTimer;
const searchInput = document.getElementById('liveSearchInput');
const resultsContainer = document.getElementById('searchResults');

if (searchInput) {
    searchInput.addEventListener('input', function(e) {
        clearTimeout(searchTimer);
        const query = e.target.value.trim();
        
        if (query.length < 2) {
            resultsContainer.style.display = 'none';
            return;
        }
        
        searchTimer = setTimeout(() => {
            fetch('?otc_search=' + encodeURIComponent(query))
            .then(res => res.json())
            .then(data => {
                resultsContainer.innerHTML = '';
                
                if (data.length === 0) {
                    resultsContainer.innerHTML = '<div style="padding:15px; text-align:center; color:#94a3b8;">No patients found. Proceed as Walk-In.</div>';
                } else {
                    data.forEach(p => {
                        const div = document.createElement('div');
                        div.className = 'search-item';
                        div.onclick = () => selectPatient(p.patient_no, p.first_name, p.last_name, p.mobile);
                        div.innerHTML = `
                            <div class="search-item-name">${p.first_name} ${p.last_name}</div>
                            <div class="search-item-meta"><i class="fa-solid fa-hashtag"></i> ${p.patient_no} &nbsp;|&nbsp; <i class="fa-solid fa-phone"></i> ${p.mobile}</div>
                        `;
                        resultsContainer.appendChild(div);
                    });
                }
                resultsContainer.style.display = 'block';
            })
            .catch(err => console.error(err));
        }, 300); 
    });
    
    // Hide results if clicking outside
    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !resultsContainer.contains(e.target)) {
            resultsContainer.style.display = 'none';
        }
    });
}

function selectPatient(id, fname, lname, mobile) {
    document.getElementById('patient_no').value = id;
    document.getElementById('patient_name').value = fname + ' ' + lname;
    document.getElementById('mobile').value = mobile;
    
    // Make fields readonly to lock in the DB profile
    document.getElementById('patient_name').setAttribute('readonly', true);
    document.getElementById('mobile').setAttribute('readonly', true);
    
    searchInput.value = '';
    resultsContainer.style.display = 'none';
}

function resetForm() {
    document.getElementById('patient_no').value = 'WALK-IN';
    document.getElementById('patient_name').removeAttribute('readonly');
    document.getElementById('mobile').removeAttribute('readonly');
    setTimeout(updateGrandTotal, 100);
}

// ==========================================
// DYNAMIC TABLE & CALCULATIONS
// ==========================================
function calcTotal(input) {
    const row = input.closest('tr');
    const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
    const rate = parseFloat(row.querySelector('.rate-input').value) || 0;
    const totalCell = row.querySelector('.total-input');
    
    totalCell.value = (qty * rate).toFixed(2);
    updateGrandTotal();
}

function updateGrandTotal() {
    let total = 0;
    document.querySelectorAll('.total-input').forEach(el => {
        total += parseFloat(el.value) || 0;
    });
    document.getElementById('grandTotal').innerText = "GHS " + total.toFixed(2);
}

function addPrescriptionRow() {
    const tableBody = document.querySelector('#prescriptionTable tbody');
    const rowCount = tableBody.querySelectorAll('tr').length + 1;
    
    const mainRow = document.createElement('tr');
    mainRow.innerHTML = `
        <td style="text-align:center; font-weight:700;">${rowCount}</td>
        <td>
            <input type="hidden" name="rx_id[]" value="MANUAL">
            <input type="text" name="drug_name[]" list="drug_catalog" placeholder="Search Catalog..." required>
        </td>
        <td><input type="text" name="dose[]" placeholder="e.g. 1 tds"></td>
        <td><input type="number" name="days[]" value="1" min="1"></td>
        <td><input type="number" name="qty[]" class="qty-input" value="1" min="1" oninput="calcTotal(this)" required></td>
        <td><input type="number" step="0.01" name="rate[]" class="rate-input" placeholder="0.00" oninput="calcTotal(this)" required></td>
        <td><input type="number" step="0.01" name="total[]" class="total-input" value="0.00" readonly></td>
        <td style="text-align:center;">
            <button type="button" class="remove-btn" onclick="removeRow(this)"><i class="fa-solid fa-trash"></i></button>
        </td>
    `;
    
    tableBody.appendChild(mainRow);
    reindexRows();
}

function removeRow(button) {
    button.closest('tr').remove();
    reindexRows();
    updateGrandTotal();
}

function reindexRows() {
    const rows = document.querySelectorAll('#prescriptionTable tbody tr');
    rows.forEach((row, index) => {
        row.querySelector('td:first-child').innerText = index + 1;
        // Ensure first row cannot be deleted
        const btn = row.querySelector('.remove-btn');
        if (index === 0 && rows.length === 1) {
            btn.disabled = true;
            btn.style.opacity = '0.3';
            btn.style.cursor = 'not-allowed';
        } else {
            btn.disabled = false;
            btn.style.opacity = '1';
            btn.style.cursor = 'pointer';
        }
    });
}
</script>
</body>
</html>