<?php
require_once 'includes/config.php';
redirectIfNotLoggedIn();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])) {
    $current = $_POST['current_password'] ?? '';
    $new = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';
    
    // Get user data
    $stmt = $pdo->prepare("SELECT password FROM members WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    
    if (md5($current) != $user['password']) {
        $error = 'Current password is incorrect';
    } elseif (strlen($new) < 6) {
        $error = 'New password must be at least 6 characters';
    } elseif ($new != $confirm) {
        $error = 'New passwords do not match';
    } else {
        $stmt = $pdo->prepare("UPDATE members SET password = ? WHERE id = ?");
        $stmt->execute([md5($new), $_SESSION['user_id']]);
        
        $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE email = (SELECT email FROM members WHERE id = ?)");
        $stmt->execute([md5($new), $_SESSION['user_id']]);
        
        $success = 'Password changed successfully!';
    }
}

header('Location: profile.php?msg=' . ($success ? urlencode($success) : urlencode($error)));
exit;
?>