<?php
include './layouts/header.php';
include './layouts/navbar.php';
include './layouts/sidebar.php';


?>
<?php
include './database/config.php';

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $patient_id   = $_POST['name'] ?? null;
    $age          = trim($_POST['age'] ?? '');
    $gender       = trim($_POST['gender'] ?? '');
    $course_year  = trim($_POST['course_year'] ?? '');
    $dob          = trim($_POST['dob'] ?? '');
    $civil_status = trim($_POST['civil_status'] ?? '');
    $religion     = trim($_POST['religion'] ?? '');
    $address      = trim($_POST['address'] ?? '');
    $guardian     = trim($_POST['guardian'] ?? '');
    $cp_no        = trim($_POST['cp_no'] ?? '');

    $decayed = $_POST['decayed'] ?? 0;
    $missing = $_POST['missing'] ?? 0;
    $filled  = $_POST['filled'] ?? 0;
    $total   = $_POST['total'] ?? 0;

    $errors = [];

    if (empty($patient_id))   $errors[] = " student name is required.";
    if (empty($age) || !is_numeric($age) || $age <= 0) $errors[] = "Valid age is required.";
    if (empty($gender))       $errors[] = "Gender is required.";
    if (empty($dob))          $errors[] = "Date of birth is required.";
    if (empty($civil_status)) $errors[] = "Civil status is required.";
    if (empty($religion))     $errors[] = "Religion is required.";
    if (empty($address))      $errors[] = "Address is required.";
    if (empty($guardian))     $errors[] = "Guardian name is required.";
    if (empty($cp_no))        $errors[] = "Contact number is required.";

    foreach (['decayed', 'missing', 'filled', 'total'] as $field) {
        if (!is_numeric($$field)) {
            $errors[] = ucfirst($field) . " must be a number.";
        }
    }

    // ✅ Validation Errors (SweetAlert)
 if (!empty($errors)) {
    echo "
    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
    <script>
        Swal.fire({
            icon: 'warning',
            title: 'Please fix the following errors:',
            html: '" . implode("<br>", $errors) . "',
            confirmButtonColor: '#3085d6'
        }).then(() => {
            window.location.href = 'oral-health.php';
        });
    </script>";
    exit();
}


    $treatments = [];
    for ($i = 1; $i <= 4; $i++) {
        if (!empty($_POST["date$i"]) || !empty($_POST["tooth_no$i"]) || !empty($_POST["operation$i"])) {
            $treatments[] = [
                'date'      => $_POST["date$i"] ?? null,
                'tooth_no'  => $_POST["tooth_no$i"] ?? null,
                'operation' => $_POST["operation$i"] ?? null,
                'remarks'   => $_POST["remarks$i"] ?? null,
                'dentist'   => $_POST["dentist$i"] ?? null
            ];
        }
    }

    $sql = "INSERT INTO dental_record
            (patient_id, age, gender, course_year, dob, civil_status, religion, address, guardian, cp_no, decayed, missing, filled, total, date_created)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        "issssssssiiiii",
        $patient_id, $age, $gender, $course_year, $dob, $civil_status,
        $religion, $address, $guardian, $cp_no, $decayed, $missing, $filled, $total
    );

    if ($stmt->execute()) {
        $record_id = $stmt->insert_id;

        $sql2 = "INSERT INTO treatment_recordsss (record_id, treatment_date, tooth_no, operation, remarks, dentist)
                 VALUES (?, ?, ?, ?, ?, ?)";
        $stmt2 = $conn->prepare($sql2);

        foreach ($treatments as $t) {
            $stmt2->bind_param(
                "isssss",
                $record_id,
                $t['date'],
                $t['tooth_no'],
                $t['operation'],
                $t['remarks'],
                $t['dentist']
            );
            $stmt2->execute();
        }

        // ✅ Success Message
        echo "
        <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon: 'success',
                title: 'Dental Record Saved!',
                text: 'The record has been successfully added.',
                confirmButtonColor: '#3085d6'
            }).then(() => {
                window.location.href = 'oral-health.php';
            });
        </script>";
    } else {
        // ❌ Error Message
        echo "
        <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon: 'error',
                title: 'Error saving record!',
                text: '" . addslashes($stmt->error) . "',
                confirmButtonColor: '#d33'
            }).then(() => { window.history.back(); });
        </script>";
    }

    $stmt->close();
    $conn->close();
}
?>




<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Oral Health Examination Record</title>
<style>
body {
  font-family: Arial, sans-serif;
  background: #f5f5f5;
}

.form-container {
  background: white;
   width: 83%;
  margin: 30px auto;
  padding: 25px 40px;
  margin-left: 17%;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

/* Header */
h2, h3 { text-align: center; margin: 5px 0; }
.header { text-align: center; }
.header img { width: 90px; margin-bottom: 10px; }

/* Tables */
table { width: 100%; border-collapse: collapse; margin-top: 5px; font-size: 14px; }
td, th { padding: 5px; vertical-align: top; }
.input-line { border-bottom: 1px solid #000; display: inline-block; min-width: 120px; height: 18px; }

/* Section titles */
.section-title { font-weight: bold; margin-top: 15px; text-decoration: underline; }

/* Dentition Diagram */
.dentition-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #eef;
  border: 1px solid #999;
  padding: 15px;
  width: max-content;
  margin: 10px auto;
}
.tooth-row { display: flex; justify-content: center; margin: 5px 0; }
.tooth {
  width: 32px; height: 32px;
  border: 2px solid #000;
  margin: 2px;
  position: relative;
  background: #fff;
  cursor: pointer;
  transition: 0.2s;
  user-select: none;
}
.tooth::before {
  content: "";
  position: absolute;
  top: 4px; left: 4px; right: 4px; bottom: 4px;
  border: 2px solid #000;
}
.tooth-symbol {
  position: absolute;
  top: 3px; left: 6px;
  font-weight: bold;
  font-size: 16px;
  color: red;
}
.tooth-number { font-size: 11px; text-align: center; width: 32px; margin-top: 3px; }

.treatment-record, .index-table {
  width: 100%; border: 1px solid #000; margin-top: 10px; border-collapse: collapse;
}
.treatment-record th, .treatment-record td,
.index-table th, .index-table td {
  border: 1px solid #000;
  text-align: center;
  padding: 4px;
}
.symbols { font-size: 14px; }

/* Popup menu */
.symbol-menu {
  position: absolute;
  background: white;
  border: 1px solid #000;
  box-shadow: 2px 2px 5px rgba(0,0,0,0.2);
  padding: 4px;
  display: none;
  z-index: 1000;
}
.symbol-menu button {
  display: block;
  width: 100%;
  border: none;
  background: none;
  padding: 4px 8px;
  text-align: left;
  cursor: pointer;
}
.symbol-menu button:hover { background: #ddd; }

/* Navigation buttons */
.nav-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
 .form-input {
    border: none;
    border-bottom: 1px solid #000;
    width: 100%;
    outline: none;
    font-size: 14px;
    padding: 2px 4px;
    background: transparent;
  }
button {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  background: #007bff;
  color: white;
  cursor: pointer;
}
button:hover { background: #0056b3; }

/* Section handling */
.section {
  display: none;
  animation: fadeIn 0.3s ease-in-out;
}
.section.active { display: block; }

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
<style>
  .index-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
    font-size: 14px;
  }
  .index-table th, .index-table td {
    border: 1px solid #000;
    padding: 6px;
    text-align: center;
  }
  .dmft-input {
    border: none;
    border-bottom: 1px solid #000;
    width: 80%;
    text-align: center;
    outline: none;
    background: transparent;
    font-size: 14px;
    padding: 2px 4px;
  }
  .flex{
    display: flex;
    align-items: center;   /* vertically center items */
    margin-left:20%;
 
  }
</style>

</head>
<body>

<div class="form-container" style="">
  <div class="header">
    <div class="flex">
           <img src="./Image/462583214_2045801295879974_7463556676306348844_n.jpg" alt="College Logo">

    <h3>J.H. CERILLES STATE COLLEGE</h3>
    </div>

    <h2>ORAL HEALTH EXAMINATION RECORD FOR STUDENTS</h2>
  </div>

</select>
   <style>
        .form-input { padding: 5px; margin: 3px; }
    </style>
    <script>
    function fetchPatientDetails(id) {
        if (id === "") {
            // Clear all fields if no selection
            document.querySelector("input[name='age']").value = "";
            document.querySelector("input[name='course_year']").value = "";
            document.querySelector("input[name='dob']").value = "";
            document.querySelector("select[name='civil_status']").value = "";
            document.querySelector("input[name='religion']").value = "";
            document.querySelector("input[name='address']").value = "";
            document.querySelector("input[name='guardian']").value = "";
            document.querySelector("input[name='cp_no']").value = "";
            document.querySelector("select[name='gender']").value = "";
            return;
        }

        // AJAX request to fetch data
        const xhr = new XMLHttpRequest();
        xhr.open("GET", "fetch_patient.php?id=" + id, true);
        xhr.onload = function() {
            if (this.status === 200) {
                const data = JSON.parse(this.responseText);
                if (data) {
                    document.querySelector("input[name='age']").value = data.age || "";
                    document.querySelector("input[name='course_year']").value = data.course || "";
                    document.querySelector("input[name='dob']").value = data.dob || "";
                    document.querySelector("select[name='civil_status']").value = data.civil_status || "";
                    document.querySelector("input[name='religion']").value = data.religion || "";
                    document.querySelector("input[name='address']").value = data.address || "";
                    document.querySelector("input[name='guardian']").value = data.parent_guardian || "";
                    document.querySelector("input[name='cp_no']").value = data.contact_no || "";
                    document.querySelector("select[name='gender']").value = data.gender || "";
              
                                  document.querySelector("select[name='civil_status']").value = data.civil_status || "";

                }
            }
        };
        xhr.send();
    }
    </script>
  <!-- SECTION 1 -->
  <div class="section active" id="section1">
<form id="oralForm" method="POST">
<table>
  <tr>
    <td colspan="3">
      <label>Name: </label>
     <select name="name" class="form-input" onchange="fetchPatientDetails(this.value)">
    <option value="">-- Select Name --</option>
    <?php
    include './database/config.php';
    $userCampus = $_SESSION['campus'] ?? ''; // make sure campus is set

    // Correct query syntax
    $result = $conn->query("SELECT id, campus, name FROM patient_info WHERE campus = '$userCampus'");

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<option value='{$row['id']}'>{$row['name']}</option>";
        }
    } else {
        echo "<option disabled>No names found</option>";
    }
    ?>
</select>

    </td>
  </tr>

  <tr>
    <td>Age: <input type="number" name="age" class="form-input" style="width:80px;"></td>
    <td>Gender:
      <select name="gender" class="form-input" style="width:auto;">
        <option value="">Select</option>
        <option>Male</option>
        <option>Female</option>
      </select>
    </td>
    <td>Course/Year: <input type="text" name="course_year" class="form-input"></td>
  </tr>

  <tr>
    <td>Date of Birth: <input type="date" name="dob" class="form-input"></td>
    <td>Civil Status:
      <select name="civil_status" class="form-input" style="width:auto;">
        <option value="">Select</option>
        <option>single</option>
        <option>Married</option>

      </select>
    </td>
    <td>Religion: <input type="text" name="religion" class="form-input"></td>
  </tr>

  <tr>
    <td colspan="3">Address: <input type="text" name="address" class="form-input" style="width:90%;"></td>
  </tr>

  <tr>
    <td>Parents/Guardian: <input type="text" name="guardian" class="form-input"></td>
    <td colspan="2">CP No.: <input type="text" name="cp_no" class="form-input"></td>
  </tr>
</table>
    <div class="section-title">Medical History:</div>
    <table>
      <tr>
        <td><input type="checkbox"> Normal</td>
        <td><input type="checkbox"> Epilepsy</td>
        <td><input type="checkbox"> Allergies</td>
        <td><input type="checkbox"> Diabetes</td>
      </tr>
      <tr>
        <td><input type="checkbox"> Bleeding Disorder</td>
        <td><input type="checkbox"> Cardio Vascular Disorder</td>
        <td><input type="checkbox"> Asthma</td>
        <td>Others: <span class="input-line" style="min-width:150px;"></span></td>
      </tr>
    </table>
  </div>
<style>
.offset-left {
  margin-left: -9px; /* adjust as needed */


}
.upper-right-numbers {
  display: flex;
  justify-content: center;
  gap: 611%;           /* evenly spaced numbers */
}

.tooth-number {
  width: 36px;        /* same as .tooth width */
  text-align: center;
  font-size: 12px;
  font-weight: 600;
}

</style>


  <!-- SECTION 2 -->
  <div class="section" id="section2">
   <div class="dflex">
     <h3>DENTITION STATUS</h3>
    <div class="dentition-container">
      <div class="tooth-row" id="upper-right"></div>
<div class="tooth-row offset-left  space-between" id="upper-right-numbers"></div>

      <div class="tooth-row" id="upper-left"></div>
      <div class="tooth-row" id="upper-left-numbers"></div>

      <div class="tooth-row" id="lower-right"></div>
      <div class="tooth-row" id="lower-right-numbers"></div>

      <div class="tooth-row" id="lower-left"></div>
      <div class="tooth-row" id="lower-left-numbers"></div>
    </div>
  

  <!-- SECTION 3 -->
<div class="c1" style="margin-top: -30%; margin-left:2%">
  <div class="section-title">Symbols for Mouth Examination</div>
    <ul class="symbols">
      <li><b>X</b> - Indicated for extraction</li>
      <li><b>F</b> - Indicated for filling</li>
      <li><b>RF</b> - Root fragment</li>
      <li><b>O</b> - Missing tooth</li>
    </ul>


    <div class="section-title">Symbols for Accomplishment</div>
    <ul class="symbols">
      <li>OP - Oral Prophylaxis</li>
      <li>X - Extracted permanent tooth</li>
      <li>R - Referred to private dentist</li>
      <li>ZnO F - Zinc Oxide Filling</li>
       <li> GIC- Glass Ioner Cement</li>
    </ul>
  </div>
  </div>
<div class="cs" style="margin-left: 40%;margin-top:-20%">
 <table class="index-table" style="width: 40%; margin-left:60%;">
  <tr><th colspan="2">INDEX: DMFT</th></tr>
  <tr>
    <td>No. of Tooth Decayed (D)</td>
    <td><input type="number" name="decayed" id="decayed" class="dmft-input" min="0" value="0" oninput="calculateDMFT()"></td>
  </tr>
  <tr>
    <td>No. of Tooth Missing (M)</td>
    <td><input type="number" name="missing" id="missing" class="dmft-input" min="0" value="0" oninput="calculateDMFT()"></td>
  </tr>
  <tr>
    <td>No. of Tooth Filled (F)</td>
    <td><input type="number" name="filled" id="filled" class="dmft-input" min="0" value="0" oninput="calculateDMFT()"></td>
  </tr>
  <tr>
    <th>Total</th>
    <th><input type="number" name="total" id="total" class="dmft-input" readonly></th>
  </tr>
</table>
   </div>
</div>

<script>
function calculateDMFT() {
  // Get input values
  const decayed = parseInt(document.getElementById("decayed").value) || 0;
  const missing = parseInt(document.getElementById("missing").value) || 0;
  const filled = parseInt(document.getElementById("filled").value) || 0;

  // Calculate total
  const total = decayed + missing + filled;

  // Display total
  document.getElementById("total").value = total;
}
</script>

    

  <!-- SECTION 4 -->
  <div class="section" id="section4">
    <h4>Treatment Records</h4>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>Date</th>
            <th>Tooth No</th>
            <th>Operation</th>
            <th>Remarks</th>
            <th>Dentist</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody id="treatmentBody"></tbody>
</table>
<button type="button" id="addRowBtn" class="btn btn-primary">Add Treatment</button>

<script>
let rowCount = 0;
const dentistName = "KHARLOU C. TAGO M.D";

function addTreatmentRow() {
    const index = rowCount++;
    const row = document.createElement('tr');

    row.innerHTML = `
        <td><input type="date" name="treatments[${index}][date]" value="${new Date().toISOString().slice(0,10)}" class="form-control" required></td>
        <td><input type="number" name="treatments[${index}][tooth_no]" class="form-control" required></td>
        <td><input type="text" name="treatments[${index}][operation]" class="form-control" required></td>
        <td><input type="text" name="treatments[${index}][remarks]" class="form-control"></td>
        <td><input type="text" name="treatments[${index}][dentist]" class="form-control" value="${dentistName}" readonly></td>
        <td><button type="button" class="btn btn-danger btn-sm removeRow">Remove</button></td>
    `;

    row.querySelector('.removeRow').addEventListener('click', () => row.remove());
    document.getElementById('treatmentBody').appendChild(row);
}

window.addEventListener('DOMContentLoaded', () => addTreatmentRow());
document.getElementById('addRowBtn').addEventListener('click', addTreatmentRow);
</script>


  </div>

  


  <!-- Navigation Buttons -->
  <div class="nav-buttons">
 <button type="button" id="prevBtn" onclick="prevSection()">Previous</button>
<a href="manahge-healrjt.php" id="backLink" class="btn btn-secondary">Back</a>
<button type="button" id="nextBtn" onclick="nextSection()">Next</button>
<button type="submit" id="submitBtn" style="display:none;">Submit</button>

</div>

<!-- Popup menu -->
<div class="symbol-menu" id="symbolMenu">
  <button data-symbol="X">X - Extraction</button>
  <button data-symbol="F">F - Filling</button>
  <button data-symbol="RF">RF - Root Fragment</button>
  <button data-symbol="O">O - Missing</button>
    <button data-symbol="OP">OP - Oral Prophylaxis</button>
    <button data-symbol="X">X - Extracted permanent tooth</button>
    <button data-symbol="R">R - Referred to private dentist</button>
    <button data-symbol="ZnOF">ZnO F - Zinc Oxide Filling</button>
        <button data-symbol="GIC">GIC- Glass Ioner Cement</button>
  <hr>
  
  <button data-symbol="">Clear</button>
</div>
</form>
<script>
let currentSection = 1;
const sections = document.querySelectorAll(".section");
const totalSections = sections.length;
const backLink = document.getElementById("backLink");

function showSection(num) {
  sections.forEach((s, i) => {
    s.classList.toggle("active", i === num - 1);
  });

  // Control visibility of navigation buttons
  document.getElementById("prevBtn").style.display = num === 1 ? "none" : "inline-block";
  document.getElementById("nextBtn").style.display = num === totalSections ? "none" : "inline-block";
  document.getElementById("submitBtn").style.display = num === totalSections ? "inline-block" : "none";

  // ✅ Hide "Back" link after clicking Next (section > 1)
  backLink.style.display = num === 1 ? "inline-block" : "none";
}

function nextSection() {
  if (currentSection < totalSections) {
    currentSection++;
    showSection(currentSection);
  }
}

function prevSection() {
  if (currentSection > 1) {
    currentSection--;
    showSection(currentSection);
  }
}

// Initialize
showSection(currentSection);
</script>

<script>
// Create teeth
function createTeeth(containerId, labelContainerId, numbers) {
  const container = document.getElementById(containerId);
  const labelContainer = document.getElementById(labelContainerId);

  numbers.forEach(num => {
    const tooth = document.createElement('div');
    tooth.classList.add('tooth');

    const symbolSpan = document.createElement('div');
    symbolSpan.classList.add('tooth-symbol');
    tooth.appendChild(symbolSpan);

    const symbols = ["", "X", "F", "RF", "O","OP","X","R","ZnOF","GIC"];
    let index = 0;

    // Left-click to cycle symbols
    tooth.addEventListener('click', () => {
      index = (index + 1) % symbols.length;
      symbolSpan.textContent = symbols[index];
    });

    // Right-click for popup symbol menu
    tooth.addEventListener('contextmenu', e => {
      e.preventDefault();
      showSymbolMenu(e.pageX, e.pageY, symbolSpan);
    });

    container.appendChild(tooth);

    const label = document.createElement('div');
    label.classList.add('tooth-number');
    label.textContent = num;
    labelContainer.appendChild(label);
  });
}

// ✅ Permanent teeth (Adult: 11–48)
createTeeth("upper-right", "upper-right-numbers", [18,17,16,15,14,13,12,11]);
createTeeth("upper-left", "upper-left-numbers", [21,22,23,24,25,26,27,28]);
createTeeth("lower-right", "lower-right-numbers", [48,47,46,45,44,43,42,41]);
createTeeth("lower-left", "lower-left-numbers", [31,32,33,34,35,36,37,38]);

// ✅ Primary teeth (Child: 51–55, 61–65, 71–75, 81–85)
createTeeth("upper-right", "upper-right-numbers", [55,54,53,52,51]);
createTeeth("upper-left", "upper-left-numbers", [61,62,63,64,65]);
createTeeth("lower-right", "lower-right-numbers", [85,84,83,82,81]);
createTeeth("lower-left", "lower-left-numbers", [71,72,73,74,75]);

// Popup menu logic
const menu = document.getElementById("symbolMenu");
let currentSymbol = null;

function showSymbolMenu(x, y, symbolEl) {
  currentSymbol = symbolEl;
  menu.style.display = "block";
  menu.style.left = `${x}px`;
  menu.style.top = `${y}px`;
}

document.addEventListener("click", e => {
  if (!menu.contains(e.target)) menu.style.display = "none";
});

menu.querySelectorAll("button").forEach(btn => {
  btn.addEventListener("click", () => {
    if (currentSymbol) currentSymbol.textContent = btn.dataset.symbol;
    menu.style.display = "none";
  });
});
</script>

</body>
   <style>
  .treatment-record {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
    font-size: 14px;
  }

  .treatment-record th, .treatment-record td {
    border: 1px solid #000;
    padding: 6px;
    text-align: center;
  }

  .treatment-input {
    width: 100%;
    border: none;
    border-bottom: 1px solid #000;
    background: transparent;
    outline: none;
    font-size: 14px;
    text-align: center;
    padding: 2px 4px;
  }

  .treatment-textarea {
    width: 100%;
    border: none;
    border-bottom: 1px solid #000;
    background: transparent;
    outline: none;
    font-size: 14px;
    resize: none;
    height: 24px;
  }
</style>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.getElementById("oralForm").addEventListener("submit", function(e) {
  e.preventDefault(); // stop form from auto-submitting
  Swal.fire({
    title: "Are you sure?",
    text: "Do you want to submit this dental record?",
    icon: "question",
    showCancelButton: true,
    confirmButtonText: "Yes, submit",
    cancelButtonText: "Cancel",
    confirmButtonColor: "#3085d6",
    cancelButtonColor: "#d33"
  }).then((result) => {
    if (result.isConfirmed) {
      this.submit(); // continue form submission
    }
  });
});
</script>

</html>


