<?php
session_start();
include "config.php";

// Redirect if user is not logged in
if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}
// Get user details from session
$user = $_SESSION['user'];
$pid = $user['pid'];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['old_password'], $_POST['new_password'])) {
    $old_password = md5(mysqli_real_escape_string($con, $_POST['old_password']));
    $new_password = md5(mysqli_real_escape_string($con, $_POST['new_password']));

    $check = mysqli_query($con, "SELECT password FROM users WHERE pid = '$pid' AND password = '$old_password'");

    if (mysqli_num_rows($check) == 1) {
        $update = mysqli_query($con, "UPDATE users SET password = '$new_password' WHERE pid = '$pid'");
        if ($update) {
            echo "<script>alert('Password updated successfully');</script>";
        } else {
            echo "<script>alert('Failed to update password');</script>";
        }
    } else {
        echo "<script>alert('Old password is incorrect');</script>";
    }
}
?>