<?php
require_once '../config.php';
requirePatient();

$patient_id = $_SESSION['patient_id'];

$record_types = [
    'consultation'     => ['label'=>'Consultation',        'fa'=>'fa-stethoscope',          'color'=>'primary'],
    'prescription'     => ['label'=>'Prescription',        'fa'=>'fa-prescription-bottle-alt','color'=>'success'],
    'lab_report'       => ['label'=>'Lab Report',          'fa'=>'fa-flask',                'color'=>'info'],
    'blood_test'       => ['label'=>'Blood Test',          'fa'=>'fa-tint',                 'color'=>'danger'],
    'xray'             => ['label'=>'X-Ray',               'fa'=>'fa-x-ray',                'color'=>'dark'],
    'mri'              => ['label'=>'MRI Report',          'fa'=>'fa-magnet',               'color'=>'secondary'],
    'ct_scan'          => ['label'=>'CT Scan',             'fa'=>'fa-microscope',           'color'=>'warning'],
    'ultrasound'       => ['label'=>'Ultrasound',          'fa'=>'fa-wave-square',          'color'=>'primary'],
    'vaccination'      => ['label'=>'Vaccination',         'fa'=>'fa-syringe',              'color'=>'success'],
    'health_assessment'=> ['label'=>'Health Assessment',   'fa'=>'fa-chart-bar',            'color'=>'info'],
    'doctor_note'      => ['label'=>"Doctor's Note",       'fa'=>'fa-sticky-note',          'color'=>'secondary'],
    'other'            => ['label'=>'Other',               'fa'=>'fa-paperclip',            'color'=>'secondary'],
];

$errors = [];

// Handle upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_record'])) {
    $title       = clean($_POST['title'] ?? '');
    $record_type = clean($_POST['record_type'] ?? '');
    $description = clean($_POST['description'] ?? '');
    $record_date = clean($_POST['record_date'] ?? date('Y-m-d'));
    $doctor_name = clean($_POST['doctor_name'] ?? '');

    if (empty($title))                               $errors[] = 'Title is required.';
    if (!array_key_exists($record_type, $record_types)) $errors[] = 'Invalid record type.';

    $file_path = null;
    if (!empty($_FILES['record_file']['name'])) {
        $file_path = uploadFile($_FILES['record_file'], 'medical_records', ['jpg','jpeg','png','pdf','doc','docx']);
        if ($file_path === false) $errors[] = 'Invalid file type. Allowed: JPG, PNG, PDF, DOC';
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO medical_records (patient_id, record_type, title, description, record_date, file_path, doctor_name, is_visible_to_patient, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, NOW())");
        $stmt->bind_param('issssss', $patient_id, $record_type, $title, $description, $record_date, $file_path, $doctor_name);
        if ($stmt->execute()) {
            setFlash('success', 'Record uploaded successfully!');
            header('Location: health-records.php');
            exit;
        }
        $errors[] = 'Upload failed. Please try again.';
    }
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $del_id = (int)$_POST['delete_id'];
    $conn->query("DELETE FROM medical_records WHERE id=$del_id AND patient_id=$patient_id");
    setFlash('success', 'Record deleted.');
    header('Location: health-records.php');
    exit;
}

// Fetch records
$type_filter = clean($_GET['type'] ?? '');
$where_type  = $type_filter && array_key_exists($type_filter, $record_types) ? "AND record_type='$type_filter'" : '';

$records = $conn->query("
    SELECT mr.*, d.full_name as linked_doctor
    FROM medical_records mr
    LEFT JOIN doctors d ON mr.doctor_id = d.id
    WHERE mr.patient_id = $patient_id $where_type
    ORDER BY mr.record_date DESC, mr.created_at DESC
")->fetch_all(MYSQLI_ASSOC);

// Counts per type
$total = $conn->query("SELECT COUNT(*) FROM medical_records WHERE patient_id=$patient_id")->fetch_row()[0];
$type_counts = [];
foreach ($record_types as $k => $v) {
    $type_counts[$k] = $conn->query("SELECT COUNT(*) FROM medical_records WHERE patient_id=$patient_id AND record_type='$k'")->fetch_row()[0];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Health Records - HealthLink</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    body { background: #f0f4ff; font-family: Inter, 'Segoe UI', sans-serif; }
    .card { border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 10px rgba(11,74,203,0.07); }
    .top-bar { background:#fff; border-bottom:1px solid #e2e8f0; padding:14px 28px; display:flex; align-items:center; justify-content:space-between; box-shadow:0 1px 8px rgba(11,74,203,.07); }
    .top-bar h5 { margin:0; font-size:16px; font-weight:700; color:#0f172a; }
    .page-body { padding:26px 28px; }
    .type-pill { cursor:pointer; border-radius:10px; padding:7px 14px; font-size:12px; font-weight:600; white-space:nowrap; transition:all .2s; text-decoration:none; border:1.5px solid #e2e8f0; background:#fff; color:#64748b; display:inline-flex; align-items:center; gap:5px; }
    .type-pill:hover { border-color:#0B4ACB; color:#0B4ACB; }
    .type-pill.active { background:linear-gradient(135deg,#0B4ACB,#3B63E6); color:#fff; border-color:#0B4ACB; box-shadow:0 4px 12px rgba(11,74,203,.25); }
    .type-pill.active .tp-badge { background:rgba(255,255,255,.25); color:#fff; }
    .tp-badge { background:#f1f5f9; color:#64748b; font-size:10px; font-weight:700; padding:1px 6px; border-radius:20px; }
    .record-row { padding:14px 20px; border-bottom:1px solid #f0f4ff; display:flex; align-items:flex-start; gap:14px; transition:background .15s; }
    .record-row:last-child { border-bottom:none; }
    .record-row:hover { background:#f8faff; }
    .record-icon { font-size:1.8rem; width:42px; text-align:center; flex-shrink:0; margin-top:2px; }
    .upload-zone { border:2px dashed #c7d7fc; border-radius:14px; padding:20px; background:#f8faff; transition:all .2s; }
    .upload-zone:hover { border-color:#0B4ACB; background:#eff4ff; }
    .modal-content { border-radius:16px; }
    .stat-type-card { border-radius:14px; border:1.5px solid #e2e8f0; background:#fff; padding:14px 10px; text-align:center; transition:all .2s; text-decoration:none; display:block; }
    .stat-type-card:hover { border-color:#0B4ACB; background:#eff4ff; transform:translateY(-2px); }
    .stat-type-card.active { border-color:#0B4ACB; background:linear-gradient(135deg,#eff4ff,#dbeafe); }
    .btn-blue { background:linear-gradient(135deg,#0B4ACB,#3B63E6); color:#fff !important; border:none; padding:8px 18px; border-radius:10px; font-size:13px; font-weight:600; cursor:pointer; transition:all .2s; text-decoration:none; display:inline-flex; align-items:center; gap:6px; }
    .btn-blue:hover { opacity:.9; transform:translateY(-1px); }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="main-content">
<?php $page_title = 'Health Records'; include 'topbar.php'; ?>

  <div class="page-body">
    <?php displayFlash(); ?>

    <?php if (!empty($errors)): ?>
      <div class="alert alert-danger"><ul class="mb-0"><?php foreach($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?></ul></div>
    <?php endif; ?>

    <!-- Stats Bar -->
    <div class="row g-2 mb-4">
      <?php foreach (array_slice($record_types, 0, 6, true) as $k => $rt): ?>
        <div class="col-4 col-md-2">
          <a href="?type=<?= $k ?>" class="stat-type-card <?= $type_filter===$k?'active':'' ?>">
            <i class="fas <?= $rt['fa'] ?>" style="font-size:1.4rem;color:#0B4ACB;"></i>
            <div style="font-size:11px;font-weight:700;color:#0f172a;line-height:1.2;margin-top:4px;"><?= $rt['label'] ?></div>
            <div style="font-size:12px;font-weight:800;color:#0B4ACB;margin-top:3px;"><?= $type_counts[$k] ?></div>
          </a>
        </div>
      <?php endforeach; ?>
    </div>

    <!-- Type Filter Scrollable -->
    <div class="d-flex gap-2 mb-3 flex-wrap">
      <a href="health-records.php" class="type-pill <?= !$type_filter?'active':'' ?>">
        All <span class="tp-badge"><?= $total ?></span>
      </a>
      <?php foreach ($record_types as $k => $rt): ?>
        <a href="?type=<?= $k ?>" class="type-pill <?= $type_filter===$k?'active':'' ?>">
          <i class="fas <?= $rt['fa'] ?>"></i> <?= $rt['label'] ?>
          <?php if ($type_counts[$k]): ?><span class="tp-badge"><?= $type_counts[$k] ?></span><?php endif; ?>
        </a>
      <?php endforeach; ?>
    </div>

    <!-- Records List -->
    <div class="card">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-700">
          <?= $type_filter ? ('<i class="fas '.$record_types[$type_filter]['fa'].' me-1"></i>'.$record_types[$type_filter]['label']) : '<i class="fas fa-folder-open me-1"></i>All Records' ?>
          <span class="badge bg-secondary ms-2"><?= count($records) ?></span>
        </h6>
        <button class="btn-blue" data-bs-toggle="modal" data-bs-target="#uploadModal" style="padding:6px 14px;font-size:12px;">
          <i class="fas fa-upload"></i>Upload
        </button>
      </div>

      <?php if (empty($records)): ?>
        <div class="p-5 text-center text-muted">
          <i class="fas fa-folder-open fa-4x mb-3" style="opacity:0.2;"></i>
          <h5>No records found</h5>
          <p>Upload your medical records using the button above.</p>
        </div>
      <?php else: ?>
        <?php foreach ($records as $r):
          $rt = $record_types[$r['record_type']] ?? ['fa'=>'fa-paperclip','label'=>'Record','color'=>'secondary'];
          $display_doctor = $r['linked_doctor'] ?? $r['doctor_name'] ?? '';
        ?>
          <div class="record-row">
            <div class="record-icon"><i class="fas <?= $rt['fa'] ?>" style="font-size:1.4rem;color:#0B4ACB;"></i></div>
            <div class="flex-grow-1">
              <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
                <div>
                  <div style="font-weight:700;font-size:0.9rem;"><?= htmlspecialchars($r['title']) ?></div>
                  <div class="mt-1 d-flex flex-wrap gap-2 align-items-center">
                    <span class="badge bg-<?= $rt['color'] ?>" style="font-size:0.68rem;"><?= $rt['label'] ?></span>
                    <?php if ($display_doctor): ?>
                      <span class="text-muted" style="font-size:0.75rem;"><i class="fas fa-user-md me-1"></i>Dr. <?= htmlspecialchars($display_doctor) ?></span>
                    <?php endif; ?>
                    <span class="text-muted" style="font-size:0.75rem;"><i class="fas fa-calendar me-1"></i><?= date('d M Y', strtotime($r['record_date'])) ?></span>
                  </div>
                  <?php if ($r['description']): ?>
                    <div style="font-size:0.78rem;color:#718096;margin-top:4px;"><?= htmlspecialchars(substr($r['description'],0,120)) ?><?= strlen($r['description'])>120?'...':'' ?></div>
                  <?php endif; ?>
                </div>
                <div class="d-flex gap-1 align-items-start">
                  <?php if ($r['file_path']): ?>
                    <a href="<?= SITE_URL ?>/<?= $r['file_path'] ?>" target="_blank" class="btn btn-sm" style="background:#eff4ff;color:#0B4ACB;border:1px solid #c7d7fc;font-size:11px;font-weight:600;">
                      <i class="fas fa-eye"></i> View
                    </a>
                    <a href="<?= SITE_URL ?>/<?= $r['file_path'] ?>" download class="btn btn-sm" style="background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;font-size:11px;">
                      <i class="fas fa-download"></i>
                    </a>
                  <?php else: ?>
                    <span class="text-muted" style="font-size:0.72rem;">No file</span>
                  <?php endif; ?>
                  <form method="POST" onsubmit="return confirm('Delete this record?')">
                    <input type="hidden" name="delete_id" value="<?= $r['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger" style="font-size:0.75rem;"><i class="fas fa-trash"></i></button>
                  </form>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content">
      <div class="modal-header border-0">
        <h5 class="modal-title fw-700"><i class="fas fa-upload me-2" style="color:#0B4ACB"></i>Upload Medical Record</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" enctype="multipart/form-data">
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-600">Record Type *</label>
              <select name="record_type" class="form-select" required>
                <option value="">Select type...</option>
                <?php foreach ($record_types as $k => $rt): ?>
                  <option value="<?= $k ?>" <?= ($_POST['record_type']??'')===$k?'selected':'' ?>><i class="fas <?= $rt['fa'] ?>"></i> <?= $rt['label'] ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Title / Name *</label>
              <input type="text" name="title" class="form-control" placeholder="e.g. Complete Blood Count July 2025" value="<?= htmlspecialchars($_POST['title']??'') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Date of Record</label>
              <input type="date" name="record_date" class="form-control" value="<?= $_POST['record_date'] ?? date('Y-m-d') ?>" max="<?= date('Y-m-d') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Doctor Name (Optional)</label>
              <input type="text" name="doctor_name" class="form-control" placeholder="e.g. Dr. Ahmed Khan" value="<?= htmlspecialchars($_POST['doctor_name']??'') ?>">
            </div>
            <div class="col-md-12">
              <label class="form-label fw-600">Description / Notes</label>
              <textarea name="description" class="form-control" rows="2" placeholder="Any additional notes about this record..."><?= htmlspecialchars($_POST['description']??'') ?></textarea>
            </div>
            <div class="col-md-12">
              <label class="form-label fw-600">Attach File <small class="text-muted fw-400">(JPG, PNG, PDF, DOC - Max 5MB)</small></label>
              <div class="upload-zone">
                <input type="file" name="record_file" class="form-control" accept=".jpg,.jpeg,.png,.pdf,.doc,.docx">
                <div class="text-center text-muted mt-2" style="font-size:0.78rem;">
                  <i class="fas fa-cloud-upload-alt fa-2x mb-1 d-block" style="color:#0B4ACB;opacity:0.5;"></i>
                  Click to browse or drag & drop your file here
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer border-0">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" name="upload_record" class="btn-blue">
            <i class="fas fa-upload"></i>Upload Record
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<?php if (!empty($errors)): ?>
<script>new bootstrap.Modal(document.getElementById('uploadModal')).show();</script>
<?php endif; ?>
</body>
</html>
