<?php
require_once("dbconn.php");
require_once("phpFunctions.php");

if (isset($_POST["cp_username"]) && isset($_POST["cp_old_password"]) && isset($_POST["cp_new_password"])) {
    $username = $_POST["cp_username"];
    $old_password = $_POST["cp_old_password"];
    $new_password = $_POST["cp_new_password"];

    $result = executeQuery($conn, "SELECT * FROM users WHERE BINARY username = ? AND password = ?", "ss", [$username, $old_password]);

    if ($result === false) { 
        error_log("Error executing query: " . $conn->error);
    } 

    if ($result->num_rows == 0) {
        echo json_encode(["status" => "error", "message" => "Invalid username or password."]);
    } else {
        $updateResult = executeQuery($conn, "UPDATE users SET password = ? WHERE username = ?", "ss", [$new_password, $username]);

        if ($updateResult === false) { 
            error_log("Error executing query: " . $conn->error);
        } 

        if ($updateResult) {
            echo json_encode(["status" => "success", "message" => "Password updated successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to update password."]);
        }
    }
} 
elseif (isset($_POST["reg_username"]) && !empty($_POST["reg_username"]) && isset($_POST["reg_password"]) && !empty($_POST["reg_password"]) && isset($_POST["reg_type"]) && !empty($_POST["reg_type"])) {
    $reg_username = $_POST["reg_username"];
    $reg_password = $_POST["reg_password"];
    $reg_type = $_POST["reg_type"];

    $result = executeQuery($conn, "SELECT * FROM users WHERE BINARY username = ?", "s", [$reg_username]);

    if ($result === false) { 
        error_log("Error executing query: " . $conn->error);
    } 

    if ($result->num_rows > 0) {
        echo json_encode(["status" => "error", "message" => "Username already exists."]);
    } else {
        $insertResult = executeQuery($conn, "INSERT INTO users (username, password, type) VALUES (?, ?, ?)", "sss", [$reg_username, $reg_password, $reg_type]);

        if ($insertResult === false) { 
            error_log("Error executing query: " . $conn->error);
        }

        if ($insertResult) {
            echo json_encode(["status" => "success", "message" => "User registered successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to register user"]);
        }
    }
} else {
    echo json_encode(["status" => "error", "message" => "All fields are required."]);
}
?>
