this error (Database Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (u406552082_info.patient_basic_info, CONSTRAINT patient_basic_info_ibfk_1 FOREIGN KEY (patient_id) REFERENCES patients (id) ON DELETE CASCADE ON UPDATE CASCADE)) i need to fix , first these pages i need to be working well (<?php
// pages/page1.php

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Initialize patient record if not already done
        if (!isset($_SESSION['patient_id'])) {
            // Insert a new patient with minimal data
            $stmt = $pdo->prepare("
                INSERT INTO patients (name, age, gender, email, registration_datetime) 
                VALUES (:name, :age, :gender, :email, NOW())
            ");
            $stmt->execute([
                ':name' => '',
                ':age' => NULL,
                ':gender' => NULL,
                ':email' => ''
            ]);
            $_SESSION['patient_id'] = $pdo->lastInsertId();
        }
        header("Location: page2.php");
        exit();
    } catch (PDOException $e) {
        $errors[] = "Database Error: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Begin Your Journey to a Longer Healthier Life</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Begin your journey to a longer healthier life</h2>
        </div>

        <div class="section">
            <h3>Welcome to Longeva Health Journey</h3>
            <p>Take our short, proprietary health survey for free.</p>
            <p>It will only take 10 minutes, and you will receive an initial assessment with key insights on how you can make simple adjustments to begin improving and optimizing your health.</p>
            <img src="../assets/images/questionnaire_icon.png" alt="Questionnaire Icon" style="width: 100px; height: 100px; display: block; margin: 20px auto;">
            
            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }
            ?>

            <form method="POST" action="">
                <input type="submit" value="Start Online Evaluation Now">
            </form>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page2.php

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['consent']) && $_POST['consent'] === 'accepted') {
        try {
            if (isset($_SESSION['patient_id'])) {
                // Check if consent already exists
                $stmt = $pdo->prepare("SELECT patient_id FROM patient_consent WHERE patient_id = ?");
                $stmt->execute([$_SESSION['patient_id']]);
                if ($stmt->rowCount() > 0) {
                    // Update existing consent
                    $stmt = $pdo->prepare("UPDATE patient_consent SET consent = ? WHERE patient_id = ?");
                    $stmt->execute(['accepted', $_SESSION['patient_id']]);
                } else {
                    // Insert new consent
                    $stmt = $pdo->prepare("INSERT INTO patient_consent (patient_id, consent) VALUES (?, ?)");
                    $stmt->execute([$_SESSION['patient_id'], 'accepted']);
                }
                header("Location: page3.php");
                exit();
            } else {
                $errors[] = "Session expired. Please start over.";
            }
        } catch (PDOException $e) {
            $errors[] = "Database Error: " . $e->getMessage();
        }
    } else {
        $errors[] = "You must accept the Privacy Policy to continue.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Privacy and Consent</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Longeva Center – Your Health, Our Priority</h2>
        </div>

        <div class="section">
            <h3>Privacy and Consent</h3>
            <p>To provide you with personalized health insights, we need to process your data. Please read our <a href="#">Privacy Policy</a> for more information.</p>

            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }
            ?>

            <form method="POST" action="">
                <div class="form-group">
                    <input type="checkbox" id="consent" name="consent" value="accepted">
                    <label for="consent">I accept the Privacy Policy</label>
                </div>
                <input type="submit" value="Continue">
            </form>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page3.php

// Enable error reporting for debugging (Remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Initialize variables
$errors = [];
$name = '';
$email = '';
$phone = '';
$gender = '';
$age = '';
$weight = '';
$height = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $name = isset($_POST['name']) ? htmlspecialchars(trim($_POST['name'])) : '';
    $email = isset($_POST['email']) ? filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL) : '';
    $phone = isset($_POST['phone']) ? htmlspecialchars(trim($_POST['phone'])) : '';
    $gender = isset($_POST['gender']) ? htmlspecialchars(trim($_POST['gender'])) : '';
    $age = isset($_POST['age']) ? intval($_POST['age']) : '';
    $weight = isset($_POST['weight']) ? floatval($_POST['weight']) : '';
    $height = isset($_POST['height']) ? floatval($_POST['height']) : '';

    // Basic validation
    if (empty($name)) {
        $errors[] = "Name is required.";
    }
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "A valid email is required.";
    }
    if (empty($phone)) {
        $errors[] = "Phone number is required.";
    } elseif (!preg_match('/^[0-9+\-\s()]{7,20}$/', $phone)) {
        $errors[] = "Please enter a valid phone number.";
    }
    if (empty($gender)) {
        $errors[] = "Gender is required.";
    }
    if (empty($age) || $age <= 0) {
        $errors[] = "Valid age is required.";
    }
    if (empty($weight) || $weight <= 0) {
        $errors[] = "Valid weight is required.";
    }
    if (empty($height) || $height <= 0) {
        $errors[] = "Valid height is required.";
    }

    if (empty($errors)) {
        try {
            if (isset($_SESSION['patient_id'])) {
                // Update existing record
                $stmt = $pdo->prepare("UPDATE patient_basic_info SET name = ?, email = ?, phone = ?, gender = ?, age = ?, weight = ?, height = ? WHERE patient_id = ?");
                $stmt->execute([$name, $email, $phone, $gender, $age, $weight, $height, $_SESSION['patient_id']]);
            } else {
                // Insert new record
                $stmt = $pdo->prepare("INSERT INTO patient_basic_info (name, email, phone, gender, age, weight, height) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $email, $phone, $gender, $age, $weight, $height]);

                // Get the auto-incremented patient_id and store it in session
                $_SESSION['patient_id'] = $pdo->lastInsertId();
            }
            // Redirect to page4.php
            header("Location: page4.php");
            exit();
        } catch (PDOException $e) {
            $errors[] = "Database Error: " . $e->getMessage();
        }
    }
}

// If 'patient_id' is set, fetch existing details to pre-fill the form
if (isset($_SESSION['patient_id']) && empty($_POST)) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM patient_basic_info WHERE patient_id = ?");
        $stmt->execute([$_SESSION['patient_id']]);
        $basic_info = $stmt->fetch();

        if ($basic_info) {
            $name = htmlspecialchars($basic_info['name']);
            $email = htmlspecialchars($basic_info['email']);
            $phone = htmlspecialchars($basic_info['phone']);
            $gender = htmlspecialchars($basic_info['gender']);
            $age = htmlspecialchars($basic_info['age']);
            $weight = htmlspecialchars($basic_info['weight']);
            $height = htmlspecialchars($basic_info['height']);
        }
    } catch (PDOException $e) {
        $errors[] = "Database Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tell Us About You</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Tell Us About You</h2>
        </div>

        <div class="section">
            <h3>Your Personal Information</h3>
            <p>Providing accurate information helps us serve you better.</p>

            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }
            ?>

            <form method="POST" action="">
                <!-- Name -->
                <div class="form-group">
                    <label for="name">Name:</label>
                    <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($name); ?>" required>
                </div>

                <!-- Email -->
                <div class="form-group">
                    <label for="email">Email:</label>
                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
                </div>
                
                <!-- Phone Number -->
                <div class="form-group">
                    <label for="phone">Phone Number:</label>
                    <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($phone); ?>" required>
                </div>

                <!-- Gender -->
                <div class="form-group">
                    <label for="gender">Gender:</label>
                    <select id="gender" name="gender" required>
                        <option value="">--Select Gender--</option>
                        <option value="Male" <?php if($gender == 'Male') echo 'selected'; ?>>Male</option>
                        <option value="Female" <?php if($gender == 'Female') echo 'selected'; ?>>Female</option>
                        <option value="Other" <?php if($gender == 'Other') echo 'selected'; ?>>Other</option>
                    </select>
                </div>

                <!-- Age -->
                <div class="form-group">
                    <label for="age">Age:</label>
                    <input type="number" id="age" name="age" min="0" value="<?php echo htmlspecialchars($age); ?>" required>
                </div>

                <!-- Weight -->
                <div class="form-group">
                    <label for="weight">Weight (kg):</label>
                    <input type="number" step="0.1" id="weight" name="weight" min="0" value="<?php echo htmlspecialchars($weight); ?>" required>
                </div>

                <!-- Height -->
                <div class="form-group">
                    <label for="height">Height (cm):</label>
                    <input type="number" step="0.1" id="height" name="height" min="0" value="<?php echo htmlspecialchars($height); ?>" required>
                </div>

                <input type="submit" value="Continue">
            </form>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page4.php

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Redirect to landing page if patient_id is not set
if (!isset($_SESSION['patient_id'])) {
    header("Location: ../index.php");
    exit();
}

$errors = [];
$exercise = '';
$diet = '';
$diet_specify = '';
$sleep = '';
$smoking = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $exercise = isset($_POST['exercise']) ? htmlspecialchars(trim($_POST['exercise'])) : '';
    $diet = isset($_POST['diet']) ? htmlspecialchars(trim($_POST['diet'])) : '';
    $diet_specify = isset($_POST['diet_specify']) ? htmlspecialchars(trim($_POST['diet_specify'])) : '';
    $sleep = isset($_POST['sleep']) ? htmlspecialchars(trim($_POST['sleep'])) : '';
    $smoking = isset($_POST['smoking']) ? htmlspecialchars(trim($_POST['smoking'])) : '';

    // Validate inputs
    if (empty($exercise)) {
        $errors[] = "Please specify how often you exercise.";
    }
    if (empty($diet)) {
        $errors[] = "Please specify if you follow any specific diet.";
    }
    if ($diet === 'Yes' && empty($diet_specify)) {
        $errors[] = "Please specify your diet.";
    }
    if (empty($sleep)) {
        $errors[] = "Please specify your average sleep.";
    }
    if (empty($smoking)) {
        $errors[] = "Please specify your smoking status.";
    }

    if (empty($errors)) {
        try {
            // Check if health_metrics already exists
            $stmt = $pdo->prepare("SELECT patient_id FROM patient_health_metrics WHERE patient_id = ?");
            $stmt->execute([$_SESSION['patient_id']]);
            if ($stmt->rowCount() > 0) {
                // Update existing record
                $stmt = $pdo->prepare("UPDATE patient_health_metrics SET exercise_frequency = ?, diet = ?, diet_specify = ?, sleep_average = ?, smoking_status = ? WHERE patient_id = ?");
                $stmt->execute([$exercise, $diet, $diet_specify, $sleep, $smoking, $_SESSION['patient_id']]);
            } else {
                // Insert new record
                $stmt = $pdo->prepare("INSERT INTO patient_health_metrics (patient_id, exercise_frequency, diet, diet_specify, sleep_average, smoking_status) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$_SESSION['patient_id'], $exercise, $diet, $diet_specify, $sleep, $smoking]);
            }

            header("Location: page5.php");
            exit();
        } catch (PDOException $e) {
            $errors[] = "Database Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Understanding Your Health</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // JavaScript to toggle the diet_specify field
        function toggleDietSpecify() {
            var dietSelect = document.getElementById('diet');
            var dietSpecifyDiv = document.getElementById('diet_specify_div');
            if (dietSelect.value === 'Yes') {
                dietSpecifyDiv.style.display = 'block';
                document.getElementById('diet_specify').required = true;
            } else {
                dietSpecifyDiv.style.display = 'none';
                document.getElementById('diet_specify').required = false;
                document.getElementById('diet_specify').value = '';
            }
        }

        window.onload = function() {
            toggleDietSpecify(); // Initial check
            document.getElementById('diet').addEventListener('change', toggleDietSpecify);
        };
    </script>
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Understanding Your Health</h2>
        </div>

        <div class="section">
            <h3>Understanding Your Health</h3>
            <p>Help us gain insights into your daily habits.</p>

            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }
            ?>

            <form method="POST" action="">
                <!-- Exercise Frequency -->
                <div class="form-group">
                    <label for="exercise">How often do you exercise?</label>
                    <select id="exercise" name="exercise" required>
                        <option value="">--Select Frequency--</option>
                        <option value="Daily" <?php if(isset($exercise) && $exercise == 'Daily') echo 'selected'; ?>>Daily</option>
                        <option value="Weekly" <?php if(isset($exercise) && $exercise == 'Weekly') echo 'selected'; ?>>Weekly</option>
                        <option value="Rarely" <?php if(isset($exercise) && $exercise == 'Rarely') echo 'selected'; ?>>Rarely</option>
                        <option value="Never" <?php if(isset($exercise) && $exercise == 'Never') echo 'selected'; ?>>Never</option>
                    </select>
                </div>

                <!-- Diet -->
                <div class="form-group">
                    <label for="diet">Do you follow any specific diet?</label>
                    <select id="diet" name="diet" required>
                        <option value="">--Select Option--</option>
                        <option value="Yes" <?php if(isset($diet) && $diet == 'Yes') echo 'selected'; ?>>Yes</option>
                        <option value="No" <?php if(isset($diet) && $diet == 'No') echo 'selected'; ?>>No</option>
                    </select>
                </div>

                <!-- Specify Diet -->
                <div class="form-group" id="diet_specify_div" style="display: none;">
                    <label for="diet_specify">Please specify your diet:</label>
                    <input type="text" id="diet_specify" name="diet_specify" value="<?php echo isset($diet_specify) ? htmlspecialchars($diet_specify) : ''; ?>">
                </div>

                <!-- Sleep -->
                <div class="form-group">
                    <label for="sleep">How much sleep do you get on average?</label>
                    <select id="sleep" name="sleep" required>
                        <option value="">--Select Duration--</option>
                        <option value="<5 Hours" <?php if(isset($sleep) && $sleep == '<5 Hours') echo 'selected'; ?>>&lt;5 Hours</option>
                        <option value="5-7 Hours" <?php if(isset($sleep) && $sleep == '5-7 Hours') echo 'selected'; ?>>5-7 Hours</option>
                        <option value="7-9 Hours" <?php if(isset($sleep) && $sleep == '7-9 Hours') echo 'selected'; ?>>7-9 Hours</option>
                        <option value=">9 Hours" <?php if(isset($sleep) && $sleep == '>9 Hours') echo 'selected'; ?>>&gt;9 Hours</option>
                    </select>
                </div>

                <!-- Smoking Status -->
                <div class="form-group">
                    <label for="smoking">Smoking Status:</label>
                    <select id="smoking" name="smoking" required>
                        <option value="">--Select Option--</option>
                        <option value="Yes" <?php if(isset($smoking) && $smoking == 'Yes') echo 'selected'; ?>>Yes</option>
                        <option value="No" <?php if(isset($smoking) && $smoking == 'No') echo 'selected'; ?>>No</option>
                        <option value="Occasionally" <?php if(isset($smoking) && $smoking == 'Occasionally') echo 'selected'; ?>>Occasionally</option>
                    </select>
                </div>

                <input type="submit" value="Continue">
            </form>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page5.php

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Redirect to landing page if patient_id is not set
if (!isset($_SESSION['patient_id'])) {
    header("Location: ../index.php");
    exit();
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $chronic_conditions = isset($_POST['chronic_conditions']) ? htmlspecialchars(trim($_POST['chronic_conditions'])) : '';
    $chronic_conditions_specify = isset($_POST['chronic_conditions_specify']) ? htmlspecialchars(trim($_POST['chronic_conditions_specify'])) : '';
    $medications = isset($_POST['medications']) ? htmlspecialchars(trim($_POST['medications'])) : '';
    $medications_list = isset($_POST['medications_list']) ? htmlspecialchars(trim($_POST['medications_list'])) : '';
    $major_surgeries = isset($_POST['major_surgeries']) ? htmlspecialchars(trim($_POST['major_surgeries'])) : '';
    $major_surgeries_specify = isset($_POST['major_surgeries_specify']) ? htmlspecialchars(trim($_POST['major_surgeries_specify'])) : '';

    // Validate inputs
    if (empty($chronic_conditions)) {
        $errors[] = "Please specify if you have any chronic conditions.";
    }
    if ($chronic_conditions === 'Yes' && empty($chronic_conditions_specify)) {
        $errors[] = "Please specify your chronic conditions.";
    }
    if (empty($medications)) {
        $errors[] = "Please specify if you are taking any medications.";
    }
    if ($medications === 'Yes' && empty($medications_list)) {
        $errors[] = "Please list your medications.";
    }
    if (empty($major_surgeries)) {
        $errors[] = "Please specify if you have any history of major surgeries.";
    }
    if ($major_surgeries === 'Yes' && empty($major_surgeries_specify)) {
        $errors[] = "Please specify your major surgeries.";
    }

    if (empty($errors)) {
        try {
            // Check if medical_history already exists
            $stmt = $pdo->prepare("SELECT patient_id FROM patient_medical_history WHERE patient_id = ?");
            $stmt->execute([$_SESSION['patient_id']]);
            if ($stmt->rowCount() > 0) {
                // Update existing record
                $stmt = $pdo->prepare("
                    UPDATE patient_medical_history 
                    SET chronic_conditions = ?, chronic_conditions_specify = ?, medications = ?, medications_list = ?, major_surgeries = ?, major_surgeries_specify = ?
                    WHERE patient_id = ?
                ");
                $stmt->execute([
                    $chronic_conditions, 
                    $chronic_conditions_specify, 
                    $medications, 
                    $medications_list, 
                    $major_surgeries, 
                    $major_surgeries_specify, 
                    $_SESSION['patient_id']
                ]);
            } else {
                // Insert new record
                $stmt = $pdo->prepare("
                    INSERT INTO patient_medical_history 
                    (patient_id, chronic_conditions, chronic_conditions_specify, medications, medications_list, major_surgeries, major_surgeries_specify) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $_SESSION['patient_id'], 
                    $chronic_conditions, 
                    $chronic_conditions_specify, 
                    $medications, 
                    $medications_list, 
                    $major_surgeries, 
                    $major_surgeries_specify
                ]);
            }
            header("Location: page6.php");
            exit();
        } catch (PDOException $e) {
            $errors[] = "Database Error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Medical History</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Medical History</h2>
        </div>

        <div class="section">
            <h3>Medical History</h3>
            <p>Your current health condition matters.</p>

            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }
            ?>

            <form method="POST" action="">
                <!-- Chronic Conditions -->
                <div class="form-group">
                    <label for="chronic_conditions">Do you have any chronic conditions?</label>
                    <select id="chronic_conditions" name="chronic_conditions" required>
                        <option value="">--Select Option--</option>
                        <option value="Yes" <?php if(isset($chronic_conditions) && $chronic_conditions == 'Yes') echo 'selected'; ?>>Yes</option>
                        <option value="No" <?php if(isset($chronic_conditions) && $chronic_conditions == 'No') echo 'selected'; ?>>No</option>
                    </select>
                </div>

                <?php
                // Show specify input if chronic_conditions is 'Yes'
                if (isset($chronic_conditions) && $chronic_conditions === 'Yes') {
                    echo '<div class="form-group">';
                    echo '<label for="chronic_conditions_specify">Please specify your chronic conditions:</label>';
                    echo '<input type="text" id="chronic_conditions_specify" name="chronic_conditions_specify" value="'.htmlspecialchars($chronic_conditions_specify).'">';
                    echo '</div>';
                }
                ?>

                <!-- Medications -->
                <div class="form-group">
                    <label for="medications">Are you taking any medications?</label>
                    <select id="medications" name="medications" required>
                        <option value="">--Select Option--</option>
                        <option value="Yes" <?php if(isset($medications) && $medications == 'Yes') echo 'selected'; ?>>Yes</option>
                        <option value="No" <?php if(isset($medications) && $medications == 'No') echo 'selected'; ?>>No</option>
                    </select>
                </div>

                <?php
                // Show medications_list input if medications is 'Yes'
                if (isset($medications) && $medications === 'Yes') {
                    echo '<div class="form-group">';
                    echo '<label for="medications_list">Please list your medications:</label>';
                    echo '<textarea id="medications_list" name="medications_list" rows="4" required>'.htmlspecialchars($medications_list).'</textarea>';
                    echo '</div>';
                }
                ?>

                <!-- Major Surgeries -->
                <div class="form-group">
                    <label for="major_surgeries">Any history of major surgeries?</label>
                    <select id="major_surgeries" name="major_surgeries" required>
                        <option value="">--Select Option--</option>
                        <option value="Yes" <?php if(isset($major_surgeries) && $major_surgeries == 'Yes') echo 'selected'; ?>>Yes</option>
                        <option value="No" <?php if(isset($major_surgeries) && $major_surgeries == 'No') echo 'selected'; ?>>No</option>
                    </select>
                </div>

                <?php
                // Show major_surgeries_specify input if major_surgeries is 'Yes'
                if (isset($major_surgeries) && $major_surgeries === 'Yes') {
                    echo '<div class="form-group">';
                    echo '<label for="major_surgeries_specify">Please specify your major surgeries:</label>';
                    echo '<input type="text" id="major_surgeries_specify" name="major_surgeries_specify" value="'.htmlspecialchars($major_surgeries_specify).'">';
                    echo '</div>';
                }
                ?>

                <input type="submit" value="Continue">
            </form>
        </div>
    </div>

    <script>
        // Enable or disable specify fields based on selection
        document.getElementById('chronic_conditions').addEventListener('change', function() {
            var specifyInput = document.getElementById('chronic_conditions_specify');
            if (this.value === 'Yes') {
                specifyInput.disabled = false;
                specifyInput.required = true;
            } else {
                specifyInput.disabled = true;
                specifyInput.required = false;
                specifyInput.value = '';
            }
        });

        document.getElementById('medications').addEventListener('change', function() {
            var textarea = document.getElementById('medications_list');
            if (this.value === 'Yes') {
                textarea.disabled = false;
                textarea.required = true;
            } else {
                textarea.disabled = true;
                textarea.required = false;
                textarea.value = '';
            }
        });

        document.getElementById('major_surgeries').addEventListener('change', function() {
            var specifyInput = document.getElementById('major_surgeries_specify');
            if (this.value === 'Yes') {
                specifyInput.disabled = false;
                specifyInput.required = true;
            } else {
                specifyInput.disabled = true;
                specifyInput.required = false;
                specifyInput.value = '';
            }
        });
    </script>
</body>
</html>) and (<?php
// pages/page6.php

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Redirect to landing page if patient_id is not set
if (!isset($_SESSION['patient_id'])) {
    header("Location: ../index.php");
    exit();
}

$errors = [];
$additional_goal = '';
$additional_concern = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $primary_goals = isset($_POST['primary_goals']) ? $_POST['primary_goals'] : [];
    $additional_goal = isset($_POST['additional_goal']) ? htmlspecialchars(trim($_POST['additional_goal'])) : '';
    $health_concerns = isset($_POST['health_concerns']) ? $_POST['health_concerns'] : [];
    $additional_concern = isset($_POST['additional_concern']) ? htmlspecialchars(trim($_POST['additional_concern'])) : '';

    // Validate inputs
    if (empty($primary_goals)) {
        $errors[] = "Please select at least one primary health goal.";
    }

    // If 'Other' is selected, ensure additional_goal is provided
    if (in_array('Other', $primary_goals) && empty($additional_goal)) {
        $errors[] = "Please specify your other health goal.";
    }

    if (empty($health_concerns)) {
        $errors[] = "Please select at least one area of health concern.";
    }

    // If 'Other' is selected in health concerns, ensure additional_concern is provided
    if (in_array('Other', $health_concerns) && empty($additional_concern)) {
        $errors[] = "Please specify your other health concern.";
    }

    if (empty($errors)) {
        try {
            // Process 'Other' goal
            $processed_goals = [];
            foreach ($primary_goals as $goal) {
                if ($goal === 'Other') {
                    $processed_goals[] = $additional_goal;
                } else {
                    $processed_goals[] = $goal;
                }
            }

            // Process 'Other' concern
            $processed_concerns = [];
            foreach ($health_concerns as $concern) {
                if ($concern === 'Other') {
                    $processed_concerns[] = $additional_concern;
                } else {
                    $processed_concerns[] = $concern;
                }
            }

            // Save to patient_goals table
            // Check if record exists
            $stmt = $pdo->prepare("SELECT patient_id FROM patient_goals WHERE patient_id = ?");
            $stmt->execute([$_SESSION['patient_id']]);
            if ($stmt->rowCount() > 0) {
                // Update existing record
                $stmt = $pdo->prepare("UPDATE patient_goals SET primary_health_goals = ?, health_concerns = ? WHERE patient_id = ?");
                $stmt->execute([
                    json_encode($processed_goals), 
                    json_encode($processed_concerns), 
                    $_SESSION['patient_id']
                ]);
            } else {
                // Insert new record
                $stmt = $pdo->prepare("INSERT INTO patient_goals (patient_id, primary_health_goals, health_concerns) VALUES (?, ?, ?)");
                $stmt->execute([
                    $_SESSION['patient_id'], 
                    json_encode($processed_goals), 
                    json_encode($processed_concerns)
                ]);
            }

            header("Location: page7.php");
            exit();
        } catch (PDOException $e) {
            $errors[] = "Database Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Defining Your Health Goals</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // JavaScript to toggle the additional_goal and additional_concern fields
        function toggleAdditionalGoal() {
            var primaryGoals = document.getElementById('primary_goals');
            var options = Array.from(primaryGoals.selectedOptions).map(option => option.value);
            var additionalGoalDiv = document.getElementById('additional_goal_div');
            if (options.includes('Other')) {
                additionalGoalDiv.style.display = 'block';
                document.getElementById('additional_goal').required = true;
            } else {
                additionalGoalDiv.style.display = 'none';
                document.getElementById('additional_goal').required = false;
                document.getElementById('additional_goal').value = '';
            }
        }

        function toggleAdditionalConcern() {
            var healthConcerns = document.getElementById('health_concerns');
            var options = Array.from(healthConcerns.selectedOptions).map(option => option.value);
            var additionalConcernDiv = document.getElementById('additional_concern_div');
            if (options.includes('Other')) {
                additionalConcernDiv.style.display = 'block';
                document.getElementById('additional_concern').required = true;
            } else {
                additionalConcernDiv.style.display = 'none';
                document.getElementById('additional_concern').required = false;
                document.getElementById('additional_concern').value = '';
            }
        }

        window.onload = function() {
            toggleAdditionalGoal(); // Initial check
            toggleAdditionalConcern(); // Initial check
            document.getElementById('primary_goals').addEventListener('change', toggleAdditionalGoal);
            document.getElementById('health_concerns').addEventListener('change', toggleAdditionalConcern);
        };
    </script>
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Defining Your Health Goals</h2>
        </div>

        <div class="section">
            <h3>Defining Your Health Goals</h3>
            <p>We tailor your journey based on what matters most to you.</p>

            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }
            ?>

            <form method="POST" action="">
                <!-- Primary Health Goals -->
                <div class="form-group">
                    <label for="primary_goals">What are your primary health goals? (Select all that apply)</label>
                    <select id="primary_goals" name="primary_goals[]" multiple size="5" required>
                        <option value="Improve energy" <?php if(isset($primary_goals) && in_array('Improve energy', $primary_goals)) echo 'selected'; ?>>Improve energy</option>
                        <option value="Lose weight" <?php if(isset($primary_goals) && in_array('Lose weight', $primary_goals)) echo 'selected'; ?>>Lose weight</option>
                        <option value="Reverse a chronic condition" <?php if(isset($primary_goals) && in_array('Reverse a chronic condition', $primary_goals)) echo 'selected'; ?>>Reverse a chronic condition</option>
                        <option value="Enhance mental well-being" <?php if(isset($primary_goals) && in_array('Enhance mental well-being', $primary_goals)) echo 'selected'; ?>>Enhance mental well-being</option>
                        <option value="Other" <?php if(isset($primary_goals) && in_array('Other', $primary_goals)) echo 'selected'; ?>>Other</option>
                    </select>
                </div>

                <!-- Additional Goal -->
                <div class="form-group" id="additional_goal_div" style="display: none;">
                    <label for="additional_goal">Please specify your other health goal:</label>
                    <input type="text" id="additional_goal" name="additional_goal" value="<?php echo isset($additional_goal) ? htmlspecialchars($additional_goal) : ''; ?>">
                </div>

                <!-- Health Concerns -->
                <div class="form-group">
                    <label for="health_concerns">What areas of your health concern you the most? (Select all that apply)</label>
                    <select id="health_concerns" name="health_concerns[]" multiple size="5" required>
                        <option value="Aging" <?php if(isset($health_concerns) && in_array('Aging', $health_concerns)) echo 'selected'; ?>>Aging</option>
                        <option value="Disease Prevention" <?php if(isset($health_concerns) && in_array('Disease Prevention', $health_concerns)) echo 'selected'; ?>>Disease Prevention</option>
                        <option value="Mental Health" <?php if(isset($health_concerns) && in_array('Mental Health', $health_concerns)) echo 'selected'; ?>>Mental Health</option>
                        <option value="Skin Health" <?php if(isset($health_concerns) && in_array('Skin Health', $health_concerns)) echo 'selected'; ?>>Skin Health</option>
                        <option value="Other" <?php if(isset($health_concerns) && in_array('Other', $health_concerns)) echo 'selected'; ?>>Other</option>
                    </select>
                </div>

                <!-- Additional Concern -->
                <div class="form-group" id="additional_concern_div" style="display: none;">
                    <label for="additional_concern">Please specify your other health concern:</label>
                    <textarea id="additional_concern" name="additional_concern" rows="3"><?php echo isset($additional_concern) ? htmlspecialchars($additional_concern) : ''; ?></textarea>
                </div>

                <input type="submit" value="Continue">
            </form>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page7.php

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Redirect to landing page if patient_id is not set
if (!isset($_SESSION['patient_id'])) {
    header("Location: ../index.php");
    exit();
}

$errors = [];
$analysis = [];

// Fetch patient basic info
try {
    $stmt = $pdo->prepare("SELECT * FROM patient_basic_info WHERE patient_id = ?");
    $stmt->execute([$_SESSION['patient_id']]);
    $basic_info = $stmt->fetch();

    if ($basic_info) {
        // Calculate BMI
        $weight = $basic_info['weight']; // in kg
        $height_cm = $basic_info['height']; // in cm
        $height_m = $height_cm / 100;
        $bmi = $weight / ($height_m * $height_m);
        $bmi = round($bmi, 2);

        // Determine BMI category
        if ($bmi < 18.5) {
            $bmi_category = 'Underweight';
            $bmi_advice = 'Consider a balanced diet rich in nutrients and consult with a nutritionist to reach a healthy weight.';
        } elseif ($bmi >= 18.5 && $bmi < 25) {
            $bmi_category = 'Normal weight';
            $bmi_advice = 'Great job! Continue maintaining your healthy lifestyle.';
        } elseif ($bmi >= 25 && $bmi < 30) {
            $bmi_category = 'Overweight';
            $bmi_advice = 'Consider incorporating regular exercise and a balanced diet to achieve a healthier weight.';
        } else {
            $bmi_category = 'Obese';
            $bmi_advice = 'It is advisable to consult with healthcare professionals to develop a suitable weight loss plan.';
        }

        // Store analysis
        $analysis['BMI'] = $bmi;
        $analysis['BMI Category'] = $bmi_category;
        $analysis['BMI Advice'] = $bmi_advice;
    } else {
        $errors[] = "Basic information not found. Please complete the previous steps.";
    }
} catch (PDOException $e) {
    $errors[] = "Database Error: " . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Redirect to page8.php
    header("Location: page8.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Your Health Analysis</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Your Health Analysis</h2>
        </div>

        <div class="section">
            <h3>Health Analysis</h3>
            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            } else {
                echo '
                <div class="analysis">
                    <div class="bmi-value">' . htmlspecialchars($analysis['BMI']) . '</div>
                    <div class="bmi-category">' . htmlspecialchars($analysis['BMI Category']) . '</div>
                    <div class="bmi-advice">' . htmlspecialchars($analysis['BMI Advice']) . '</div>
                    <div class="encouraging-message">Great job taking charge of your health journey!</div>
                </div>
                ';
            }
            ?>

            <?php if (empty($errors)) { ?>
                <div class="buttons">
                    <form method="POST" action="" style="display:inline;">
                        <input type="submit" value="Get Appointment Now & Free Consultation" class="btn">
                    </form>
                    <a href="https://longevacare.com/" class="btn">Return to Homepage</a>
                </div>
            <?php } ?>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page8.php

// Enable error reporting for debugging (Remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Check if patient_id is set; if not, redirect to page3.php to collect information
if (!isset($_SESSION['patient_id'])) {
    header("Location: page3.php");
    exit();
}

$errors = [];
$success = '';

// Initialize variables
$name = '';
$email = '';
$phone = '';
$gender = '';
$age = '';
$weight = '';
$height = '';

// Fetch existing patient_basic_info to pre-fill the form
try {
    $stmt = $pdo->prepare("SELECT * FROM patient_basic_info WHERE patient_id = ?");
    $stmt->execute([$_SESSION['patient_id']]);
    $basic_info = $stmt->fetch();

    if ($basic_info) {
        $name = htmlspecialchars($basic_info['name']);
        $email = htmlspecialchars($basic_info['email']);
        $phone = htmlspecialchars($basic_info['phone']);
        $gender = htmlspecialchars($basic_info['gender']);
        $age = htmlspecialchars($basic_info['age']);
        $weight = htmlspecialchars($basic_info['weight']);
        $height = htmlspecialchars($basic_info['height']);
    }
} catch (PDOException $e) {
    $errors[] = "Database Error: " . $e->getMessage();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect and sanitize inputs
    $name = isset($_POST['name']) ? htmlspecialchars(trim($_POST['name'])) : '';
    $email = isset($_POST['email']) ? filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL) : '';
    $phone = isset($_POST['phone']) ? htmlspecialchars(trim($_POST['phone'])) : '';
    $gender = isset($_POST['gender']) ? htmlspecialchars(trim($_POST['gender'])) : '';
    $age = isset($_POST['age']) ? intval($_POST['age']) : '';
    $weight = isset($_POST['weight']) ? floatval($_POST['weight']) : '';
    $height = isset($_POST['height']) ? floatval($_POST['height']) : '';

    // Validate inputs
    if (empty($name)) {
        $errors[] = "Name is required.";
    }

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "A valid Email is required.";
    }

    if (empty($phone)) {
        $errors[] = "Phone number is required.";
    } elseif (!preg_match('/^[0-9+\-\s()]{7,20}$/', $phone)) {
        $errors[] = "Please enter a valid phone number.";
    }

    if (empty($gender)) {
        $errors[] = "Gender is required.";
    }

    if (empty($age) || $age <= 0) {
        $errors[] = "Valid age is required.";
    }

    if (empty($weight) || $weight <= 0) {
        $errors[] = "Valid weight is required.";
    }

    if (empty($height) || $height <= 0) {
        $errors[] = "Valid height is required.";
    }

    if (empty($errors)) {
        try {
            // Update existing record
            $stmt = $pdo->prepare("UPDATE patient_basic_info SET name = ?, email = ?, phone = ?, gender = ?, age = ?, weight = ?, height = ? WHERE patient_id = ?");
            $stmt->execute([$name, $email, $phone, $gender, $age, $weight, $height, $_SESSION['patient_id']]);

            $success = "Your details have been successfully saved.";
        } catch (PDOException $e) {
            $errors[] = "Database Error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Your Information</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Your Information</h2>
        </div>

        <div class="section">
            <h3>Ensure Your Details Are Correct</h3>
            <p>Providing accurate information helps us serve you better.</p>

            <?php
            if (!empty($success)) {
                echo '<div class="success">';
                echo "<p>$success</p>";
                echo '</div>';

                echo '
                <div class="buttons">
                    <a href="page9.php" class="btn-gold">Get Appointment Now & Free Consultation</a>
                    <a href="https://longevacare.com/" class="btn-gold">Return to Homepage</a>
                </div>
                ';
            }

            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }

            if (empty($success)) {
                ?>
                <form method="POST" action="">
                    <!-- Name -->
                    <div class="form-group">
                        <label for="name">Name:</label>
                        <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($name); ?>" required>
                    </div>

                    <!-- Email -->
                    <div class="form-group">
                        <label for="email">Email:</label>
                        <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
                    </div>

                    <!-- Phone Number -->
                    <div class="form-group">
                        <label for="phone">Phone Number:</label>
                        <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($phone); ?>" required>
                    </div>

                    <!-- Gender -->
                    <div class="form-group">
                        <label for="gender">Gender:</label>
                        <select id="gender" name="gender" required>
                            <option value="">--Select Gender--</option>
                            <option value="Male" <?php if($gender == 'Male') echo 'selected'; ?>>Male</option>
                            <option value="Female" <?php if($gender == 'Female') echo 'selected'; ?>>Female</option>
                            <option value="Other" <?php if($gender == 'Other') echo 'selected'; ?>>Other</option>
                        </select>
                    </div>

                    <!-- Age -->
                    <div class="form-group">
                        <label for="age">Age:</label>
                        <input type="number" id="age" name="age" min="0" value="<?php echo htmlspecialchars($age); ?>" required>
                    </div>

                    <!-- Weight -->
                    <div class="form-group">
                        <label for="weight">Weight (kg):</label>
                        <input type="number" step="0.1" id="weight" name="weight" min="0" value="<?php echo htmlspecialchars($weight); ?>" required>
                    </div>

                    <!-- Height -->
                    <div class="form-group">
                        <label for="height">Height (cm):</label>
                        <input type="number" step="0.1" id="height" name="height" min="0" value="<?php echo htmlspecialchars($height); ?>" required>
                    </div>

                    <input type="submit" value="Save & Continue">
                </form>
                <?php
            }
            ?>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page9.php

// Enable error reporting for debugging (Remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Check if patient_id is set; if not, redirect to page3.php
if (!isset($_SESSION['patient_id'])) {
    header("Location: page3.php");
    exit();
}

$errors = [];
$success = '';
$scheduled_at = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Collect and sanitize inputs
    $scheduled_at = isset($_POST['scheduled_at']) ? htmlspecialchars(trim($_POST['scheduled_at'])) : '';

    // Validate input
    if (empty($scheduled_at)) {
        $errors[] = "Please select a consultation date and time.";
    } else {
        // Validate datetime format
        $date = DateTime::createFromFormat('Y-m-d\TH:i', $scheduled_at);
        if (!$date) {
            $errors[] = "Invalid date and time format.";
        }
    }

    if (empty($errors)) {
        try {
            // Save to patient_consultation table
            $stmt = $pdo->prepare("INSERT INTO patient_consultation (patient_id, scheduled_at) VALUES (?, ?)");
            $stmt->execute([$_SESSION['patient_id'], $scheduled_at]);

            // Redirect to page10.php
            header("Location: page10.php");
            exit();
        } catch (PDOException $e) {
            $errors[] = "Database Error: " . $e->getMessage();
        }
    }
}

// If form is not submitted, attempt to fetch existing consultation (optional)
try {
    $stmt = $pdo->prepare("SELECT scheduled_at FROM patient_consultation WHERE patient_id = ?");
    $stmt->execute([$_SESSION['patient_id']]);
    $consultation = $stmt->fetch();

    if ($consultation) {
        $scheduled_at = htmlspecialchars($consultation['scheduled_at']);
    }
} catch (PDOException $e) {
    $errors[] = "Database Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Personalized Consultation</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Personalized Consultation</h2>
        </div>

        <div class="section">
            <h3>Schedule Your Personalized Consultation</h3>
            <p>Your answers help us tailor your health journey. Next, you’ll receive a personalized consultation and diagnostic tests. Our team will visit you for a detailed consultation and telomere test.</p>

            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            }
            ?>

            <form method="POST" action="">
                <!-- Consultation Date and Time -->
                <div class="form-group">
                    <label for="scheduled_at">Select Consultation Date and Time:</label>
                    <input type="datetime-local" id="scheduled_at" name="scheduled_at" value="<?php echo htmlspecialchars($scheduled_at); ?>" required>
                </div>
                <input type="submit" value="Schedule Your Consultation">
            </form>
        </div>
    </div>
</body>
</html>) and (<?php
// pages/page10.php

// Enable error reporting for debugging (Remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session and include database connection
session_start();
require '../db_connect.php';

// Check if patient_id is set; if not, redirect to page3.php
if (!isset($_SESSION['patient_id'])) {
    header("Location: page3.php");
    exit();
}

$errors = [];
$scheduled_at = '';

// Fetch scheduled consultation details
try {
    $stmt = $pdo->prepare("SELECT scheduled_at FROM patient_consultation WHERE patient_id = ?");
    $stmt->execute([$_SESSION['patient_id']]);
    $consultation = $stmt->fetch();

    if ($consultation) {
        $scheduled_at = $consultation['scheduled_at'];
    } else {
        // If no consultation is scheduled, redirect back to page9.php
        header("Location: page9.php");
        exit();
    }
} catch (PDOException $e) {
    $errors[] = "Database Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Consultation Scheduled</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/images/gold-logo.png" alt="Longeva Logo">
            <h2>Consultation Scheduled Successfully!</h2>
        </div>

        <div class="section">
            <?php
            if (!empty($errors)) {
                echo '<div class="error">';
                foreach($errors as $error){
                    echo "<p>$error</p>";
                }
                echo '</div>';
            } else {
                // Format the scheduled_at datetime
                $scheduled_datetime = DateTime::createFromFormat('Y-m-d H:i:s', $scheduled_at);
                if (!$scheduled_datetime) {
                    $scheduled_datetime = DateTime::createFromFormat('Y-m-d\TH:i', $scheduled_at);
                }
                if ($scheduled_datetime) {
                    $formatted_datetime = $scheduled_datetime->format('F j, Y, g:i A');
                } else {
                    $formatted_datetime = htmlspecialchars($scheduled_at);
                }

                echo '<div class="success">';
                echo "<p>Your consultation has been scheduled on <strong>$formatted_datetime</strong>.</p>";
                echo '<p>Our team will contact you shortly to confirm the details.</p>';
                echo '</div>';

                echo '<div class="buttons">';
                echo '<a href="https://info.longevacare.com/appointment/public_appointment.php" class="btn-gold">View Your Appointments</a>';
                echo '<a href="https://longevacare.com/" class="btn-gold">Return to Homepage</a>';
                echo '</div>';
            }
            ?>
        </div>
    </div>
</body>
</html>) and i want to fix them well and this database info (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Oct 16, 2024 at 02:08 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `u406552082_info`
--

-- --------------------------------------------------------

--
-- Table structure for table `admins`
--

CREATE TABLE `admins` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `appointments`
--

CREATE TABLE `appointments` (
  `id` int(11) NOT NULL,
  `package_id` int(11) NOT NULL,
  `appointment_date` datetime NOT NULL,
  `proposed_appointment_date` datetime DEFAULT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `age` int(3) DEFAULT NULL,
  `gender` enum('Male','Female','Other') DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `preferred_contact_method` enum('Email','Phone','WhatsApp') DEFAULT NULL,
  `additional_notes` text DEFAULT NULL,
  `admin_notes` text DEFAULT NULL,
  `status` enum('Pending','Confirmed','Completed','Cancelled') DEFAULT 'Pending',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `patient_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `budgets`
--

CREATE TABLE `budgets` (
  `id` int(11) NOT NULL,
  `month` varchar(7) DEFAULT NULL,
  `budgeted_revenue` decimal(10,2) DEFAULT NULL,
  `budgeted_expenses` decimal(10,2) DEFAULT NULL,
  `notes` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `comments`
--

CREATE TABLE `comments` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `sender` enum('patient','doctor','admin') NOT NULL,
  `message` text NOT NULL,
  `timestamp` datetime DEFAULT current_timestamp(),
  `parent_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `doctors`
--

CREATE TABLE `doctors` (
  `id` int(11) NOT NULL,
  `employee_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `specialization` varchar(255) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `registration_date` date DEFAULT curdate(),
  `profile_picture` varchar(255) DEFAULT NULL,
  `department` varchar(100) DEFAULT NULL,
  `date_of_joining` date DEFAULT NULL,
  `status` enum('active','inactive') DEFAULT 'active'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `doctor_patient`
--

CREATE TABLE `doctor_patient` (
  `id` int(11) NOT NULL,
  `doctor_id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `employees`
--

CREATE TABLE `employees` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `role` enum('admin','doctor','staff','accountant') NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `department` varchar(100) DEFAULT NULL,
  `date_of_joining` date DEFAULT NULL,
  `status` enum('active','inactive') DEFAULT 'active',
  `username` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `profile_picture` varchar(255) DEFAULT NULL,
  `specialization` varchar(255) DEFAULT NULL,
  `is_online` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `expenses`
--

CREATE TABLE `expenses` (
  `id` int(11) NOT NULL,
  `expense_date` date NOT NULL,
  `category` varchar(100) NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `amount` decimal(10,2) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `health_records`
--

CREATE TABLE `health_records` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `blood_pressure` varchar(20) DEFAULT NULL,
  `weight` decimal(5,2) DEFAULT NULL,
  `bmi` decimal(4,2) DEFAULT NULL,
  `cholesterol` decimal(5,2) DEFAULT NULL,
  `prescription` text DEFAULT NULL,
  `treatment_progress` text DEFAULT NULL,
  `record_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `insurance_claims`
--

CREATE TABLE `insurance_claims` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) DEFAULT NULL,
  `invoice_id` int(11) DEFAULT NULL,
  `claim_amount` decimal(10,2) DEFAULT NULL,
  `status` enum('Pending','Approved','Rejected') DEFAULT NULL,
  `submission_date` date DEFAULT NULL,
  `processing_date` date DEFAULT NULL,
  `notes` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `invoices`
--

CREATE TABLE `invoices` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `service_name` varchar(255) NOT NULL,
  `service_description` text DEFAULT NULL,
  `cost` decimal(10,2) NOT NULL,
  `tax_rate` decimal(5,2) DEFAULT 0.00,
  `discount` decimal(5,2) DEFAULT 0.00,
  `total_amount` decimal(10,2) NOT NULL,
  `invoice_date` date DEFAULT curdate(),
  `due_date` date DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `tax` decimal(5,2) DEFAULT 0.00
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `invoice_services`
--

CREATE TABLE `invoice_services` (
  `id` int(11) NOT NULL,
  `invoice_id` int(11) NOT NULL,
  `service_id` int(11) NOT NULL,
  `service_name` varchar(255) NOT NULL,
  `cost` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `packages`
--

CREATE TABLE `packages` (
  `id` int(11) NOT NULL,
  `package_name` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `details` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patients`
--

CREATE TABLE `patients` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `age` int(3) DEFAULT NULL,
  `gender` enum('Male','Female','Other') DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `medical_history` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `date_of_birth` date DEFAULT NULL,
  `registration_datetime` datetime DEFAULT current_timestamp(),
  `registration_date` date DEFAULT NULL,
  `status` enum('Initial Consultation','Diagnostic Phase','Treatment in Progress','Improving','Monitoring','Maintenance Phase','Awaiting Test Results','Follow-up Needed','Paused','Completed Program','Relapsed','Discontinued','Inactive') DEFAULT 'Initial Consultation',
  `doctor_id` int(11) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_basic_info`
--

CREATE TABLE `patient_basic_info` (
  `patient_id` int(11) NOT NULL,
  `gender` enum('Male','Female','Other') NOT NULL,
  `age` int(3) NOT NULL,
  `weight` decimal(5,2) NOT NULL,
  `height` decimal(5,2) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_consent`
--

CREATE TABLE `patient_consent` (
  `patient_id` int(11) NOT NULL,
  `consent` enum('accepted','declined') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_consultation`
--

CREATE TABLE `patient_consultation` (
  `patient_id` int(11) NOT NULL,
  `scheduled_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_goals`
--

CREATE TABLE `patient_goals` (
  `patient_id` int(11) NOT NULL,
  `primary_health_goals` text NOT NULL,
  `health_concerns` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_health_metrics`
--

CREATE TABLE `patient_health_metrics` (
  `patient_id` int(11) NOT NULL,
  `exercise_frequency` enum('Daily','Weekly','Rarely','Never') NOT NULL,
  `diet` enum('Yes','No') NOT NULL,
  `diet_specify` varchar(255) DEFAULT NULL,
  `sleep_average` enum('<5 Hours','5-7 Hours','7-9 Hours','>9 Hours') NOT NULL,
  `smoking_status` enum('Yes','No','Occasionally') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_logins`
--

CREATE TABLE `patient_logins` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_medical_history`
--

CREATE TABLE `patient_medical_history` (
  `patient_id` int(11) NOT NULL,
  `chronic_conditions` enum('Yes','No') NOT NULL,
  `chronic_conditions_specify` varchar(255) DEFAULT NULL,
  `medications` enum('Yes','No') NOT NULL,
  `medications_list` text DEFAULT NULL,
  `major_surgeries` enum('Yes','No') NOT NULL,
  `major_surgeries_specify` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `payments`
--

CREATE TABLE `payments` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `invoice_id` int(11) NOT NULL,
  `amount_paid` decimal(10,2) NOT NULL,
  `payment_date` date NOT NULL,
  `payment_method` varchar(50) DEFAULT NULL,
  `notes` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `prescriptions`
--

CREATE TABLE `prescriptions` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `doctor_id` int(11) DEFAULT NULL,
  `medications` text NOT NULL,
  `instructions` text DEFAULT NULL,
  `date_prescribed` datetime DEFAULT current_timestamp(),
  `status` enum('active','inactive') DEFAULT 'active'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `questionnaire_responses`
--

CREATE TABLE `questionnaire_responses` (
  `id` int(11) NOT NULL,
  `session_id` varchar(255) NOT NULL,
  `page_number` int(2) NOT NULL,
  `question` varchar(255) NOT NULL,
  `answer` text NOT NULL,
  `submitted_at` timestamp NULL DEFAULT current_timestamp(),
  `consent` enum('Yes','No') DEFAULT 'No'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- --------------------------------------------------------

--
-- Table structure for table `salaries`
--

CREATE TABLE `salaries` (
  `id` int(11) NOT NULL,
  `employee_id` int(11) NOT NULL,
  `basic_salary` decimal(10,2) NOT NULL,
  `bonuses` decimal(10,2) DEFAULT 0.00,
  `deductions` decimal(10,2) DEFAULT 0.00,
  `overtime_hours` int(11) DEFAULT 0,
  `overtime_rate` decimal(10,2) DEFAULT 0.00,
  `tax` decimal(10,2) DEFAULT 0.00,
  `payment_date` date NOT NULL,
  `net_salary` decimal(10,2) NOT NULL,
  `status` enum('Pending','Paid') DEFAULT 'Pending',
  `notes` text DEFAULT NULL,
  `payslip_path` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `services`
--

CREATE TABLE `services` (
  `service_id` int(11) NOT NULL,
  `service_name` varchar(255) NOT NULL,
  `service_price` decimal(10,2) NOT NULL,
  `service_description` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- Indexes for table `appointments`
--
ALTER TABLE `appointments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `package_id` (`package_id`),
  ADD KEY `appointments_ibfk_2` (`patient_id`);

--
-- Indexes for table `budgets`
--
ALTER TABLE `budgets`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `comments`
--
ALTER TABLE `comments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`);

--
-- Indexes for table `doctors`
--
ALTER TABLE `doctors`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`),
  ADD UNIQUE KEY `email` (`email`),
  ADD KEY `employee_id` (`employee_id`);

--
-- Indexes for table `doctor_patient`
--
ALTER TABLE `doctor_patient`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `doctor_id` (`doctor_id`,`patient_id`),
  ADD KEY `fk_doctor_patient_patient_id` (`patient_id`);

--
-- Indexes for table `employees`
--
ALTER TABLE `employees`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`),
  ADD UNIQUE KEY `username` (`username`);

--
-- Indexes for table `expenses`
--
ALTER TABLE `expenses`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `health_records`
--
ALTER TABLE `health_records`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`);

--
-- Indexes for table `insurance_claims`
--
ALTER TABLE `insurance_claims`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`),
  ADD KEY `invoice_id` (`invoice_id`);

--
-- Indexes for table `invoices`
--
ALTER TABLE `invoices`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`);

--
-- Indexes for table `invoice_services`
--
ALTER TABLE `invoice_services`
  ADD PRIMARY KEY (`id`),
  ADD KEY `invoice_id` (`invoice_id`),
  ADD KEY `service_id` (`service_id`);

--
-- Indexes for table `packages`
--
ALTER TABLE `packages`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `patients`
--
ALTER TABLE `patients`
  ADD PRIMARY KEY (`id`),
  ADD KEY `doctor_id` (`doctor_id`);

--
-- Indexes for table `patient_basic_info`
--
ALTER TABLE `patient_basic_info`
  ADD PRIMARY KEY (`patient_id`);

--
-- Indexes for table `patient_consent`
--
ALTER TABLE `patient_consent`
  ADD PRIMARY KEY (`patient_id`);

--
-- Indexes for table `patient_consultation`
--
ALTER TABLE `patient_consultation`
  ADD PRIMARY KEY (`patient_id`);

--
-- Indexes for table `patient_goals`
--
ALTER TABLE `patient_goals`
  ADD PRIMARY KEY (`patient_id`);

--
-- Indexes for table `patient_health_metrics`
--
ALTER TABLE `patient_health_metrics`
  ADD PRIMARY KEY (`patient_id`);

--
-- Indexes for table `patient_logins`
--
ALTER TABLE `patient_logins`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `patient_id` (`patient_id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- Indexes for table `patient_medical_history`
--
ALTER TABLE `patient_medical_history`
  ADD PRIMARY KEY (`patient_id`);

--
-- Indexes for table `payments`
--
ALTER TABLE `payments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`),
  ADD KEY `invoice_id` (`invoice_id`);

--
-- Indexes for table `prescriptions`
--
ALTER TABLE `prescriptions`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`),
  ADD KEY `doctor_id` (`doctor_id`);

--
-- Indexes for table `questionnaire_responses`
--
ALTER TABLE `questionnaire_responses`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `salaries`
--
ALTER TABLE `salaries`
  ADD PRIMARY KEY (`id`),
  ADD KEY `employee_id` (`employee_id`);

--
-- Indexes for table `services`
--
ALTER TABLE `services`
  ADD PRIMARY KEY (`service_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `appointments`
--
ALTER TABLE `appointments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `budgets`
--
ALTER TABLE `budgets`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `comments`
--
ALTER TABLE `comments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `doctors`
--
ALTER TABLE `doctors`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `doctor_patient`
--
ALTER TABLE `doctor_patient`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `employees`
--
ALTER TABLE `employees`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `expenses`
--
ALTER TABLE `expenses`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `health_records`
--
ALTER TABLE `health_records`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `insurance_claims`
--
ALTER TABLE `insurance_claims`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `invoices`
--
ALTER TABLE `invoices`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `invoice_services`
--
ALTER TABLE `invoice_services`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `packages`
--
ALTER TABLE `packages`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `patients`
--
ALTER TABLE `patients`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `patient_logins`
--
ALTER TABLE `patient_logins`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `payments`
--
ALTER TABLE `payments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `prescriptions`
--
ALTER TABLE `prescriptions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `questionnaire_responses`
--
ALTER TABLE `questionnaire_responses`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `salaries`
--
ALTER TABLE `salaries`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `services`
--
ALTER TABLE `services`
  MODIFY `service_id` int(11) NOT NULL AUTO_INCREMENT;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `appointments`
--
ALTER TABLE `appointments`
  ADD CONSTRAINT `appointments_ibfk_1` FOREIGN KEY (`package_id`) REFERENCES `packages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `appointments_ibfk_2` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `comments`
--
ALTER TABLE `comments`
  ADD CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`);

--
-- Constraints for table `doctors`
--
ALTER TABLE `doctors`
  ADD CONSTRAINT `doctors_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`id`);

--
-- Constraints for table `doctor_patient`
--
ALTER TABLE `doctor_patient`
  ADD CONSTRAINT `doctor_patient_fk_doctor_id` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `doctor_patient_ibfk_2` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_doctor` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_doctor_patient_doctor_id` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_doctor_patient_patient_id` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `health_records`
--
ALTER TABLE `health_records`
  ADD CONSTRAINT `health_records_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `insurance_claims`
--
ALTER TABLE `insurance_claims`
  ADD CONSTRAINT `insurance_claims_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `insurance_claims_ibfk_2` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `invoices`
--
ALTER TABLE `invoices`
  ADD CONSTRAINT `invoices_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`);

--
-- Constraints for table `invoice_services`
--
ALTER TABLE `invoice_services`
  ADD CONSTRAINT `invoice_services_ibfk_1` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `invoice_services_ibfk_2` FOREIGN KEY (`service_id`) REFERENCES `services` (`service_id`) ON DELETE CASCADE;

--
-- Constraints for table `patients`
--
ALTER TABLE `patients`
  ADD CONSTRAINT `patients_ibfk_1` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;

--
-- Constraints for table `patient_logins`
--
ALTER TABLE `patient_logins`
  ADD CONSTRAINT `patient_logins_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `payments`
--
ALTER TABLE `payments`
  ADD CONSTRAINT `payments_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `payments_ibfk_2` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `prescriptions`
--
ALTER TABLE `prescriptions`
  ADD CONSTRAINT `prescriptions_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `prescriptions_ibfk_2` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `salaries`
--
ALTER TABLE `salaries`
  ADD CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;) so fix it and make it working well and make sure in the page7 show data and fix the errer and type full codes with guides