<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: /login.php');
    exit;
}

$name = $_SESSION['user_name'] ?? 'User';
$email = $_SESSION['user_email'] ?? '';
$role = $_SESSION['user_role'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Caregiver Deluxe Dashboard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      font-family: Arial, sans-serif;
      background: #f4f7fb;
      margin: 0;
      padding: 40px;
    }

    .card {
      max-width: 900px;
      margin: 0 auto;
      background: #fff;
      padding: 32px;
      border-radius: 14px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.10);
    }

    h1 {
      margin-top: 0;
      margin-bottom: 10px;
    }

    h3 {
      margin-top: 30px;
      margin-bottom: 12px;
    }

    .meta {
      color: #555;
      margin-bottom: 24px;
      line-height: 1.7;
    }

    form {
      margin-bottom: 20px;
    }

    input,
    select,
    button,
    textarea {
      width: 100%;
      padding: 12px;
      margin-bottom: 12px;
      border: 1px solid #ccc;
      border-radius: 8px;
      box-sizing: border-box;
      font-size: 14px;
    }

    button {
      background: #2563eb;
      color: #fff;
      border: 0;
      cursor: pointer;
    }

    button:hover {
      background: #1d4ed8;
    }

    ul {
      padding-left: 20px;
    }

    li {
      margin-bottom: 8px;
    }

    a.button {
      display: inline-block;
      padding: 10px 16px;
      background: #dc2626;
      color: #fff;
      text-decoration: none;
      border-radius: 8px;
      margin-top: 20px;
    }

    a.button:hover {
      background: #b91c1c;
    }

    .section {
      border-top: 1px solid #e5e7eb;
      padding-top: 24px;
      margin-top: 24px;
    }
  </style>
</head>
<body>
  <div class="card">
    <h1>Caregiver Deluxe</h1>

    <div class="meta">
      <strong>Welcome:</strong> <?php echo htmlspecialchars($name); ?><br>
      <strong>Email:</strong> <?php echo htmlspecialchars($email); ?><br>
      <strong>Role:</strong> <?php echo htmlspecialchars($role); ?>
    </div>

    <div class="section">
      <h3>Add Patient</h3>

      <form id="patientForm">
        <input type="text" id="name" placeholder="Patient Name" required>
        <input type="date" id="dob">
        <input type="text" id="notes" placeholder="Notes">
        <button type="submit">Add Patient</button>
      </form>

      <h3>Patients</h3>
      <ul id="patientList"></ul>
    </div>

    <div class="section">
      <h3>Add Medication</h3>

      <form id="medForm">
        <select id="med_patient_id" required>
          <option value="">Select Patient</option>
        </select>
        <input type="text" id="med_name" placeholder="Medication Name" required>
        <input type="text" id="med_dosage" placeholder="Dosage">
        <input type="text" id="med_instructions" placeholder="Instructions">
        <button type="submit">Add Medication</button>
      </form>

      <h3>Medications</h3>
      <ul id="medList"></ul>
    </div>

    <a class="button" href="/logout.php">Log Out</a>
  </div>

  <script>
    let patientsCache = [];

    async function loadPatients() {
      const res = await fetch('/api/patients.php');
      const data = await res.json();

      const list = document.getElementById('patientList');
      const select = document.getElementById('med_patient_id');

      list.innerHTML = '';
      select.innerHTML = '<option value="">Select Patient</option>';
      patientsCache = data.patients || [];

      patientsCache.forEach(p => {
        const li = document.createElement('li');
        li.textContent = p.name + (p.dob ? ' (' + p.dob + ')' : '');
        list.appendChild(li);

        const option = document.createElement('option');
        option.value = p.id;
        option.textContent = p.name;
        select.appendChild(option);
      });
    }

    async function loadMedications(patientId) {
      const list = document.getElementById('medList');
      list.innerHTML = '';

      if (!patientId) return;

      const res = await fetch('/api/medications.php?patient_id=' + encodeURIComponent(patientId));
      const data = await res.json();

      if (data.medications) {
        data.medications.forEach(m => {
          const li = document.createElement('li');
          let text = m.name;
          if (m.dosage) text += ' - ' + m.dosage;
          if (m.instructions) text += ' - ' + m.instructions;
          li.textContent = text;
          list.appendChild(li);
        });
      }
    }

    document.getElementById('patientForm').addEventListener('submit', async (e) => {
      e.preventDefault();

      const formData = new FormData();
      formData.append('name', document.getElementById('name').value);
      formData.append('dob', document.getElementById('dob').value);
      formData.append('notes', document.getElementById('notes').value);

      await fetch('/api/patients.php', {
        method: 'POST',
        body: formData
      });

      document.getElementById('patientForm').reset();
      await loadPatients();
    });

    document.getElementById('med_patient_id').addEventListener('change', function() {
      loadMedications(this.value);
    });

    document.getElementById('medForm').addEventListener('submit', async (e) => {
      e.preventDefault();

      const formData = new FormData();
      formData.append('patient_id', document.getElementById('med_patient_id').value);
      formData.append('name', document.getElementById('med_name').value);
      formData.append('dosage', document.getElementById('med_dosage').value);
      formData.append('instructions', document.getElementById('med_instructions').value);

      await fetch('/api/medications.php', {
        method: 'POST',
        body: formData
      });

      const selectedPatient = document.getElementById('med_patient_id').value;
      document.getElementById('med_name').value = '';
      document.getElementById('med_dosage').value = '';
      document.getElementById('med_instructions').value = '';

      loadMedications(selectedPatient);
    });

    loadPatients();
  </script>
</body>
</html>