<?php
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    
$_SESSION['message'] = "You are not logged in. Please log in to continue.";
    
header("Location: index.php?page=login");
    exit();
}

$profile_error = "";
$profile_success = "";
$user_id = $_SESSION['user_id'];

// process submissions
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    
// update email
    
if (isset($_POST['update_email'])) {
        
$new_email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
        if (!
$new_email) {
            
$profile_error = "Invalid email format.";
        } else {
            
// check if the email has already been used
            
$stmt = mysqli_prepare($dbc, "SELECT pk_Person FROM CINE_Person WHERE email = ? AND pk_Person != ?");
            if (
$stmt) {
                
mysqli_stmt_bind_param($stmt, "si", $new_email, $user_id);
                
mysqli_stmt_execute($stmt);
                
$result = mysqli_stmt_get_result($stmt);
                if (
mysqli_num_rows($result) > 0) {
                    
$profile_error = "Email already in use.";
                } else {
                    
// Update email
                    
$updateStmt = mysqli_prepare($dbc, "UPDATE CINE_Person SET email = ? WHERE pk_Person = ?");
                    if (
$updateStmt) {
                        
mysqli_stmt_bind_param($updateStmt, "si", $new_email, $user_id);
                        if (
mysqli_stmt_execute($updateStmt)) {
                            
$profile_success = "Email updated successfully.";
                        } else {
                            
$profile_error = "Failed to update email: " . mysqli_error($dbc);
                        }
                        
mysqli_stmt_close($updateStmt);
                    } else {
                        
$profile_error = "Error preparing email update: " . mysqli_error($dbc);
                    }
                }
                
mysqli_stmt_close($stmt);
            } else {
                
$profile_error = "Error preparing email check: " . mysqli_error($dbc);
            }
        }
    }

    
// Update Password
    
if (isset($_POST['update_password'])) {
        
$old_password = $_POST['old_password'];
        
$new_password = $_POST['new_password'];
        
$confirm_password = $_POST['confirm_password'];

        
$stmt = mysqli_prepare($dbc, "SELECT password FROM CINE_Person WHERE pk_Person = ?");
        if (
$stmt) {
            
mysqli_stmt_bind_param($stmt, "i", $user_id);
            
mysqli_stmt_execute($stmt);
            
$result = mysqli_stmt_get_result($stmt);
            
$row = mysqli_fetch_assoc($result);
            
mysqli_stmt_close($stmt);

            if (!
$row || !password_verify($old_password, $row['password'])) {
                
$profile_error = "Old password is incorrect.";
            } else if (
$new_password !== $confirm_password) {
                
$profile_error = "New passwords do not match.";
            } else {
                
$new_hashed = password_hash($new_password, PASSWORD_DEFAULT);
                
$updateStmt = mysqli_prepare($dbc, "UPDATE CINE_Person SET password = ? WHERE pk_Person = ?");
                if (
$updateStmt) {
                    
mysqli_stmt_bind_param($updateStmt, "si", $new_hashed, $user_id);
                    if (
mysqli_stmt_execute($updateStmt)) {
                        
$profile_success = "Password updated successfully.";
                    } else {
                        
$profile_error = "Failed to update password: " . mysqli_error($dbc);
                    }
                    
mysqli_stmt_close($updateStmt);
                } else {
                    
$profile_error = "Error preparing password update: " . mysqli_error($dbc);
                }
            }
        } else {
            
$profile_error = "Error retrieving current password: " . mysqli_error($dbc);
        }
    }
}

// get current email
$current_email = "";
$stmt = mysqli_prepare($dbc, "SELECT email FROM CINE_Person WHERE pk_Person = ?");
if (
$stmt) {
    
mysqli_stmt_bind_param($stmt, "i", $user_id);
    
mysqli_stmt_execute($stmt);
    
$result = mysqli_stmt_get_result($stmt);
    if (
$row = mysqli_fetch_assoc($result)) {
        
$current_email = $row['email'];
    }
    
mysqli_stmt_close($stmt);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Profile</title>
    <link rel="stylesheet" type="text/css" href="assets/css/profile.css">
</head>
<body>
<div class="container profile-container">
    <h2>Profile Settings</h2>

    <?php if (!empty($profile_error)): ?>
        <div class="notification notification-error"><?php echo htmlspecialchars($profile_error); ?></div>
    <?php endif; ?>

    <?php if (!empty($profile_success)): ?>
        <div class="notification notification-success"><?php echo htmlspecialchars($profile_success); ?></div>
    <?php endif; ?>

    <!-- Update Email Form -->
    <div class="profile-section">
        <h3 class="section-header">Update Email</h3>
        <form method="POST">
            <div class="form-group">
                <label for="email">Current Email:</label>
                <input type="email" name="email" id="email" class="form-control" value="<?php echo htmlspecialchars($current_email); ?>" required>
            </div>
            <input type="submit" name="update_email" value="Update Email" class="btn btn-primary">
        </form>
    </div>

    <!-- Change Password Form -->
    <div class="profile-section">
        <h3 class="section-header">Change Password</h3>
        <form method="POST">
            <div class="form-group">
                <label for="old_password">Old Password:</label>
                <input type="password" name="old_password" id="old_password" class="form-control" required>
            </div>

            <div class="form-group">
                <label for="new_password">New Password:</label>
                <input type="password" name="new_password" id="new_password" class="form-control" required>
                <div class="password-strength-meter">
                    <div class="password-strength-meter-bar"></div>
                </div>
                <div class="password-requirements">
                    <div class="requirement" id="req-length">At least 8 characters</div>
                    <div class="requirement" id="req-letter">At least one letter</div>
                    <div class="requirement" id="req-number">At least one number</div>
                    <div class="requirement" id="req-special">At least one special character</div>
                </div>
            </div>

            <div class="form-group">
                <label for="confirm_password">Confirm New Password:</label>
                <input type="password" name="confirm_password" id="confirm_password" class="form-control" required>
            </div>

            <input type="submit" name="update_password" value="Change Password" class="btn btn-primary">
        </form>
    </div>
</div>

<script>
// Simple password strength meter
document.addEventListener('DOMContentLoaded', function() {
    const passwordInput = document.getElementById('new_password');
    const confirmInput = document.getElementById('confirm_password');
    const strengthBar = document.querySelector('.password-strength-meter-bar');
    
    // Requirements
    const reqLength = document.getElementById('req-length');
    const reqLetter = document.getElementById('req-letter');
    const reqNumber = document.getElementById('req-number');
    const reqSpecial = document.getElementById('req-special');
    
    passwordInput.addEventListener('input', function() {
        const password = this.value;
        let strength = 0;
        
        // Check requirements
        const hasLength = password.length >= 8;
        const hasLetter = /[a-zA-Z]/.test(password);
        const hasNumber = /[0-9]/.test(password);
        const hasSpecial = /[^a-zA-Z0-9]/.test(password);
        
        // Update requirement indicators
        reqLength.className = hasLength ? 'requirement valid' : 'requirement';
        reqLetter.className = hasLetter ? 'requirement valid' : 'requirement';
        reqNumber.className = hasNumber ? 'requirement valid' : 'requirement';
        reqSpecial.className = hasSpecial ? 'requirement valid' : 'requirement';
        
        // Calculate strength
        if (hasLength) strength += 1;
        if (hasLetter) strength += 1;
        if (hasNumber) strength += 1;
        if (hasSpecial) strength += 1;
        
        // Update strength bar
        strengthBar.className = 'password-strength-meter-bar';
        if (strength === 0) {
            strengthBar.style.width = '0';
        } else if (strength < 3) {
            strengthBar.classList.add('strength-weak');
            strengthBar.style.width = '33%';
        } else if (strength === 3) {
            strengthBar.classList.add('strength-medium');
            strengthBar.style.width = '66%';
        } else {
            strengthBar.classList.add('strength-strong');
            strengthBar.style.width = '100%';
        }
    });
    
    // Check if passwords match
    confirmInput.addEventListener('input', function() {
        if (this.value === passwordInput.value) {
            this.style.borderColor = 'rgba(40, 167, 69, 0.5)';
            this.style.boxShadow = '0 0 0 3px rgba(40, 167, 69, 0.2)';
        } else {
            this.style.borderColor = 'rgba(220, 53, 69, 0.5)';
            this.style.boxShadow = '0 0 0 3px rgba(220, 53, 69, 0.2)';
        }
    });
});
</script>
</body>
</html>