<?php
include 'includes/header.php';

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

$user_id = $_SESSION['user_id'];

if($_POST) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    try {
        // Verify current password
        $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!password_verify($current_password, $user['password'])) {
            throw new Exception("Current password is incorrect!");
        }
        
        if($new_password !== $confirm_password) {
            throw new Exception("New passwords do not match!");
        }
        
        if(strlen($new_password) < 6) {
            throw new Exception("New password must be at least 6 characters long!");
        }
        
        // Update password
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
        $stmt->execute([$hashed_password, $user_id]);
        
        $_SESSION['success'] = "Password changed successfully!";
        header('Location: profile.php');
        exit;
        
    } catch(Exception $e) {
        $error = $e->getMessage();
    }
}
?>

<div class="container">
    <div class="auth-form">
        <h2>Change Password</h2>
        
        <?php if(isset($error)): ?>
            <div class='alert error'><?php echo $error; ?></div>
        <?php endif; ?>
        
        <form method="POST">
            <div class="form-group">
                <label>Current Password:</label>
                <input type="password" name="current_password" required>
            </div>
            
            <div class="form-group">
                <label>New Password:</label>
                <input type="password" name="new_password" required 
                       placeholder="At least 6 characters">
            </div>
            
            <div class="form-group">
                <label>Confirm New Password:</label>
                <input type="password" name="confirm_password" required>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">Change Password</button>
                <a href="profile.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

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