<?php
session_start();

if (!isset($_SESSION['username'], $_SESSION['userid'], $_SESSION['database'])) {
    header("Location: login.html");
    exit();
}

$username = $_SESSION['username'];
$userid = $_SESSION['userid'];
$database = $_SESSION['database'];


try {
    require_once 'connection.php';

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND userid = :userid");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':userid', $userid);
    $stmt->execute();

    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        echo "<script>alert('User not found'); window.location.href='login.php';</script>";
        exit();
    }
} catch (PDOException $e) {
    echo "<script>alert('Database connection failed');</script>";
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Profile</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/6.6.6/css/flag-icons.min.css">
</head>

<body class="profilephp">
    <div class="container">
        <button id="edit-btn" onclick="history.back();" title="Back to Homepage">←</button>
        <button id="logout-btn" onclick="logoutUser()" title="Logout">⏻</button>
        <h1>User Profile</h1>
        <div class="profile-card">
            <div class="avatar" onclick="document.getElementById('upload-avatar').click();">
                <img id="avatar-img" src="DATA/<?php echo $_SESSION["profile_photo"] ?? "avatar.jpg" ?>" alt="USER AVATAR">
                <div class="avatar-overlay">
                    <span class="edit-icon">✎</span>
                </div>
                <input type="file" id="upload-avatar" accept="image/*" onchange="changeAvatar(event)">
            </div>

            <div class="profile-info">
                <h2 id="display-name"><?php echo htmlspecialchars($user['uname']); ?></h2>
                <input type="text" class="edit-field" id="input-uname" value="<?php echo htmlspecialchars($user['uname']); ?>" />
                <div class="info-group">
                    <label>Email:</label>
                    <p id="display-email"><?php echo htmlspecialchars($user['email']); ?></p>
                    <input type="email" disabled id="input-email" value="<?php echo htmlspecialchars($user['email']); ?>" class="edit-field" />
                </div>
                <div class="info-group">
                    <label>Phone:</label>
                    <p id="display-phone">+91-<?php echo htmlspecialchars($user['contact']); ?></p>
                    <div class="phone-fields edit-field" style="display: none;">
                        <!-- You must include flag-icon CSS library (optional CDN version) -->
                        <select id="input-country" name="input-country" class="phone-code">
                            <?php
                            $stmt2 = $pdo->prepare("SELECT countryName, ISD, countryCode FROM country ORDER BY countryName ASC");
                            $stmt2->execute();

                            while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
                                $name = htmlspecialchars($row['countryName']);
                                $code = htmlspecialchars($row['ISD']);
                                $cc   = strtolower($row['countryCode']);
                                $selected = ($code == $user['countryCode']) ? 'selected' : '';

                                echo "<option value=$code data-flag=$cc $selected>$name ($code)</option>";
                            }
                            ?>
                        </select>

                        <input type="text" id="input-phone" value="<?php echo htmlspecialchars($user['contact']); ?>" required minlength="10" maxlength="10" class="phone-number" />
                    </div>
                </div>
                <div class="info-group">
                    <label>Username:</label>
                    <p id="display-username"><?php echo htmlspecialchars($user['username']); ?></p>
                    <input type="text" required id="input-username" value="<?php echo htmlspecialchars($user['username']); ?>" class="edit-field" />
                </div>
                <div class="info-group">
                    <label>Role:</label>
                    <p id="display-role"><?php echo htmlspecialchars($user['role']); ?></p>
                    <input type="text" id="input-role" value="<?php echo htmlspecialchars($user['role']); ?>" class="edit-field" disabled />
                </div>
            </div>
        </div>
        <div class="error" id="error">
            Unable to update data. Try Again!
        </div>
        <div class="action-buttons">
            <button id="edit-btn2" onclick="toggleEdit()">Edit Profile</button>
            <button id="save-btn" onclick="saveProfile()" style="display:none;">Save</button>
        </div>
    </div>

    <script src="profile.js"></script>
</body>

</html>