<?php
header("Content-Type: application/json");
require_once "../config.php";

$email = $_POST['email'] ?? $_GET['email'] ?? '';
$role = $_POST['role'] ?? $_GET['role'] ?? '';
$currentpassword = $_POST['currentpassword'] ?? $_GET['currentpassword'] ?? '';
$password = $_POST['password'] ?? $_GET['password'] ?? null;
$newpassword = password_hash($password, PASSWORD_DEFAULT);


if (!empty($role) && ($role) == 'admin') {
    $query = $dbh->prepare('SELECT * FROM admin WHERE AdminEmail=:email');
    $query->bindParam(':email', $email, PDO::PARAM_STR);
    $query->execute();
    $row = $query->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        if (password_verify($currentpassword, $row['Password']) && !empty($newpassword)) {
            $update = "UPDATE admin SET Password=:newpassword WHERE AdminEmail=:email";
            $chngpwd1 = $dbh->prepare($update);
            $chngpwd1->bindParam(':email', $email, PDO::PARAM_STR);
            $chngpwd1->bindParam(':newpassword', $newpassword, PDO::PARAM_STR);
            $chngpwd1->execute();
            echo json_encode([
                'status' => 'success',
                "message" => "Password updated successfully"
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                "message" => "Password error"
            ]);
        }
    } else {
        echo json_encode([
            'status' => 'error',
            "message" => "Email Not Found"
        ]);
    }
} else if (!empty($role) && ($role) == 'student') {

    $update = "UPDATE tblstudents SET Password=:newpassword WHERE EmailId=:email AND Password=:currentpassword";
    $chngpwd1 = $dbh->prepare($update);
    $chngpwd1->bindParam(':email', $email, PDO::PARAM_STR);
    $chngpwd1->bindParam(':currentpassword', $currentpassword, PDO::PARAM_STR);
    $chngpwd1->bindParam(':newpassword', $newpassword, PDO::PARAM_STR);
    $chngpwd1->execute();
    echo json_encode([
        'status' => 'success',
        "message" => "Password updated successfully"
    ]);
} else if (!empty($role) && ($role) == 'staff') {

    $update = "UPDATE tblstaff SET Password=:newpassword WHERE EmailId=:email AND Password=:currentpassword";
    $chngpwd1 = $dbh->prepare($update);
    $chngpwd1->bindParam(':email', $email, PDO::PARAM_STR);
    $chngpwd1->bindParam(':currentpassword', $currentpassword, PDO::PARAM_STR);
    $chngpwd1->bindParam(':newpassword', $newpassword, PDO::PARAM_STR);
    $chngpwd1->execute();
    echo json_encode([
        'status' => 'success',
        "message" => "Password updated successfully"
    ]);
} else {
    echo json_encode(["status" => "error", "message" => "Update Failed" . $password . 'ff']);
}
