<?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)) {
        $profile_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]);
        $profile_success = "Profile updated successfully!";
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    $p_user = $db->prepare("SELECT password FROM users WHERE id = ?");
    $p_user->execute([$user_id]);
    $user_data = $p_user->fetch();

    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $password_error = "All password fields are required.";
    } elseif (!password_verify($current_password, $user_data['password'])) {
        $password_error = "Incorrect current password.";
    } elseif ($new_password !== $confirm_password) {
        $password_error = "New passwords do not match.";
    } else {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $p_pass_update = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
        $p_pass_update->execute([$hashed_password, $user_id]);
        $password_success = "Password changed successfully!";
    }
}


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

// Fetch favorite restaurants
$fav_stmt = $db->prepare("
    SELECT r.id, r.name, r.image_url, c.name as cuisine_name
    FROM favorite_restaurants fr
    JOIN restaurants r ON fr.restaurant_id = r.id
    LEFT JOIN restaurant_cuisines rc ON r.id = rc.restaurant_id
    LEFT JOIN cuisines c ON rc.cuisine_id = c.id
    WHERE fr.user_id = ?
    GROUP BY r.id
");
$fav_stmt->execute([$user_id]);
$favorite_restaurants = $fav_stmt->fetchAll();

?>

<div class="container mt-5">
    <div class="row">
        <div class="col-md-6">
            <h2>My Profile</h2>
            <hr>

            <?php if (isset($profile_success)): ?>
                <div class="alert alert-success"><?php echo $profile_success; ?></div>
            <?php endif; ?>
            <?php if (isset($profile_error)): ?>
                <div class="alert alert-danger"><?php echo $profile_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>
        <div class="col-md-6">
            <h2>Change Password</h2>
            <hr>

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

            <form method="POST" action="profile.php">
                <div class="mb-3">
                    <label for="current_password" class="form-label">Current Password</label>
                    <input type="password" class="form-control" id="current_password" name="current_password" required>
                </div>
                <div class="mb-3">
                    <label for="new_password" class="form-label">New Password</label>
                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                </div>
                <div class="mb-3">
                    <label for="confirm_password" class="form-label">Confirm New Password</label>
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                </div>
                <button type="submit" name="change_password" class="btn btn-primary">Change Password</button>
            </form>
        </div>
    </div>


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

    <div class="row mt-5">
        <div class="col-12">
            <h2>My Favorite Restaurants</h2>
            <hr>
            <?php if ($favorite_restaurants): ?>
                <div class="row">
                    <?php foreach ($favorite_restaurants as $fav_restaurant): ?>
                        <div class="col-md-4 mb-4">
                            <div class="card h-100">
                                <a href="menu.php?restaurant_id=<?php echo $fav_restaurant['id']; ?>">
                                    <img src="<?php echo htmlspecialchars($fav_restaurant['image_url'] ? $fav_restaurant['image_url'] : 'https://via.placeholder.com/300x200'); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($fav_restaurant['name']); ?>" style="height: 200px; object-fit: cover;">
                                </a>
                                <div class="card-body d-flex flex-column">
                                    <h5 class="card-title"><?php echo htmlspecialchars($fav_restaurant['name']); ?></h5>
                                    <p class="card-text text-muted"><?php echo htmlspecialchars($fav_restaurant['cuisine_name']); ?></p>
                                    <a href="menu.php?restaurant_id=<?php echo $fav_restaurant['id']; ?>" class="btn btn-primary mt-auto">View Menu</a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p>You haven't added any favorite restaurants yet. <a href="index.php">Explore restaurants</a> to find some!</p>
            <?php endif; ?>
        </div>
    </div>
</div>

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