<?php 
// Include tenant-specific config if it exists
if (file_exists('../../'.$_REQUEST['tenant'].'/config.php')) {
    require_once('../../'.$_REQUEST['tenant'].'/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
}

// Handle password update
$token = $_POST['token'];
$email = $_POST['email'];
$newPassword = $_POST['new_password'];
$confirmPassword = $_POST['confirm_password'];
$type = $_POST['type']; // User type: surveyor, contractors, admins, client

// Validate passwords
if ($newPassword !== $confirmPassword) {
    echo json_encode(['status' => 'error', 'message' => 'Passwords do not match']);
    exit();
}

// Check if the token is valid and has not expired
$stmt = $con->prepare("SELECT * FROM password_resets WHERE email = ? AND token = ? AND expires_at > NOW() AND user_type = ?");
$stmt->bind_param('sss', $email, $token, $type);
$stmt->execute();
$result = $stmt->get_result();
$resetRequest = $result->fetch_assoc();

if (!$resetRequest) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid or expired token']);
    exit();
}

// Update the password in the respective user table.
$userSources = [
    'surveyor' => ['table' => 'surveyor', 'email_column' => 'email'],
    'contractors' => ['table' => 'contractors', 'email_column' => 'email'],
    'admins' => ['table' => 'admins', 'email_column' => 'email'],
    'client' => ['table' => 'client_users', 'email_column' => 'username'],
];

if (!isset($userSources[$type])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid user type']);
    exit();
}

$table = $userSources[$type]['table'];
$emailColumn = $userSources[$type]['email_column'];

$stmt = $con->prepare("UPDATE `$table` SET password = AES_ENCRYPT(?, ?) WHERE `$emailColumn` = ?");
if ($stmt) {
    $stmt->bind_param('sss', $newPassword, $email, $email);
    $stmt->execute();
    $stmt->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Error updating password: ' . $con->error]);
    exit();
}

// Delete the reset token
$stmt = $con->prepare("DELETE FROM password_resets WHERE email = ? AND user_type = ?");
$stmt->bind_param('ss', $email, $type);
$stmt->execute();
$stmt->close();

echo json_encode(['status' => 'success']);
$con->close();
?>
