<?php
session_start();
require_once 'db/config.php';
include 'header.php';

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

$user_id = $_SESSION['user_id'];
$db = db();

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $address = trim($_POST['address']);

    if (empty($name) || empty($email)) {
        $error = "Name and email are required.";
    } else {
        $p_update = $db->prepare("UPDATE users SET name = ?, email = ?, address = ? WHERE id = ?");
        $p_update->execute([$name, $email, $address, $user_id]);
        $success = "Profile updated successfully!";
    }
}

// Fetch user data
$p_user = $db->prepare("SELECT * FROM users WHERE id = ?");
$p_user->execute([$user_id]);
$user = $p_user->fetch();


?>

<div class="container mt-5">
    <h2>My Profile</h2>
    <hr>

    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>

    <form method="POST" action="profile.php">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($user['name']); ?>" required>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">Email address</label>
            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
        </div>
        <div class="mb-3">
            <label for="address" class="form-label">Address</label>
            <textarea class="form-control" id="address" name="address" rows="3"><?php echo htmlspecialchars($user['address']); ?></textarea>
        </div>
        <button type="submit" name="update_profile" class="btn btn-primary">Update Profile</button>
    </form>

    <div class="mt-5">
        <a href="order_history.php" class="btn btn-secondary">View Order History</a>
    </div>
</div>

<?php include 'footer.php'; ?>
