<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
if (!isset($_SESSION['patient_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';
$patient_id = $_SESSION['patient_id'];

$msg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $stmt = $conn->prepare("UPDATE patients SET first_name=?, last_name=?, phone=?, address=? WHERE patient_id=?");
    $stmt->bind_param("sssss", $first_name, $last_name, $phone, $address, $patient_id);
    if ($stmt->execute()) $msg = "Profile updated successfully!";
    else $msg = "Error: " . $conn->error;
    $stmt->close();
}
$p = $conn->query("SELECT * FROM patients WHERE patient_id='$patient_id'")->fetch_assoc();
if (!$p) { die("Patient record not found."); }
?>
<!DOCTYPE html>
<html>
<head><title>My Profile</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body><div class="container mt-4"><h2>My Profile</h2>
<?php if($msg) echo "<div class='alert alert-success'>$msg</div>"; ?>
<form method="POST">
<div class="mb-3"><label>First Name</label><input type="text" name="first_name" class="form-control" value="<?= htmlspecialchars($p['first_name']) ?>" required></div>
<div class="mb-3"><label>Last Name</label><input type="text" name="last_name" class="form-control" value="<?= htmlspecialchars($p['last_name']) ?>" required></div>
<div class="mb-3"><label>Email</label><input type="email" class="form-control" value="<?= $p['email'] ?>" disabled></div>
<div class="mb-3"><label>Phone</label><input type="tel" name="phone" class="form-control" value="<?= htmlspecialchars($p['phone'] ?? '') ?>"></div>
<div class="mb-3"><label>Address</label><textarea name="address" class="form-control" rows="2"><?= htmlspecialchars($p['address'] ?? '') ?></textarea></div>
<div class="mb-3"><label>Patient ID</label><input type="text" class="form-control" value="<?= $p['patient_id'] ?>" disabled></div>
<button type="submit" class="btn btn-primary">Update Profile</button>
<a href="dashboard.php" class="btn btn-secondary">Back</a>
</form></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>